import { useConfirm } from '@/Components/ConfirmDialog';
import Select from '@/Components/Select';
import AppLayout from '@/Layouts/AppLayout';
import Link from '@/Components/Link';
import { Head, router } from '@inertiajs/react';
import { ArrowLeft, Copy, Plus, Save, Trash2, Users } from 'lucide-react';
import { FormEvent, useState } from 'react';

interface Props {
    kategoriler: { id: number; ad: string }[];
    onerilen_kod?: string;
}

interface Satir {
    cari_kodu: string;
    unvan: string;
    kategori_id: number | '';
    vergi_dairesi: string;
    vergi_no: string;
    telefon: string;
    email: string;
    adres: string;
    notlar: string;
}

const bosSatir = (kategoriIdDefault: number | '' = ''): Satir => ({
    cari_kodu: '',
    unvan: '',
    kategori_id: kategoriIdDefault,
    vergi_dairesi: '',
    vergi_no: '',
    telefon: '',
    email: '',
    adres: '',
    notlar: '',
});

export default function CariToplu({ kategoriler, onerilen_kod }: Props) {
    const varsayilanKat = kategoriler[0]?.id ?? '';
    const [satirlar, setSatirlar] = useState<Satir[]>([bosSatir(varsayilanKat), bosSatir(varsayilanKat), bosSatir(varsayilanKat)]);
    const [processing, setProcessing] = useState(false);
    const confirm = useConfirm();

    const guncelle = (idx: number, alan: keyof Satir, deger: any) => {
        setSatirlar((s) => s.map((sa, i) => (i === idx ? { ...sa, [alan]: deger } : sa)));
    };

    const ekle = () => setSatirlar((s) => [...s, bosSatir(varsayilanKat)]);
    const sil = async (idx: number) => {
        const onay = await confirm({
            tip: 'tehlike', baslik: 'Satırı Sil',
            mesaj: <>Bu satırı silmek istediğine emin misin?</>,
            detay: 'Henüz kaydedilmemiş; girdiğin bilgiler kaybolacak.',
            onayMetni: 'Sil',
        });
        if (!onay) return;
        setSatirlar((s) => s.filter((_, i) => i !== idx));
    };
    const kopyala = (idx: number) => setSatirlar((s) => [
        ...s.slice(0, idx + 1),
        { ...s[idx], cari_kodu: '' },
        ...s.slice(idx + 1),
    ]);

    const dolu = satirlar.filter((s) => s.unvan.trim() && s.kategori_id);

    const kaydet = async (e: FormEvent) => {
        e.preventDefault();
        if (dolu.length === 0) {
            await confirm({
                tip: 'uyari', baslik: 'Geçerli Satır Yok',
                mesaj: 'En az bir satır için unvan ve kategori girilmelidir.',
                onayMetni: 'Tamam', iptalMetni: 'Kapat',
            });
            return;
        }
        const onay = await confirm({
            tip: 'soru', baslik: 'Toplu Cari Kaydetme',
            mesaj: <><strong>{dolu.length}</strong> cari aynı transaction'da kaydedilecek.</>,
            detay: 'Boş kod alanları otomatik üretilir. İşlem başarısız olursa hiçbiri kaydedilmez (atomik).',
            onayMetni: 'Kaydet',
        });
        if (!onay) return;
        setProcessing(true);
        router.post('/cariler/toplu/', { satirlar: dolu as any }, {
            onFinish: () => setProcessing(false),
        });
    };

    return (
        <AppLayout title="Toplu Cari Girişi">
            <Head title="Toplu Cari" />
            <Link href="/cariler/" className="mb-4 inline-flex items-center gap-1 text-sm text-slate-600 hover:text-slate-900">
                <ArrowLeft className="h-4 w-4" /> Cariler listesine dön
            </Link>

            <div className="mb-4 flex items-center gap-3 rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-900">
                <Users className="h-5 w-5 flex-shrink-0" />
                <div>
                    Birden fazla cariyi tek seferde kaydedin. Her satır için <strong>unvan</strong> ve <strong>kategori</strong> zorunlu;
                    diğer alanlar opsiyonel ve sonradan tek tek düzenlenebilir.
                    Cari kodu boş bırakılırsa otomatik üretilir (örn: <code className="rounded bg-white px-1">{onerilen_kod ?? '120.001'}</code>).
                    Tüm satırlar tek transaction'da kaydedilir.
                </div>
            </div>

            <form onSubmit={kaydet}>
                <div className="overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm">
                    <div className="overflow-x-auto">
                        <table className="w-full">
                            <thead className="bg-slate-50 text-xs uppercase text-slate-600">
                                <tr>
                                    <th className="px-3 py-3 text-left">#</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 140 }}>Cari Kodu</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 220 }}>Unvan *</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 180 }}>Kategori *</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 160 }}>Vergi Dairesi</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 140 }}>Vergi No / TC</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 140 }}>Telefon</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 180 }}>E-posta</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 200 }}>Adres</th>
                                    <th className="px-3 py-3 text-left" style={{ minWidth: 200 }}>Notlar</th>
                                    <th className="px-3 py-3 text-center" style={{ width: 80 }}>İşlem</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-200 text-sm">
                                {satirlar.map((s, i) => (
                                    <tr key={i} className="hover:bg-slate-50">
                                        <td className="px-3 py-2 text-xs text-slate-500">{i + 1}</td>
                                        <td className="px-3 py-2">
                                            <input type="text" value={s.cari_kodu}
                                                onChange={(e) => guncelle(i, 'cari_kodu', e.target.value)}
                                                placeholder="(Otomatik)"
                                                className="w-full rounded-lg border-slate-300 font-mono text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <input type="text" value={s.unvan}
                                                onChange={(e) => guncelle(i, 'unvan', e.target.value)}
                                                placeholder="Cari unvanı..."
                                                className="w-full rounded-lg border-slate-300 text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <Select
                                                value={s.kategori_id}
                                                onChange={(v) => guncelle(i, 'kategori_id', v ? Number(v) : '')}
                                                options={kategoriler.map((k) => ({ value: k.id, label: k.ad }))}
                                                placeholder="Kategori seçiniz..."
                                                hizliEkleUrl="/tanimlamalar/tip/cari-kategori"
                                                hizliEkleBaslik="Yeni Cari Kategorisi"
                                            />
                                        </td>
                                        <td className="px-3 py-2">
                                            <input type="text" value={s.vergi_dairesi}
                                                onChange={(e) => guncelle(i, 'vergi_dairesi', e.target.value)}
                                                placeholder="Örn: Beşiktaş VD"
                                                className="w-full rounded-lg border-slate-300 text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <input type="text" value={s.vergi_no}
                                                onChange={(e) => guncelle(i, 'vergi_no', e.target.value)}
                                                placeholder="10 haneli VN / 11 haneli TC"
                                                className="w-full rounded-lg border-slate-300 font-mono text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <input type="text" value={s.telefon}
                                                onChange={(e) => guncelle(i, 'telefon', e.target.value)}
                                                placeholder="0532 123 45 67"
                                                className="w-full rounded-lg border-slate-300 text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <input type="email" value={s.email}
                                                onChange={(e) => guncelle(i, 'email', e.target.value)}
                                                placeholder="ornek@firma.com"
                                                className="w-full rounded-lg border-slate-300 text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <input type="text" value={s.adres}
                                                onChange={(e) => guncelle(i, 'adres', e.target.value)}
                                                placeholder="Mahalle, sokak, ilçe, il..."
                                                className="w-full rounded-lg border-slate-300 text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <input type="text" value={s.notlar}
                                                onChange={(e) => guncelle(i, 'notlar', e.target.value)}
                                                placeholder="Not, açıklama veya detay..."
                                                className="w-full rounded-lg border-slate-300 text-sm" />
                                        </td>
                                        <td className="px-3 py-2">
                                            <div className="flex items-center justify-center gap-1">
                                                <button type="button" onClick={() => kopyala(i)} title="Kopyala"
                                                    className="rounded-md p-1 text-slate-500 hover:bg-blue-50 hover:text-blue-700">
                                                    <Copy className="h-4 w-4" />
                                                </button>
                                                <button type="button" onClick={() => sil(i)} disabled={satirlar.length === 1} title="Satır Sil"
                                                    className="rounded-md p-1 text-slate-500 hover:bg-rose-50 hover:text-rose-700 disabled:opacity-30">
                                                    <Trash2 className="h-4 w-4" />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    <div className="flex items-center justify-between border-t border-slate-200 bg-slate-50 px-5 py-3">
                        <button type="button" onClick={ekle}
                            className="inline-flex items-center gap-2 rounded-lg border border-blue-300 bg-white px-4 py-2 text-sm font-medium text-blue-700 hover:bg-blue-50">
                            <Plus className="h-4 w-4" /> Satır Ekle
                        </button>
                        <div className="flex items-center gap-4 text-sm">
                            <div className="text-slate-600">
                                <span className="font-medium">{satirlar.length}</span> satır
                            </div>
                            <div className="font-bold text-emerald-700">
                                {dolu.length} kayıt edilecek
                            </div>
                        </div>
                    </div>
                </div>

                <div className="mt-4 flex justify-end gap-3">
                    <Link href="/cariler/" className="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-50">
                        İptal
                    </Link>
                    <button type="submit" disabled={processing || dolu.length === 0}
                        className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-700 disabled:opacity-50">
                        <Save className="h-4 w-4" />
                        {processing ? 'Kaydediliyor...' : `${dolu.length} Cariyi Kaydet`}
                    </button>
                </div>
            </form>
        </AppLayout>
    );
}
