import { Head, Link, useForm } from '@inertiajs/react';
import {
    AlertCircle,
    CheckCircle2,
    Download,
    Home,
    Mail,
    MapPin,
    MessageCircle,
    Plus,
    Save,
    Send,
    ShieldCheck,
    Trash2,
    UserRound,
    Users,
} from 'lucide-react';
import StudentLayout from '@/layouts/StudentLayout';
import type { ProfileCompletion, StudentGuardian, StudentProfile, SyncedStudent } from '@/types';

interface Props {
    student: SyncedStudent & { synced_class?: { id: number; name: string } | null };
    profile: StudentProfile;
    completion: ProfileCompletion;
}

type GuardianForm = Omit<StudentGuardian, 'id'>;

const emptyGuardian = (primary = false): GuardianForm => ({
    relationship: 'father',
    full_name: '',
    phone: '',
    whatsapp_phone: '',
    occupation: '',
    same_address: true,
    address: '',
    is_primary_contact: primary,
    is_emergency_contact: false,
});

const statusConfig = {
    draft: { label: 'Draft', className: 'bg-slate-500/10 text-slate-300 border-slate-500/30' },
    submitted: { label: 'Menunggu verifikasi', className: 'bg-sky-500/10 text-sky-300 border-sky-500/30' },
    verified: { label: 'Terverifikasi', className: 'bg-emerald-500/10 text-emerald-300 border-emerald-500/30' },
    revision_requested: { label: 'Perlu revisi', className: 'bg-amber-500/10 text-amber-300 border-amber-500/30' },
    not_started: { label: 'Belum diisi', className: 'bg-slate-500/10 text-slate-300 border-slate-500/30' },
};

