import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { Building2, User, Heart, Baby, CheckCircle, AlertCircle } from 'lucide-react';

interface Staff {
    id: number;
    staff_no: string;
    full_name: string;
    job_title: string | null;
    phone: string | null;
    mobile_no: string | null;
    personal_email: string | null;
    address_line1: string | null;
    address_line2: string | null;
    city: string | null;
    state: string | null;
    postcode: string | null;
    company: { name: string } | null;
}

interface Spouse {
    id: number;
    full_name: string;
    ic_no: string | null;
    occupation: string | null;
    phone: string | null;
    status: string;
}

interface Child {
    id: number;
    full_name: string;
    ic_no: string | null;
    date_of_birth: string | null;
    gender: string | null;
}

interface Props {
    staff: Staff;
    spouses: Spouse[];
    children: Child[];
    token: string;
}

interface PageProps {
    flash: { success?: string; error?: string };
    [key: string]: unknown;
}

const TABS = [
    { key: 'contact', label: 'Update Contact', icon: User },
    { key: 'spouse', label: 'Add Spouse', icon: Heart },
    { key: 'child', label: 'Add Child', icon: Baby },
];

function Input({ label, name, value, onChange, type = 'text', required = false }: {
    label: string; name: string; value: string; onChange: (v: string) => void; type?: string; required?: boolean;
}) {
    return (
        <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">
                {label}{required && <span className="text-red-500 ml-0.5">*</span>}
            </label>
            <input type={type} name={name} value={value} onChange={e => onChange(e.target.value)} required={required}
                className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>
    );
}

