import React, { useState, useEffect, useRef } from 'react'
import {
    Box,
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Stepper,
    Step,
    StepLabel,
    Typography,
    TextField,
    MenuItem,
    Select,
    FormControl,
    InputLabel,
    Paper,
    InputAdornment,
    CircularProgress,
    Divider,
    Stack,
    FormControlLabel,
    Checkbox
} from '@mui/material'
import {
    CheckCircle as SuccessIcon,
    Error as ErrorIcon,
    Save as SaveIcon
} from '@mui/icons-material'
import Swal from 'sweetalert2'

interface MariaDbExportWizardProps {
    open: boolean
    onClose: () => void
    mariaDbVersions: any[]
}

const steps = [
    'Sunucu Seçimi',
    'Veritabanı Seçimi',
    'Dışa Aktarma Ayarları',
    'Özet ve İşlem'
]

const MariaDbExportWizard: React.FC<MariaDbExportWizardProps> = ({ open, onClose, mariaDbVersions }) => {
    const [activeStep, setActiveStep] = useState(0)
    const [selectedVersion, setSelectedVersion] = useState('')
    const [databases, setDatabases] = useState<string[]>([])
    const [selectedDb, setSelectedDb] = useState('')
    const [savePath, setSavePath] = useState('')
    const [compress, setCompress] = useState(true)
    const [rootPass, setRootPass] = useState('')
    const [loading, setLoading] = useState(false)
    const [logs, setLogs] = useState<string[]>([])
    const logEndRef = useRef<HTMLDivElement>(null)
    const [exportResult, setExportResult] = useState<{ success: boolean; message: string } | null>(null)

    useEffect(() => {
        if (open) {
            setActiveStep(0)
            setSelectedDb('')
            setSavePath('')
            setLogs([])
            setExportResult(null)
            const installedVersion = mariaDbVersions.find(v => v.status === 'installed')
            if (installedVersion) setSelectedVersion(installedVersion.id)
        }
    }, [open, mariaDbVersions])

    useEffect(() => {
        if (logEndRef.current) {
            logEndRef.current.scrollIntoView({ behavior: 'smooth' })
        }
    }, [logs])

    const nextStep = () => setActiveStep(prev => prev + 1)
    const prevStep = () => setActiveStep(prev => prev - 1)

    const handleStep1Next = async () => {
        if (!selectedVersion) {
            Swal.fire('Hata', 'Lütfen bir MariaDB sunucusu seçin.', 'error')
            return
        }
        setLoading(true)
        try {
            const dbs = await window.api.invoke('mariadb:export-wizard:list-dbs', { versionId: selectedVersion, rootPass })
            setDatabases(dbs)
            nextStep()
        } catch (err: any) {
            Swal.fire('Hata', 'Veritabanları listelenemedi: ' + err.message, 'error')
        } finally {
            setLoading(false)
        }
    }

    const handleSelectSavePath = async () => {
        const path = await window.api.invoke('dialog:save-file', [
            { name: compress ? 'Compressed SQL' : 'SQL File', extensions: [compress ? 'sql.gz' : 'sql'] }
        ])
        if (path) setSavePath(path)
    }

    const startExport = async () => {
        setLoading(true)
        setLogs(['[Sistem] Dışa aktarma işlemi başlatılıyor...'])

        const removeListener = window.api.onMariaDbExportLog((msg: string) => {
            setLogs(prev => [...prev, msg])
        })

        try {
            const result = await window.api.invoke('mariadb:export-wizard:start', {
                versionId: selectedVersion,
                dbName: selectedDb,
                savePath,
                compress,
                rootPass
            })
            setExportResult(result)
        } catch (err: any) {
            setExportResult({ success: false, message: err.message })
        } finally {
            setLoading(false)
            if (removeListener) removeListener()
        }
    }

    const renderStepContent = (step: number) => {
        switch (step) {
            case 0:
                return (
                    <Box sx={{ mt: 2 }}>
                        <Typography variant="body1" gutterBottom>Veritabanın hangi MariaDB sunucusunda olduğunu seçin.</Typography>
                        <FormControl fullWidth sx={{ mt: 2 }}>
                            <InputLabel>MariaDB Sunucusu</InputLabel>
                            <Select
                                value={selectedVersion}
                                label="MariaDB Sunucusu"
                                onChange={(e) => setSelectedVersion(e.target.value)}
                            >
                                {mariaDbVersions.filter(v => v.status === 'installed').map(v => (
                                    <MenuItem key={v.id} value={v.id}>
                                        MariaDB {v.version} (Port: {v.port})
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                        <TextField
                            label="Root Şifresi (Eğer varsa)"
                            fullWidth
                            sx={{ mt: 3 }}
                            value={rootPass}
                            type="password"
                            onChange={(e) => setRootPass(e.target.value)}
                            helperText="MariaDB 'root' kullanıcısının şifresi. Boşsa boş bırakın."
                        />
                    </Box>
                )
            case 1:
                return (
                    <Box sx={{ mt: 2 }}>
                        <Typography variant="body1" gutterBottom>Dışa aktarmak istediğiniz veritabanını seçin.</Typography>
                        <FormControl fullWidth sx={{ mt: 2 }}>
                            <InputLabel>Veritabanı</InputLabel>
                            <Select
                                value={selectedDb}
                                label="Veritabanı"
                                onChange={(e) => setSelectedDb(e.target.value)}
                            >
                                {databases.map(db => (
                                    <MenuItem key={db} value={db}>{db}</MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                        {databases.length === 0 && (
                            <Typography variant="caption" color="error" sx={{ mt: 1, display: 'block' }}>
                                Seçili sunucuda erişilebilir veritabanı bulunamadı.
                            </Typography>
                        )}
                    </Box>
                )
            case 2:
                return (
                    <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 3 }}>
                        <Typography variant="body1">Dosyanın kaydedileceği yeri ve formatını belirleyin.</Typography>
                        <FormControlLabel
                            control={<Checkbox checked={compress} onChange={(e) => setCompress(e.target.checked)} />}
                            label="Gzip ile Sıkıştır (.sql.gz)"
                        />
                        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
                            <TextField
                                fullWidth
                                variant="outlined"
                                value={savePath}
                                placeholder="Kaydedilecek dosya..."
                                disabled
                                InputProps={{
                                    startAdornment: (
                                        <InputAdornment position="start">
                                            <SaveIcon color="primary" />
                                        </InputAdornment>
                                    ),
                                }}
                            />
                            <Button variant="contained" onClick={handleSelectSavePath} sx={{ minWidth: '120px' }}>SEÇ</Button>
                        </Box>
                    </Box>
                )
            case 3:
                return (
                    <Box sx={{ mt: 2 }}>
                        {!exportResult ? (
                            <>
                                <Paper sx={{ p: 2, bgcolor: 'rgba(255,255,255,0.05)', borderRadius: 2 }}>
                                    <Typography variant="subtitle2" color="primary" sx={{ fontWeight: 'bold' }}>Özet Bilgiler</Typography>
                                    <Divider sx={{ my: 1 }} />
                                    <Stack spacing={1}>
                                        <Typography variant="body2"><strong>Sunucu:</strong> {selectedVersion}</Typography>
                                        <Typography variant="body2"><strong>Veritabanı:</strong> {selectedDb}</Typography>
                                        <Typography variant="body2"><strong>Hedef:</strong> {savePath}</Typography>
                                        <Typography variant="body2"><strong>Sıkıştırma:</strong> {compress ? 'Açık (.gz)' : 'Kapalı (.sql)'}</Typography>
                                    </Stack>
                                </Paper>
                                {loading && (
                                    <Box sx={{ mt: 3, p: 2, bgcolor: '#000', borderRadius: 2, maxHeight: '200px', overflowY: 'auto', fontFamily: 'monospace' }}>
                                        {logs.map((log, i) => (
                                            <Typography key={i} variant="caption" sx={{ display: 'block', color: log.includes('error') ? 'error.main' : 'success.main' }}>
                                                {log}
                                            </Typography>
                                        ))}
                                        <div ref={logEndRef} />
                                    </Box>
                                )}
                            </>
                        ) : (
                            <Box sx={{ textAlign: 'center', py: 3 }}>
                                {exportResult.success ? (
                                    <>
                                        <SuccessIcon color="success" sx={{ fontSize: 60 }} />
                                        <Typography variant="h6" sx={{ mt: 2 }}>İşlem Başarılı!</Typography>
                                        <Typography variant="body2" color="text.secondary">{exportResult.message}</Typography>
                                        <Button
                                            variant="outlined"
                                            sx={{ mt: 3 }}
                                            onClick={() => window.api.invoke('shell:open-path', savePath.substring(0, savePath.lastIndexOf('\\')))}
                                        >
                                            DOSYAYI GÖSTER
                                        </Button>
                                    </>
                                ) : (
                                    <>
                                        <ErrorIcon color="error" sx={{ fontSize: 60 }} />
                                        <Typography variant="h6" sx={{ mt: 2 }}>Hata Oluştu!</Typography>
                                        <Typography variant="body2" color="error">{exportResult.message}</Typography>
                                    </>
                                )}
                            </Box>
                        )}
                    </Box>
                )
            default:
                return 'Bilinmeyen adım'
        }
    }

    return (
        <Dialog open={open} onClose={loading ? undefined : onClose} maxWidth="sm" fullWidth>
            <DialogTitle>MariaDB Veritabanı Dışa Aktarma Sihirbazı</DialogTitle>
            <DialogContent>
                <Stepper activeStep={activeStep} orientation="horizontal" sx={{ pt: 2, pb: 4 }}>
                    {steps.map((label) => (
                        <Step key={label}>
                            <StepLabel>{label}</StepLabel>
                        </Step>
                    ))}
                </Stepper>

                {renderStepContent(activeStep)}

            </DialogContent>
            <DialogActions>
                <Button onClick={onClose} disabled={loading}>KAPAT</Button>
                <Box sx={{ flexGrow: 1 }} />
                {activeStep > 0 && activeStep < 3 && !exportResult && (
                    <Button onClick={prevStep} disabled={loading}>GERİ</Button>
                )}
                {activeStep === 0 && (
                    <Button variant="contained" onClick={handleStep1Next} disabled={loading}>
                        {loading ? <CircularProgress size={24} /> : 'İLERİ'}
                    </Button>
                )}
                {activeStep === 1 && (
                    <Button variant="contained" onClick={nextStep} disabled={!selectedDb}>İLERİ</Button>
                )}
                {activeStep === 2 && (
                    <Button variant="contained" onClick={nextStep} disabled={!savePath}>İLERİ</Button>
                )}
                {activeStep === 3 && !exportResult && (
                    <Button variant="contained" color="primary" onClick={startExport} disabled={loading}>
                        {loading ? <CircularProgress size={24} /> : 'EXPORTU BAŞLAT'}
                    </Button>
                )}
            </DialogActions>
        </Dialog>
    )
}

export default MariaDbExportWizard