export default function StudentProfileEdit({ student, profile, completion }: Props) {
    const { data, setData, post, processing, errors } = useForm({
        phone: profile.phone ?? '',
        whatsapp_phone: profile.whatsapp_phone ?? '',
        email: profile.email ?? '',
        address_line: profile.address_line ?? '',
        rt: profile.rt ?? '',
        rw: profile.rw ?? '',
        village: profile.village ?? '',
        district: profile.district ?? '',
        city: profile.city ?? '',
        province: profile.province ?? '',
        postal_code: profile.postal_code ?? '',
        living_with: profile.living_with ?? '',
        transportation: profile.transportation ?? '',
        guardians: (profile.guardians?.length
            ? profile.guardians.map((guardian) => ({
                relationship: guardian.relationship,
                full_name: guardian.full_name ?? '',
                phone: guardian.phone ?? '',
                whatsapp_phone: guardian.whatsapp_phone ?? '',
                occupation: guardian.occupation ?? '',
                same_address: guardian.same_address,
                address: guardian.address ?? '',
                is_primary_contact: guardian.is_primary_contact,
                is_emergency_contact: guardian.is_emergency_contact,
            }))
            : [emptyGuardian(true)]) as GuardianForm[],
    });

    const status = statusConfig[profile.status] ?? statusConfig.draft;

    const updateGuardian = <K extends keyof GuardianForm>(index: number, key: K, value: GuardianForm[K]) => {
        const guardians = [...data.guardians];
        guardians[index] = { ...guardians[index], [key]: value };
        if (key === 'is_primary_contact' && value === true) {
            guardians.forEach((guardian, guardianIndex) => {
                guardian.is_primary_contact = guardianIndex === index;
            });
        }
        setData('guardians', guardians);
    };

    const removeGuardian = (index: number) => {
        setData('guardians', data.guardians.filter((_, guardianIndex) => guardianIndex !== index));
    };

    const save = (submit: boolean) => {
        post(submit ? '/student/profile/submit' : '/student/profile/draft', {
            preserveScroll: true,
        });
    };

    return (
        <>
            <Head title="Biodata Saya" />

            <div className="mx-auto max-w-5xl space-y-5 pb-28 sm:space-y-6 sm:pb-8">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <h1 className="flex items-center gap-2 text-xl font-black text-text sm:text-3xl">
                            <UserRound className="h-6 w-6 text-primary-400" />
                            Biodata Saya
                        </h1>
                        <p className="mt-1 text-xs text-text-muted sm:text-sm">
                            Lengkapi data kontak dan orang tua/wali untuk memudahkan komunikasi sekolah.
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        {profile.id && (
                            <>
                                <a
                                    href="/student/profile/export"
                                    className="inline-flex items-center gap-1.5 rounded-xl border border-border bg-surface px-3 py-2 text-xs font-semibold text-text hover:bg-surface-hover"
                                >
                                    <Download className="h-4 w-4" />
                                    XLSX
                                </a>
                                <a
                                    href="/student/profile/export/docx"
                                    className="inline-flex items-center gap-1.5 rounded-xl border border-primary-500/30 bg-primary-500/10 px-3 py-2 text-xs font-semibold text-primary-300 hover:bg-primary-500/20"
                                >
                                    <Download className="h-4 w-4" />
                                    DOCX
                                </a>
                            </>
                        )}
                        <span className={`rounded-full border px-3 py-1.5 text-xs font-bold ${status.className}`}>
                            {status.label}
                        </span>
                    </div>
                </div>
                <p className="-mt-3 text-[11px] text-text-muted sm:text-xs">
                    Terakhir diperbarui: {profile.updated_at ? new Date(profile.updated_at).toLocaleString('id-ID') : '-'}
                    {' - '}
                    Terakhir diverifikasi: {profile.verified_at ? new Date(profile.verified_at).toLocaleString('id-ID') : '-'}
                </p>

                {profile.revision_notes && (
                    <div className="rounded-2xl border border-amber-500/30 bg-amber-500/10 p-4">
                        <div className="flex gap-3">
                            <AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-amber-400" />
                            <div>
                                <p className="text-sm font-bold text-amber-300">Catatan revisi</p>
                                <p className="mt-1 whitespace-pre-wrap text-sm text-amber-100/80">{profile.revision_notes}</p>
                            </div>
                        </div>
                    </div>
                )}

                <section className="glass rounded-2xl p-4 sm:p-6">
                    <div className="mb-4 flex items-center justify-between gap-3">
                        <div>
                            <h2 className="text-sm font-bold text-text sm:text-base">Kelengkapan biodata</h2>
                            <p className="text-xs text-text-muted">{completion.percentage}% lengkap</p>
                        </div>
                        <span className="text-2xl font-black text-primary-400">{completion.percentage}%</span>
                    </div>
                    <div className="h-2 overflow-hidden rounded-full bg-surface-hover">
                        <div
                            className="h-full rounded-full bg-linear-to-r from-primary-500 to-emerald-400 transition-all"
                            style={{ width: `${completion.percentage}%` }}
                        />
                    </div>
                    {completion.missing.length > 0 && (
                        <p className="mt-3 text-xs text-text-muted">
                            Masih perlu dilengkapi: {completion.missing.join(', ')}.
                        </p>
                    )}
                </section>

                <section className="glass rounded-2xl p-4 sm:p-6">
                    <div className="mb-5 flex items-center gap-2">
                        <ShieldCheck className="h-5 w-5 text-emerald-400" />
                        <div>
                            <h2 className="font-bold text-text">Identitas resmi</h2>
                            <p className="text-xs text-text-muted">Data ini berasal dari sinkronisasi sekolah dan tidak dapat diedit di sini.</p>
                        </div>
                    </div>
                    <div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2 lg:grid-cols-3">
                        <ReadOnlyField label="Nama lengkap" value={student.full_name} />
                        <ReadOnlyField label="NISN / NIS" value={`${student.nisn}${student.nis ? ` / ${student.nis}` : ''}`} />
                        <ReadOnlyField label="Kelas" value={student.synced_class?.name ?? '-'} />
                        <ReadOnlyField label="Jenis kelamin" value={student.gender === 'L' ? 'Laki-laki' : student.gender === 'P' ? 'Perempuan' : '-'} />
                        <ReadOnlyField label="Tempat lahir" value={student.birth_place ?? '-'} />
                        <ReadOnlyField label="Tanggal lahir" value={student.birth_date ?? '-'} />
                    </div>
                </section>

                <section className="glass rounded-2xl p-4 sm:p-6">
                    <SectionTitle icon={<Mail className="h-5 w-5" />} title="Kontak siswa" description="Semua kolom pada bagian ini opsional." />
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                        <FormField label="Nomor HP" error={errors.phone}>
                            <input value={data.phone} onChange={(event) => setData('phone', event.target.value)} placeholder="0812..." className="form-input w-full rounded-xl" inputMode="tel" />
                        </FormField>
                        <FormField label="Nomor WhatsApp" error={errors.whatsapp_phone}>
                            <input value={data.whatsapp_phone} onChange={(event) => setData('whatsapp_phone', event.target.value)} placeholder="0812..." className="form-input w-full rounded-xl" inputMode="tel" />
                        </FormField>
                        <FormField label="Email" error={errors.email}>
                            <input type="email" value={data.email} onChange={(event) => setData('email', event.target.value)} placeholder="nama@email.com" className="form-input w-full rounded-xl" />
                        </FormField>
                    </div>
                </section>

                <section className="glass rounded-2xl p-4 sm:p-6">
                    <SectionTitle icon={<MapPin className="h-5 w-5" />} title="Alamat tempat tinggal" description="Isi alamat yang sedang digunakan sekarang." />
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <FormField label="Jalan / Dusun / Lingkungan" error={errors.address_line} className="sm:col-span-2">
                            <textarea value={data.address_line} onChange={(event) => setData('address_line', event.target.value)} rows={3} className="form-input w-full resize-none rounded-xl" />
                        </FormField>
                        <div className="grid grid-cols-2 gap-3 sm:col-span-2 sm:max-w-sm">
                            <FormField label="RT" error={errors.rt}>
                                <input value={data.rt} onChange={(event) => setData('rt', event.target.value)} className="form-input w-full rounded-xl" />
                            </FormField>
                            <FormField label="RW" error={errors.rw}>
                                <input value={data.rw} onChange={(event) => setData('rw', event.target.value)} className="form-input w-full rounded-xl" />
                            </FormField>
                        </div>
                        <FormField label="Desa / Kelurahan" error={errors.village}>
                            <input value={data.village} onChange={(event) => setData('village', event.target.value)} className="form-input w-full rounded-xl" />
                        </FormField>
                        <FormField label="Kecamatan" error={errors.district}>
                            <input value={data.district} onChange={(event) => setData('district', event.target.value)} className="form-input w-full rounded-xl" />
                        </FormField>
                        <FormField label="Kabupaten / Kota" error={errors.city}>
                            <input value={data.city} onChange={(event) => setData('city', event.target.value)} className="form-input w-full rounded-xl" />
                        </FormField>
                        <FormField label="Provinsi" error={errors.province}>
                            <input value={data.province} onChange={(event) => setData('province', event.target.value)} className="form-input w-full rounded-xl" />
                        </FormField>
                        <FormField label="Kode pos" error={errors.postal_code}>
                            <input value={data.postal_code} onChange={(event) => setData('postal_code', event.target.value)} inputMode="numeric" className="form-input w-full rounded-xl" />
                        </FormField>
                        <FormField label="Tinggal bersama" error={errors.living_with}>
                            <input value={data.living_with} onChange={(event) => setData('living_with', event.target.value)} placeholder="Orang tua / wali / lainnya" className="form-input w-full rounded-xl" />
                        </FormField>
                        <FormField label="Transportasi utama" error={errors.transportation}>
                            <input value={data.transportation} onChange={(event) => setData('transportation', event.target.value)} placeholder="Jalan kaki / motor / angkot" className="form-input w-full rounded-xl" />
                        </FormField>
                    </div>
                </section>

                <section className="glass rounded-2xl p-4 sm:p-6">
                    <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <SectionTitle icon={<Users className="h-5 w-5" />} title="Orang tua / wali" description="Tambahkan sesuai kondisi keluarga. Tidak harus selalu ayah dan ibu." />
                        <button
                            type="button"
                            onClick={() => setData('guardians', [...data.guardians, emptyGuardian()])}
                            disabled={data.guardians.length >= 5}
                            className="inline-flex items-center justify-center gap-1.5 rounded-xl bg-primary-500/10 px-3 py-2 text-xs font-bold text-primary-300 hover:bg-primary-500/20 disabled:opacity-40"
                        >
                            <Plus className="h-4 w-4" />
                            Tambah kontak
                        </button>
                    </div>

                    {errors.guardians && <p className="mb-3 rounded-xl bg-rose-500/10 p-3 text-xs text-rose-300">{errors.guardians}</p>}

                    <div className="space-y-4">
                        {data.guardians.map((guardian, index) => (
                            <div key={index} className="rounded-2xl border border-border bg-surface/40 p-4">
                                <div className="mb-4 flex items-center justify-between">
                                    <p className="text-sm font-bold text-text">Kontak {index + 1}</p>
                                    <div className="flex items-center gap-1">
                                        {whatsappLink(guardian.whatsapp_phone) && (
                                            <a
                                                href={whatsappLink(guardian.whatsapp_phone) ?? undefined}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="rounded-lg p-2 text-emerald-400 hover:bg-emerald-500/10"
                                                aria-label={`Buka WhatsApp kontak ${index + 1}`}
                                            >
                                                <MessageCircle className="h-4 w-4" />
                                            </a>
                                        )}
                                        <button type="button" onClick={() => removeGuardian(index)} className="rounded-lg p-2 text-rose-400 hover:bg-rose-500/10" aria-label={`Hapus kontak ${index + 1}`}>
                                            <Trash2 className="h-4 w-4" />
                                        </button>
                                    </div>
                                </div>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                    <FormField label="Hubungan">
                                        <select value={guardian.relationship} onChange={(event) => updateGuardian(index, 'relationship', event.target.value as GuardianForm['relationship'])} className="form-input w-full rounded-xl">
                                            <option value="father">Ayah</option>
                                            <option value="mother">Ibu</option>
                                            <option value="guardian">Wali</option>
                                            <option value="other">Lainnya</option>
                                        </select>
                                    </FormField>
                                    <FormField label="Nama lengkap" error={(errors as Record<string, string>)[`guardians.${index}.full_name`]}>
                                        <input value={guardian.full_name ?? ''} onChange={(event) => updateGuardian(index, 'full_name', event.target.value)} className="form-input w-full rounded-xl" />
                                    </FormField>
                                    <FormField label="Nomor telepon" error={(errors as Record<string, string>)[`guardians.${index}.phone`]}>
                                        <input value={guardian.phone ?? ''} onChange={(event) => updateGuardian(index, 'phone', event.target.value)} placeholder="0812..." inputMode="tel" className="form-input w-full rounded-xl" />
                                    </FormField>
                                    <FormField label="Nomor WhatsApp" error={(errors as Record<string, string>)[`guardians.${index}.whatsapp_phone`]}>
                                        <input value={guardian.whatsapp_phone ?? ''} onChange={(event) => updateGuardian(index, 'whatsapp_phone', event.target.value)} placeholder="Isi jika nomor dapat dihubungi via WA" inputMode="tel" className="form-input w-full rounded-xl" />
                                    </FormField>
                                    <FormField label="Pekerjaan">
                                        <input value={guardian.occupation ?? ''} onChange={(event) => updateGuardian(index, 'occupation', event.target.value)} className="form-input w-full rounded-xl" />
                                    </FormField>
                                    <div className="flex flex-col justify-end gap-2 pb-1">
                                        <CheckOption checked={guardian.is_primary_contact} onChange={(value) => updateGuardian(index, 'is_primary_contact', value)} label="Kontak utama" />
                                        <CheckOption checked={guardian.is_emergency_contact} onChange={(value) => updateGuardian(index, 'is_emergency_contact', value)} label="Kontak darurat" />
                                        <CheckOption checked={guardian.same_address} onChange={(value) => updateGuardian(index, 'same_address', value)} label="Alamat sama dengan siswa" />
                                    </div>
                                    {!guardian.same_address && (
                                        <FormField label="Alamat orang tua / wali" error={(errors as Record<string, string>)[`guardians.${index}.address`]} className="sm:col-span-2">
                                            <textarea value={guardian.address ?? ''} onChange={(event) => updateGuardian(index, 'address', event.target.value)} rows={2} className="form-input w-full resize-none rounded-xl" />
                                        </FormField>
                                    )}
                                </div>
                            </div>
                        ))}
                    </div>
                </section>

                <div className="app-eco-solid-surface mobile-safe-bottom mobile-safe-action-bar fixed inset-x-0 z-30 border-t border-border bg-surface/95 p-3 backdrop-blur-xl sm:static sm:rounded-2xl sm:border">
                    <div className="mx-auto flex max-w-5xl gap-2 sm:justify-end">
                        <Link href="/dashboard" className="inline-flex items-center justify-center rounded-xl border border-border px-3 py-2.5 text-xs font-bold text-text-muted hover:bg-surface-hover sm:px-4">
                            <Home className="mr-1.5 h-4 w-4" />
                            Kembali
                        </Link>
                        <button type="button" onClick={() => save(false)} disabled={processing} className="inline-flex flex-1 items-center justify-center gap-1.5 rounded-xl border border-primary-500/30 bg-primary-500/10 px-3 py-2.5 text-xs font-bold text-primary-300 hover:bg-primary-500/20 disabled:opacity-50 sm:flex-none sm:px-4">
                            <Save className="h-4 w-4" />
                            Simpan draft
                        </button>
                        <button type="button" onClick={() => save(true)} disabled={processing} className="inline-flex flex-1 items-center justify-center gap-1.5 rounded-xl bg-primary-500 px-3 py-2.5 text-xs font-bold text-white hover:bg-primary-400 disabled:opacity-50 sm:flex-none sm:px-5">
                            <Send className="h-4 w-4" />
                            Ajukan
                        </button>
                    </div>
                </div>

                {profile.status === 'verified' && (
                    <div className="flex items-center gap-2 text-xs text-emerald-300">
                        <CheckCircle2 className="h-4 w-4" />
                        Perubahan setelah verifikasi akan diajukan kembali untuk diperiksa.
                    </div>
                )}
            </div>
        </>
    );
}

