import { router } from '@inertiajs/react';
import { usePage } from '@inertiajs/react';
import { Alert, AlertDescription, AlertTitle } from '@ui/components/ui/alert';
import { Button } from '@ui/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@ui/components/ui/dialog';
import { Input } from '@ui/components/ui/input';
import { Label } from '@ui/components/ui/label';
import { Upload, Download, FileSpreadsheet, AlertCircle } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { useAppText } from '@/lib/app-text';

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

export function ExcelImportDialog({
    open,
    onOpenChange,
    importUrl,
    templateUrl,
    onImportSuccess,
}: ExcelImportDialogProps) {
    const { t: text } = useAppText();
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [isUploading, setIsUploading] = useState(false);

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

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

            if (!validTypes.includes(file.type)) {
                toast.error(text('fund_request.msg_invalid_excel'));

                return;
            }

            // Validate file size (max 10MB)
            if (file.size > 10 * 1024 * 1024) {
                toast.error(text('fund_request.msg_file_too_large'));

                return;
            }

            setSelectedFile(file);
        }
    };

    const handleDownloadTemplate = () => {
        window.location.href = templateUrl;
        toast.success(text('fund_request.msg_template_download_started'));
    };

    const handleImport = () => {
        if (!selectedFile) {
            toast.error(text('fund_request.msg_select_file_first'));

            return;
        }

        setIsUploading(true);

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

        router.post(importUrl, formData, {
            preserveState: true,
            preserveScroll: true,
            onSuccess: (page) => {
                const flash = (page.props as any).flash;
                const errors = flash?.import_errors;
                const hasError = flash?.error || (errors && errors.length > 0);

                if (hasError) {
                    if (errors && errors.length > 0) {
                        toast.warning(text('fund_request.msg_import_with_issues', { count: errors.length }));
                    } else if (flash?.error) {
                        toast.error(flash.error);
                    }
                    // Modal remains open to show error alert
                } else {
                    toast.success(text('fund_request.msg_import_success'));
                    setSelectedFile(null);
                    onOpenChange(false);
                    onImportSuccess?.();
                }
            },
            onError: (errors) => {
                console.error('Import errors:', errors);
                toast.error(text('fund_request.msg_import_failed'));
            },
            onFinish: () => {
                setIsUploading(false);
            },
        });
    };

    const handleClose = () => {
        if (!isUploading) {
            setSelectedFile(null);
            onOpenChange(false);
        }
    };

    const { flash } = usePage().props as any;
    const importErrors = flash?.import_errors as string[] | undefined;

    return (
        <Dialog open={open} onOpenChange={handleClose}>
            <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-hidden flex flex-col">
                <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                        <FileSpreadsheet className="h-5 w-5" />
                        {text('fund_request.import_title')}
                    </DialogTitle>
                    <DialogDescription>
                        {text('fund_request.import_description')}
                    </DialogDescription>
                </DialogHeader>

                <div className="flex-1 overflow-y-auto py-4 space-y-4 px-1">
                    {/* Error Alerts if any */}
                    {importErrors && importErrors.length > 0 && (
                        <Alert className="border-destructive/30 bg-destructive/10 text-destructive">
                            <AlertCircle className="h-4 w-4 text-destructive" />
                            <AlertTitle className="font-bold">{text('fund_request.import_issues_title')}</AlertTitle>
                            <AlertDescription>
                                <div className="mt-2 text-xs font-mono max-h-[150px] overflow-y-auto space-y-1 text-destructive">
                                    {importErrors.map((err, idx) => (
                                        <div key={idx} className="border-b border-destructive/20 pb-1">
                                            {err}
                                        </div>
                                    ))}
                                </div>
                            </AlertDescription>
                        </Alert>
                    )}

                    {/* Download Template Section */}
                    <div className="rounded-lg border border-border bg-muted/50 p-4">
                        <div className="flex items-start gap-3">
                            <Download className="h-5 w-5 text-primary mt-0.5" />
                            <div className="flex-1">
                                <h4 className="font-medium text-sm mb-1">{text('fund_request.import_download_template_title')}</h4>
                                <p className="text-sm text-muted-foreground mb-3">
                                    {text('fund_request.import_download_template_desc')}
                                </p>
                                <Button
                                    type="button"
                                    variant="outline"
                                    size="sm"
                                    onClick={handleDownloadTemplate}
                                >
                                    <Download className="mr-2 h-4 w-4" />
                                    {text('fund_request.import_download_template_title')}
                                </Button>
                            </div>
                        </div>
                    </div>

                    {/* File Upload Section */}
                    <div className="space-y-2">
                        <Label htmlFor="excel-file">{text('fund_request.import_select_file')}</Label>
                        <div className="flex gap-2">
                            <Input
                                id="excel-file"
                                type="file"
                                accept=".xlsx,.xls"
                                onChange={handleFileChange}
                                disabled={isUploading}
                                className="flex-1"
                            />
                            {selectedFile && (
                                <Button
                                    variant="outline"
                                    size="icon"
                                    onClick={() => setSelectedFile(null)}
                                    title={text('fund_request.import_clear_selection')}
                                >
                                    <AlertCircle className="h-4 w-4" />
                                </Button>
                            )}
                        </div>
                        {selectedFile && (
                            <p className="text-sm text-green-600 dark:text-green-400 font-medium">
                                {text('fund_request.import_ready', { name: selectedFile.name })}
                            </p>
                        )}
                    </div>

                    {/* Important Notes */}
                    <Alert>
                        <AlertCircle className="h-4 w-4" />
                        <AlertDescription className="text-sm">
                            <strong>{text('fund_request.import_rules_title')}</strong>
                            <ul className="list-disc list-inside mt-2 space-y-1 text-xs">
                                <li>{text('fund_request.import_rule_1')}</li>
                                <li>{text('fund_request.import_rule_2')}</li>
                                <li>{text('fund_request.import_rule_3')}</li>
                            </ul>
                        </AlertDescription>
                    </Alert>
                </div>

                <DialogFooter>
                    <Button
                        type="button"
                        variant="outline"
                        onClick={handleClose}
                        disabled={isUploading}
                    >
                        {text('common.btn_cancel')}
                    </Button>
                    <Button
                        type="button"
                        onClick={handleImport}
                        disabled={!selectedFile || isUploading}
                    >
                        {isUploading ? (
                            <>
                                <Upload className="mr-2 h-4 w-4 animate-spin" />
                                {text('common.msg_loading')}
                            </>
                        ) : (
                            <>
                                <Upload className="mr-2 h-4 w-4" />
                                {text('common.btn_import')}
                            </>
                        )}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
