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

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

const steps = [
    'Veri Seçimi',
    'Sunucu Seçimi',
    'Veritabanı Yapılandırması',
    'Özet ve İşlem'
]

const MariaDbImportWizard: React.FC<MariaDbImportWizardProps> = ({ open, onClose, mariaDbVersions }) => {
    const [activeStep, setActiveStep] = useState(0)
    const [filePath, setFilePath] = useState('')
    const [selectedVersion, setSelectedVersion] = useState('')
    const [dbConfig, setDbConfig] = useState({
        dbName: '',
        user: '',
        pass: '',
        rootPass: ''
    })
    const [loading, setLoading] = useState(false)
    const [logs, setLogs] = useState<string[]>([])
    const logEndRef = useRef<HTMLDivElement>(null)
    const [importResult, setImportResult] = useState<{ success: boolean; message: string } | null>(null)

    useEffect(() => {
        if (open) {
            setActiveStep(0)
            setFilePath('')
            setLogs([])
            setImportResult(null)
            const installedVersion = mariaDbVersions.find(v => v.status === 'installed')
            if (installedVersion) setSelectedVersion(installedVersion.id)

            // Generate random credentials
            const randomStr = Math.random().toString(36).substring(2, 8)
            setDbConfig({
                dbName: `db_${randomStr}`,
                user: `user_${randomStr}`,
                pass: Math.random().toString(36).substring(2, 12),
                rootPass: ''
            })
        }
    }, [open, mariaDbVersions])

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

    const handleSelectFile = async () => {
        const path = await window.api.selectFile([
            { name: 'SQL & Archives', extensions: ['sql', 'zip', 'gz', 'tar'] }
        ])
        if (path) {
            setFilePath(path)
            // Try to guess DB name from file name
            const fileName = path.split(/[/\\]/).pop()?.split('.')[0] || ''
            if (fileName && !dbConfig.dbName.startsWith('db_')) {
                setDbConfig(prev => ({ ...prev, dbName: fileName }))
            }
        }
    }

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

    const handleStep2Next = () => {
        if (!selectedVersion) {
            Swal.fire('Hata', 'Lütfen bir MariaDB sunucusu seçin.', 'error')
            return
        }
        nextStep()
    }

    const handleStep3Next = async () => {
        if (!dbConfig.dbName || !dbConfig.user) {
            Swal.fire('Hata', 'Lütfen veritabanı adı ve kullanıcıyı doldurun.', 'error')
            return
        }

        setLoading(true)
        try {
            const { exists } = await window.api.checkMariaDbDb(selectedVersion, dbConfig.dbName, dbConfig.rootPass)
            if (exists) {
                const result = await Swal.fire({
                    title: 'Veritabanı Mevcut!',
                    text: `'${dbConfig.dbName}' veritabanı zaten var. Üzerine yazmak istiyor musunuz? Mevcut tüm veriler silinecektir!`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Evet, Üzerine Yaz',
                    cancelButtonText: 'Hayır, Vazgeç',
                    confirmButtonColor: '#d33'
                })
                if (!result.isConfirmed) return
            }
            nextStep()
        } catch (err: any) {
            Swal.fire('Hata', err.message, 'error')
        } finally {
            setLoading(false)
        }
    }

    const startImport = async () => {
        setLoading(true)
        setLogs(['[Sistem] İşlem başlatılıyor...'])

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

        try {
            const result = await window.api.startMariaDbImport({
                versionId: selectedVersion,
                filePath,
                dbName: dbConfig.dbName,
                user: dbConfig.user,
                pass: dbConfig.pass,
                rootPass: dbConfig.rootPass,
                overwrite: true // Logic handled by checkMariaDbDb before
            })
            setImportResult(result)
        } catch (err: any) {
            setImportResult({ success: false, message: err.message })
        } finally {
            setLoading(false)
            if (removeListener) removeListener()
        }
    }

    const renderStepContent = (step: number) => {
        switch (step) {
            case 0:
                return (
                    <Box sx={{ mt: 2, textAlign: 'center' }}>
                        <Typography variant="body1" gutterBottom>Lütfen yüklenecek olan .sql dosyasını veya arşivini (.zip, .tar.gz) seçin.</Typography>
                        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', mt: 3 }}>
                            <TextField
                                fullWidth
                                variant="outlined"
                                value={filePath}
                                placeholder="Dosya seçilmedi..."
                                disabled
                                InputProps={{
                                    startAdornment: (
                                        <InputAdornment position="start">
                                            <FileIcon color="primary" />
                                        </InputAdornment>
                                    ),
                                }}
                            />
                            <Button variant="contained" onClick={handleSelectFile} sx={{ minWidth: '120px' }}>SEÇ</Button>
                        </Box>
                    </Box>
                )
            case 1:
                return (
                    <Box sx={{ mt: 2 }}>
                        <Typography variant="body1" gutterBottom>Dosyanın hangi MariaDB sunucusuna yükleneceğini 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={dbConfig.rootPass}
                            type="password"
                            onChange={(e) => setDbConfig({ ...dbConfig, rootPass: e.target.value })}
                            helperText="MariaDB 'root' kullanıcısının mevcut şifresini girin. Boşsa boş bırakın."
                        />
                    </Box>
                )
            case 2:
                return (
                    <Box sx={{ mt: 2, display: 'flex', flexDirection: 'column', gap: 3 }}>
                        <Typography variant="body1">Veritabanı ve kullanıcı bilgilerini yapılandırın.</Typography>
                        <TextField
                            label="Veritabanı Adı"
                            fullWidth
                            value={dbConfig.dbName}
                            onChange={(e) => setDbConfig({ ...dbConfig, dbName: e.target.value })}
                        />
                        <TextField
                            label="Veritabanı Kullanıcısı"
                            fullWidth
                            value={dbConfig.user}
                            onChange={(e) => setDbConfig({ ...dbConfig, user: e.target.value })}
                        />
                        <TextField
                            label="Kullanıcı Şifresi"
                            fullWidth
                            value={dbConfig.pass}
                            type="text"
                            onChange={(e) => setDbConfig({ ...dbConfig, pass: e.target.value })}
                            InputProps={{
                                endAdornment: (
                                    <InputAdornment position="end">
                                        <IconButton onClick={() => setDbConfig({ ...dbConfig, pass: Math.random().toString(36).substring(2, 12) })}>
                                            <RefreshIcon fontSize="small" />
                                        </IconButton>
                                    </InputAdornment>
                                )
                            }}
                        />
                    </Box>
                )
            case 3:
                return (
                    <Box sx={{ mt: 2 }}>
                        {!importResult ? (
                            <>
                                <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>Dosya:</strong> {filePath.split(/[/\\]/).pop()}</Typography>
                                        <Typography variant="body2"><strong>Sunucu:</strong> {selectedVersion}</Typography>
                                        <Typography variant="body2"><strong>Veritabanı:</strong> {dbConfig.dbName}</Typography>
                                        <Typography variant="body2"><strong>Kullanıcı:</strong> {dbConfig.user}</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('fail') ? 'error.main' : 'success.main' }}>
                                                {log}
                                            </Typography>
                                        ))}
                                        <div ref={logEndRef} />
                                    </Box>
                                )}
                            </>
                        ) : (
                            <Box sx={{ textAlign: 'center', py: 3 }}>
                                {importResult.success ? (
                                    <>
                                        <SuccessIcon color="success" sx={{ fontSize: 60 }} />
                                        <Typography variant="h6" sx={{ mt: 2 }}>İşlem Başarılı!</Typography>
                                        <Typography variant="body2" color="text.secondary">{importResult.message}</Typography>
                                        <Paper sx={{ p: 2, mt: 3, textAlign: 'left', bgcolor: 'rgba(0,180,0,0.1)' }}>
                                            <Typography variant="caption" sx={{ fontWeight: 'bold' }}>Erişim Bilgileri:</Typography>
                                            <Typography variant="body2"><strong>Host:</strong> localhost</Typography>
                                            <Typography variant="body2"><strong>DB:</strong> {dbConfig.dbName}</Typography>
                                            <Typography variant="body2"><strong>User:</strong> {dbConfig.user}</Typography>
                                            <Typography variant="body2"><strong>Pass:</strong> {dbConfig.pass}</Typography>
                                        </Paper>
                                    </>
                                ) : (
                                    <>
                                        <ErrorIcon color="error" sx={{ fontSize: 60 }} />
                                        <Typography variant="h6" sx={{ mt: 2 }}>Hata Oluştu!</Typography>
                                        <Typography variant="body2" color="error">{importResult.message}</Typography>
                                        <Box sx={{ mt: 2, textAlign: 'left', bgcolor: '#000', p: 1, maxHeight: 150, overflowY: 'auto' }}>
                                            {logs.slice(-5).map((l, i) => <Typography key={i} variant="caption" sx={{ color: '#fff', display: 'block' }}>{l}</Typography>)}
                                        </Box>
                                    </>
                                )}
                            </Box>
                        )}
                    </Box>
                )
            default:
                return 'Bilinmeyen adım'
        }
    }

    return (
        <Dialog open={open} onClose={loading ? undefined : onClose} maxWidth="sm" fullWidth>
            <DialogTitle>MariaDB Hızlı Dump/Import 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 && !importResult && (
                    <Button onClick={prevStep} disabled={loading}>GERİ</Button>
                )}
                {activeStep === 0 && (
                    <Button variant="contained" onClick={nextStep} disabled={!filePath}>İLERİ</Button>
                )}
                {activeStep === 1 && (
                    <Button variant="contained" onClick={handleStep2Next}>İLERİ</Button>
                )}
                {activeStep === 2 && (
                    <Button variant="contained" onClick={handleStep3Next} disabled={loading}>
                        {loading ? <CircularProgress size={24} /> : 'ÖZETİ GÖR'}
                    </Button>
                )}
                {activeStep === 3 && !importResult && (
                    <Button variant="contained" color="primary" onClick={startImport} disabled={loading}>
                        {loading ? <CircularProgress size={24} /> : 'IMPORTU BAŞLAT'}
                    </Button>
                )}
            </DialogActions>
        </Dialog>
    )
}

export default MariaDbImportWizard