function ReadOnlyField({ label, value }: { label: string; value: string }) {
    return (
        <div className="rounded-xl border border-border/60 bg-surface/40 px-3 py-2.5">
            <p className="text-[10px] font-bold uppercase tracking-wide text-text-muted">{label}</p>
            <p className="mt-1 break-words font-semibold text-text">{value}</p>
        </div>
    );
}

function SectionTitle({ icon, title, description }: { icon: React.ReactNode; title: string; description: string }) {
    return (
        <div className="flex items-start gap-2">
            <span className="mt-0.5 text-primary-400">{icon}</span>
            <div>
                <h2 className="font-bold text-text">{title}</h2>
                <p className="text-xs text-text-muted">{description}</p>
            </div>
        </div>
    );
}

function FormField({ label, error, className = '', children }: { label: string; error?: string; className?: string; children: React.ReactNode }) {
    return (
        <label className={`block space-y-1.5 ${className}`}>
            <span className="text-xs font-bold text-text-muted">{label}</span>
            {children}
            {error && <span className="block text-xs text-rose-400">{error}</span>}
        </label>
    );
}

function CheckOption({ checked, onChange, label }: { checked: boolean; onChange: (value: boolean) => void; label: string }) {
    return (
        <label className="flex cursor-pointer items-center gap-2 text-xs font-medium text-text">
            <input type="checkbox" checked={checked} onChange={(event) => onChange(event.target.checked)} className="rounded border-border text-primary-500 focus:ring-primary-500" />
            {label}
        </label>
    );
}

function whatsappLink(phone: string | null): string | null {
    const digits = (phone ?? '').replace(/\D/g, '');
    const normalized = digits.startsWith('0')
        ? `62${digits.slice(1)}`
        : digits.startsWith('8')
            ? `62${digits}`
            : digits;

    return /^628\d{7,12}$/.test(normalized) ? `https://wa.me/${normalized}` : null;
}

StudentProfileEdit.layout = (page: any) => <StudentLayout title="Biodata Saya" hideMobileDock>{page}</StudentLayout>;