export default function SelfServiceShow({ staff, spouses, children, token }: Props) {
    const { flash } = usePage<PageProps>().props;
    const [activeTab, setActiveTab] = useState('contact');

    const [contact, setContact] = useState({
        phone: staff.phone ?? '', mobile_no: staff.mobile_no ?? '', personal_email: staff.personal_email ?? '',
        address_line1: staff.address_line1 ?? '', address_line2: staff.address_line2 ?? '',
        city: staff.city ?? '', state: staff.state ?? '', postcode: staff.postcode ?? '', notes: '',
    });

    const [spouse, setSpouse] = useState({
        full_name: '', ic_no: '', date_of_birth: '', nationality: 'Malaysian',
        occupation: '', phone: '', marriage_date: '', notes: '',
    });

    const [child, setChild] = useState({
        full_name: '', ic_no: '', date_of_birth: '', gender: '',
        is_dependent: true, is_student: false, notes: '',
    });

    function submitContact(e: React.FormEvent) {
        e.preventDefault();
        router.post(`/hr-portal/self-service/${token}/contact`, contact);
    }

    function submitSpouse(e: React.FormEvent) {
        e.preventDefault();
        router.post(`/hr-portal/self-service/${token}/spouse`, spouse, {
            onSuccess: () => setSpouse({ full_name: '', ic_no: '', date_of_birth: '', nationality: 'Malaysian', occupation: '', phone: '', marriage_date: '', notes: '' }),
        });
    }

    function submitChild(e: React.FormEvent) {
        e.preventDefault();
        router.post(`/hr-portal/self-service/${token}/child`, child, {
            onSuccess: () => setChild({ full_name: '', ic_no: '', date_of_birth: '', gender: '', is_dependent: true, is_student: false, notes: '' }),
        });
    }

    return (
        <>
            <Head title="Staff Self-Service" />

            <div className="min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900">
                {/* Header */}
                <header className="border-b border-slate-700/50 bg-slate-900/50 backdrop-blur-sm">
                    <div className="mx-auto max-w-3xl px-4 py-4 flex items-center gap-3">
                        <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-blue-600 shadow-lg">
                            <Building2 className="h-5 w-5 text-white" />
                        </div>
                        <div>
                            <p className="text-sm font-semibold text-white">HR Portal</p>
                            <p className="text-xs text-slate-400">Staff Self-Service</p>
                        </div>
                    </div>
                </header>

                <main className="mx-auto max-w-3xl px-4 py-8 space-y-6">
                    {/* Staff info card */}
                    <div className="rounded-xl border border-slate-700 bg-slate-800/60 p-5">
                        <div className="flex items-center gap-4">
                            <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-blue-600 text-lg font-bold text-white">
                                {staff.full_name.charAt(0).toUpperCase()}
                            </div>
                            <div>
                                <p className="font-semibold text-white">{staff.full_name}</p>
                                <p className="text-sm text-slate-400">
                                    {staff.staff_no}{staff.job_title ? ` · ${staff.job_title}` : ''}{staff.company ? ` · ${staff.company.name}` : ''}
                                </p>
                            </div>
                        </div>

                        {(spouses.length > 0 || children.length > 0) && (
                            <div className="mt-4 grid grid-cols-2 gap-3">
                                {spouses.length > 0 && (
                                    <div className="rounded-lg bg-slate-700/50 p-3">
                                        <p className="text-xs font-medium text-slate-400 mb-1">Spouses on record</p>
                                        {spouses.map(s => (
                                            <p key={s.id} className="text-sm text-white">{s.full_name}</p>
                                        ))}
                                    </div>
                                )}
                                {children.length > 0 && (
                                    <div className="rounded-lg bg-slate-700/50 p-3">
                                        <p className="text-xs font-medium text-slate-400 mb-1">Children on record</p>
                                        {children.map(c => (
                                            <p key={c.id} className="text-sm text-white">{c.full_name}</p>
                                        ))}
                                    </div>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Flash messages */}
                    {flash?.success && (
                        <div className="flex items-center gap-3 rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-400">
                            <CheckCircle className="h-5 w-5 flex-shrink-0" />
                            {flash.success}
                        </div>
                    )}
                    {flash?.error && (
                        <div className="flex items-center gap-3 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-400">
                            <AlertCircle className="h-5 w-5 flex-shrink-0" />
                            {flash.error}
                        </div>
                    )}

                    {/* Tabs */}
                    <div className="flex gap-1 rounded-xl border border-slate-700 bg-slate-800/60 p-1">
                        {TABS.map(tab => (
                            <button key={tab.key} onClick={() => setActiveTab(tab.key)}
                                className={`flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors flex-1 justify-center ${
                                    activeTab === tab.key ? 'bg-blue-600 text-white shadow-sm' : 'text-slate-400 hover:text-white'
                                }`}>
                                <tab.icon className="h-4 w-4" />
                                <span className="hidden sm:inline">{tab.label}</span>
                            </button>
                        ))}
                    </div>

                    <p className="text-xs text-slate-500 text-center">
                        All submissions are reviewed and approved by HR before any changes take effect.
                    </p>

                    {/* Contact form */}
                    {activeTab === 'contact' && (
                        <form onSubmit={submitContact} className="rounded-xl border border-slate-700 bg-slate-800/60 p-6 space-y-4">
                            <h2 className="text-sm font-semibold text-white">Update Contact Information</h2>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                {([
                                    ['phone', 'Phone', 'tel'],
                                    ['mobile_no', 'Mobile', 'tel'],
                                    ['personal_email', 'Personal Email', 'email'],
                                    ['address_line1', 'Address Line 1', 'text'],
                                    ['address_line2', 'Address Line 2', 'text'],
                                    ['city', 'City', 'text'],
                                    ['state', 'State', 'text'],
                                    ['postcode', 'Postcode', 'text'],
                                ] as [string, string, string][]).map(([key, label, type]) => (
                                    <div key={key} className={key === 'address_line1' || key === 'address_line2' ? 'sm:col-span-2' : ''}>
                                        <label className="block text-xs font-medium text-slate-400 mb-1">{label}</label>
                                        <input type={type} value={(contact as Record<string, string>)[key]}
                                            onChange={e => setContact(c => ({ ...c, [key]: e.target.value }))}
                                            className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                    </div>
                                ))}
                                <div className="sm:col-span-2">
                                    <label className="block text-xs font-medium text-slate-400 mb-1">Notes (optional)</label>
                                    <textarea value={contact.notes} onChange={e => setContact(c => ({ ...c, notes: e.target.value }))} rows={2}
                                        placeholder="Any notes for HR..."
                                        className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                </div>
                            </div>
                            <button type="submit" className="w-full rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-blue-700 transition-colors">
                                Submit for Review
                            </button>
                        </form>
                    )}

                    {/* Spouse form */}
                    {activeTab === 'spouse' && (
                        <form onSubmit={submitSpouse} className="rounded-xl border border-slate-700 bg-slate-800/60 p-6 space-y-4">
                            <h2 className="text-sm font-semibold text-white">Add Spouse</h2>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                {([
                                    ['full_name', 'Full Name', 'text', true],
                                    ['ic_no', 'IC No', 'text', false],
                                    ['date_of_birth', 'Date of Birth', 'date', false],
                                    ['nationality', 'Nationality', 'text', false],
                                    ['occupation', 'Occupation', 'text', false],
                                    ['phone', 'Phone', 'tel', false],
                                    ['marriage_date', 'Marriage Date', 'date', false],
                                ] as [string, string, string, boolean][]).map(([key, label, type, req]) => (
                                    <div key={key}>
                                        <label className="block text-xs font-medium text-slate-400 mb-1">
                                            {label}{req && <span className="text-red-400 ml-0.5">*</span>}
                                        </label>
                                        <input type={type} value={(spouse as Record<string, string>)[key]}
                                            onChange={e => setSpouse(s => ({ ...s, [key]: e.target.value }))} required={req}
                                            className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                    </div>
                                ))}
                                <div className="sm:col-span-2">
                                    <label className="block text-xs font-medium text-slate-400 mb-1">Notes (optional)</label>
                                    <textarea value={spouse.notes} onChange={e => setSpouse(s => ({ ...s, notes: e.target.value }))} rows={2}
                                        className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                </div>
                            </div>
                            <button type="submit" className="w-full rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-blue-700 transition-colors">
                                Submit for Review
                            </button>
                        </form>
                    )}

                    {/* Child form */}
                    {activeTab === 'child' && (
                        <form onSubmit={submitChild} className="rounded-xl border border-slate-700 bg-slate-800/60 p-6 space-y-4">
                            <h2 className="text-sm font-semibold text-white">Add Child</h2>
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <div>
                                    <label className="block text-xs font-medium text-slate-400 mb-1">Full Name <span className="text-red-400">*</span></label>
                                    <input value={child.full_name} onChange={e => setChild(c => ({ ...c, full_name: e.target.value }))} required
                                        className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                </div>
                                <div>
                                    <label className="block text-xs font-medium text-slate-400 mb-1">IC No</label>
                                    <input value={child.ic_no} onChange={e => setChild(c => ({ ...c, ic_no: e.target.value }))}
                                        className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                </div>
                                <div>
                                    <label className="block text-xs font-medium text-slate-400 mb-1">Date of Birth</label>
                                    <input type="date" value={child.date_of_birth} onChange={e => setChild(c => ({ ...c, date_of_birth: e.target.value }))}
                                        className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                </div>
                                <div>
                                    <label className="block text-xs font-medium text-slate-400 mb-1">Gender</label>
                                    <select value={child.gender} onChange={e => setChild(c => ({ ...c, gender: e.target.value }))}
                                        className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                                        <option value="">— Select —</option>
                                        <option value="male">Male</option>
                                        <option value="female">Female</option>
                                    </select>
                                </div>
                                <div className="flex items-center gap-3">
                                    <label className="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" checked={child.is_dependent} onChange={e => setChild(c => ({ ...c, is_dependent: e.target.checked }))}
                                            className="h-4 w-4 rounded border-slate-600 accent-blue-600" />
                                        <span className="text-sm text-slate-300">Dependent</span>
                                    </label>
                                    <label className="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" checked={child.is_student} onChange={e => setChild(c => ({ ...c, is_student: e.target.checked }))}
                                            className="h-4 w-4 rounded border-slate-600 accent-blue-600" />
                                        <span className="text-sm text-slate-300">Student</span>
                                    </label>
                                </div>
                                <div className="sm:col-span-2">
                                    <label className="block text-xs font-medium text-slate-400 mb-1">Notes (optional)</label>
                                    <textarea value={child.notes} onChange={e => setChild(c => ({ ...c, notes: e.target.value }))} rows={2}
                                        className="w-full rounded-lg border border-slate-600 bg-slate-700 px-3 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                </div>
                            </div>
                            <button type="submit" className="w-full rounded-lg bg-blue-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-blue-700 transition-colors">
                                Submit for Review
                            </button>
                        </form>
                    )}
                </main>
            </div>
        </>
    );
}
