import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import axios from 'axios';
import { Upload, Download, FileSpreadsheet, AlertCircle, CheckCircle2, XCircle, Loader2 } from 'lucide-react';
import { useState, useRef } from 'react';
import { toast } from 'sonner';

interface ExcelImportDialogProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onSuccess?: () => void;
    importUrl: string;
    templateUrl: string;
    title?: string;
    description?: string;
}

interface ImportSummary {
    success_count: number;
    error_count: number;
    total_processed: number;
    errors?: any[];
    failures?: any[];
}

export function ExcelImportDialog({
    open,
    onOpenChange,
    onSuccess,
    importUrl,
    templateUrl,
    title = 'Import Data dari Excel',
    description = 'Upload file Excel untuk mengimport data dalam jumlah banyak',
}: ExcelImportDialogProps) {
    const [file, setFile] = useState<File | null>(null);
    const [isUploading, setIsUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [summary, setSummary] = useState<ImportSummary | null>(null);
    const [errors, setErrors] = useState<any[]>([]);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const selectedFile = e.target.files?.[0];

        if (selectedFile) {
            // Validate file type
            const validTypes = [
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-excel',
            ];

            if (!validTypes.includes(selectedFile.type)) {
                toast.error('File harus berformat Excel (.xlsx atau .xls)');

                return;
            }

            // Validate file size (max 10MB)
            if (selectedFile.size > 10 * 1024 * 1024) {
                toast.error('Ukuran file maksimal 10MB');

                return;
            }

            setFile(selectedFile);
            setSummary(null);
            setErrors([]);
        }
    };

    const handleDownloadTemplate = async () => {
        try {
            const response = await axios.get(templateUrl, {
                responseType: 'blob',
            });

            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `template_import_${Date.now()}.xlsx`);
            document.body.appendChild(link);
            link.click();
            link.remove();
            window.URL.revokeObjectURL(url);

            toast.success('Template berhasil didownload');
        } catch (error) {
            toast.error('Gagal mendownload template');
            console.error(error);
        }
    };

    const handleUpload = async () => {
        if (!file) {
            toast.error('Pilih file terlebih dahulu');

            return;
        }

        setIsUploading(true);
        setUploadProgress(0);
        setSummary(null);
        setErrors([]);

        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await axios.post(importUrl, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
                onUploadProgress: (progressEvent) => {
                    const progress = progressEvent.total
                        ? Math.round((progressEvent.loaded * 100) / progressEvent.total)
                        : 0;
                    setUploadProgress(progress);
                },
            });

            setSummary(response.data.summary);

            if (response.data.success) {
                toast.success(response.data.message);
                onSuccess?.();

                // Reset after success
                setTimeout(() => {
                    handleClose();
                }, 2000);
            } else {
                toast.warning(response.data.message);
                setErrors(response.data.summary?.errors || []);
            }
        } catch (error: any) {
            const errorMessage = error.response?.data?.message || 'Gagal mengimport file';
            toast.error(errorMessage);

            if (error.response?.data?.summary) {
                setSummary(error.response.data.summary);
                setErrors(error.response.data.summary.errors || []);
            }
        } finally {
            setIsUploading(false);
        }
    };

    const handleClose = () => {
        setFile(null);
        setSummary(null);
        setErrors([]);
        setUploadProgress(0);

        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }

        onOpenChange(false);
    };

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <FileSpreadsheet className="h-5 w-5" />
                        {title}
                    </DialogTitle>
                    <DialogDescription>{description}</DialogDescription>
                </DialogHeader>

                <div className="space-y-4">
                    {/* Download Template */}
                    <Alert>
                        <Download className="h-4 w-4" />
                        <AlertDescription className="flex items-center justify-between">
                            <span>Download template Excel untuk format yang benar</span>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={handleDownloadTemplate}
                            >
                                <Download className="mr-2 h-4 w-4" />
                                Download Template
                            </Button>
                        </AlertDescription>
                    </Alert>

                    {/* File Upload */}
                    <div className="space-y-2">
                        <Label htmlFor="file">File Excel</Label>
                        <Input
                            ref={fileInputRef}
                            id="file"
                            type="file"
                            accept=".xlsx,.xls"
                            onChange={handleFileChange}
                            disabled={isUploading}
                        />
                        {file && (
                            <p className="text-sm text-muted-foreground">
                                File terpilih: {file.name} ({(file.size / 1024).toFixed(2)} KB)
                            </p>
                        )}
                    </div>

                    {/* Upload Progress */}
                    {isUploading && (
                        <div className="space-y-2">
                            <div className="flex items-center justify-between text-sm">
                                <span>Mengupload...</span>
                                <span>{uploadProgress}%</span>
                            </div>
                            <Progress value={uploadProgress} />
                        </div>
                    )}

                    {/* Summary */}
                    {summary && (
                        <Alert variant={summary.error_count > 0 ? 'destructive' : 'default'}>
                            {summary.error_count > 0 ? (
                                <AlertCircle className="h-4 w-4" />
                            ) : (
                                <CheckCircle2 className="h-4 w-4" />
                            )}
                            <AlertDescription>
                                <div className="space-y-1">
                                    <p className="font-semibold">Hasil Import:</p>
                                    <div className="grid grid-cols-3 gap-2 text-sm">
                                        <div className="flex items-center gap-1">
                                            <CheckCircle2 className="h-3 w-3 text-green-600" />
                                            <span>Berhasil: {summary.success_count}</span>
                                        </div>
                                        <div className="flex items-center gap-1">
                                            <XCircle className="h-3 w-3 text-red-600" />
                                            <span>Gagal: {summary.error_count}</span>
                                        </div>
                                        <div className="flex items-center gap-1">
                                            <span>Total: {summary.total_processed}</span>
                                        </div>
                                    </div>
                                </div>
                            </AlertDescription>
                        </Alert>
                    )}

                    {/* Errors */}
                    {errors.length > 0 && (
                        <div className="space-y-2">
                            <Label className="text-destructive">Error Details:</Label>
                            <div className="max-h-40 overflow-y-auto border rounded-md p-3 space-y-2">
                                {errors.slice(0, 10).map((error, index) => (
                                    <div key={index} className="text-sm text-destructive">
                                        <p className="font-medium">Row {error.row || index + 1}:</p>
                                        <p className="text-xs">{error.error || JSON.stringify(error)}</p>
                                    </div>
                                ))}
                                {errors.length > 10 && (
                                    <p className="text-xs text-muted-foreground">
                                        ... dan {errors.length - 10} error lainnya
                                    </p>
                                )}
                            </div>
                        </div>
                    )}
                </div>

                <DialogFooter>
                    <Button variant="outline" onClick={handleClose} disabled={isUploading}>
                        Tutup
                    </Button>
                    <Button onClick={handleUpload} disabled={!file || isUploading}>
                        {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                        <Upload className="mr-2 h-4 w-4" />
                        Upload & Import
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
