'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { createManyAnggotaParlemen } from '@/lib/admin-actions';
import { uploadImage } from '@/lib/upload';
import { CheckCircle2, Upload, AlertCircle, PlayCircle, Users } from 'lucide-react';

interface BulkImportParlemenProps {
    isOpen: boolean;
    setIsOpen: (open: boolean) => void;
}

export default function BulkImportParlemen({ isOpen, setIsOpen }: BulkImportParlemenProps) {
    const [step, setStep] = useState(1);
    const [tsvData, setTsvData] = useState('');
    const [parsedData, setParsedData] = useState<any[]>([]);
    const [imageFiles, setImageFiles] = useState<Record<number, File | null>>({});
    const [isSubmitting, setIsSubmitting] = useState(false);

    const handleParse = () => {
        if (!tsvData.trim()) {
            toast.error('Data tidak boleh kosong');
            return;
        }

        const rows = tsvData.trim().split('\n');
        const parsed = rows.map((row) => {
            const cols = row.split('\t');
            return {
                nama: cols[0]?.trim() || '',
                jabatan: cols[1]?.trim() || '',
                komisi: cols[2]?.trim() || '',
                angkatan: cols[3]?.trim() || '',
            };
        }).filter(r => r.nama && r.jabatan && r.komisi && r.angkatan);

        if (parsed.length === 0) {
            toast.error('Format data tidak sesuai. Pastikan ada 4 kolom.');
            return;
        }

        setParsedData(parsed);
        setStep(2);
    };

    const handleFileChange = (index: number, file: File | null) => {
        setImageFiles((prev) => ({ ...prev, [index]: file }));
    };

    const handleSubmit = async () => {
        setIsSubmitting(true);
        try {
            const finalData = [];
            for (let i = 0; i < parsedData.length; i++) {
                const item = parsedData[i];
                const file = imageFiles[i];
                let fotoUrl = 'https://api.dicebear.com/9.x/avataaars/svg?seed=' + encodeURIComponent(item.nama) + '&backgroundColor=transparent'; // Placeholder
                
                if (file) {
                    fotoUrl = await uploadImage(file);
                }

                finalData.push({
                    nama: item.nama,
                    jabatan: item.jabatan,
                    komisi: item.komisi,
                    angkatan: item.angkatan,
                    fotoUrl: fotoUrl,
                    npm: null,
                    linkedinUrl: null,
                    instagramUrl: null
                });
            }

            const res = await createManyAnggotaParlemen(finalData);
            if (res.success) {
                toast.success(res.message);
                setIsOpen(false);
                window.location.reload();
            } else {
                toast.error(res.message);
            }
        } catch (e: any) {
            toast.error('Terjadi kesalahan: ' + e.message);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogContent className="max-w-[90vw] md:max-w-6xl max-h-[90vh] overflow-hidden flex flex-col">
                <DialogHeader>
                    <DialogTitle>Bulk Insert Parlemen</DialogTitle>
                    <DialogDescription>
                        Tambahkan banyak pengurus sekaligus dengan copy-paste dari Excel.
                    </DialogDescription>
                </DialogHeader>

                <div className="flex-1 overflow-y-auto pr-2 pb-4">
                    {step === 1 && (
                        <div className="space-y-4">
                            <div className="bg-blue-50 text-blue-800 p-4 rounded-lg text-sm flex gap-3">
                                <AlertCircle className="w-5 h-5 shrink-0" />
                                <div>
                                    <p className="font-semibold mb-1">Panduan Format</p>
                                    <p>Siapkan data di Excel/Google Sheets dengan 4 kolom secara berurutan:</p>
                                    <ul className="list-decimal pl-5 mt-2 space-y-1 font-mono bg-white/50 p-2 rounded">
                                        <li>Nama Lengkap</li>
                                        <li>Jabatan (KETUA_HIMPUNAN, WAKIL_KETUA_HIMPUNAN, KETUA, WAKIL_KETUA, STAF)</li>
                                        <li>Komisi (cth: Bidang Kaderisasi)</li>
                                        <li>Angkatan (Contoh: 2023)</li>
                                    </ul>
                                    <p className="mt-2">Lalu copy baris-baris tersebut dan paste ke dalam kotak di bawah ini.</p>
                                </div>
                            </div>
                            <textarea
                                className="w-full h-64 p-4 border border-slate-200 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                                placeholder="Paste data dari Excel di sini..."
                                value={tsvData}
                                onChange={(e) => setTsvData(e.target.value)}
                            />
                        </div>
                    )}

                    {step === 2 && (
                        <div className="space-y-4">
                            <div className="flex justify-between items-center bg-slate-50 p-3 rounded-lg border border-slate-200">
                                <div className="flex items-center gap-2 text-slate-700">
                                    <Users className="w-5 h-5 text-blue-600" />
                                    <span className="font-semibold">{parsedData.length} Data Terdeteksi</span>
                                </div>
                                <Button variant="outline" size="sm" onClick={() => setStep(1)}>
                                    Edit Data
                                </Button>
                            </div>
                            
                            <div className="bg-orange-50 text-orange-800 p-3 rounded-lg text-sm mb-4">
                                Anda dapat mengunggah foto profil untuk setiap anggota. Jika dikosongkan, sistem akan memberikan avatar default secara otomatis.
                            </div>

                            <div className="rounded-lg border border-slate-200 overflow-x-auto">
                                <table className="w-full text-sm text-left text-slate-600 min-w-max">
                                    <thead className="text-xs text-slate-700 uppercase bg-slate-50 border-b border-slate-200">
                                        <tr>
                                            <th className="px-4 py-3">Nama</th>
                                            <th className="px-4 py-3">Jabatan</th>
                                            <th className="px-4 py-3">Komisi</th>
                                            <th className="px-4 py-3">Angkatan</th>
                                            <th className="px-4 py-3 w-64">Foto Profil</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-200">
                                        {parsedData.map((item, index) => (
                                            <tr key={index} className="bg-white hover:bg-slate-50/50 transition-colors">
                                                <td className="px-4 py-3 font-medium text-slate-900">{item.nama}</td>
                                                <td className="px-4 py-3">{item.jabatan}</td>
                                                <td className="px-4 py-3">{item.divisi}</td>
                                                <td className="px-4 py-3">{item.angkatan}</td>
                                                <td className="px-4 py-3">
                                                    <Input
                                                        type="file"
                                                        accept="image/*"
                                                        className="h-8 text-xs file:h-8 file:py-1 file:px-2"
                                                        onChange={(e) => handleFileChange(index, e.target.files?.[0] || null)}
                                                    />
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}
                </div>

                <div className="pt-4 mt-2 border-t border-slate-100 flex justify-end gap-3 bg-white">
                    <Button variant="ghost" onClick={() => setIsOpen(false)} disabled={isSubmitting}>Batal</Button>
                    {step === 1 ? (
                        <Button onClick={handleParse} className="gap-2">
                            Lanjut Preview <PlayCircle className="w-4 h-4" />
                        </Button>
                    ) : (
                        <Button onClick={handleSubmit} disabled={isSubmitting} className="gap-2">
                            {isSubmitting ? (
                                'Memproses...'
                            ) : (
                                <>Simpan {parsedData.length} Data <CheckCircle2 className="w-4 h-4" /></>
                            )}
                        </Button>
                    )}
                </div>
            </DialogContent>
        </Dialog>
    );
}
