import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { TrendingDown, Users, Clock, UserCheck } from 'lucide-react';

interface Separation {
    id: number;
    separation_type: string;
    last_working_day: string;
    effective_date: string;
    reason: string | null;
    is_eligible_rehire: boolean;
    exit_remarks: string | null;
    staff: { id: number; full_name: string; staff_no: string | null; join_date: string | null; company: { name: string } | null } | null;
    approver: { name: string } | null;
}

interface Props {
    separations: Separation[];
    stats: { total: number; turnover_rate: number; avg_tenure_months: number; rehirable_pct: number };
    byType: Record<string, number>;
    byMonth: Record<string, number>;
    companies: { id: number; name: string }[];
    filters: { year: number; company_id?: string };
    years: number[];
}

const SEP_COLORS: Record<string, string> = {
    Resignation:  'bg-amber-50 text-amber-700',
    Termination:  'bg-red-50 text-red-700',
    Retirement:   'bg-blue-50 text-blue-700',
    Redundancy:   'bg-purple-50 text-purple-700',
    Mutual:       'bg-teal-50 text-teal-700',
};

export default function TurnoverIndex({ separations, stats, byType, byMonth, companies, filters, years }: Props) {
    const { auth, flash } = usePage<any>().props;
    const isSuperAdmin = auth?.user?.role === 'super_admin';
    const [year, setYear] = useState(String(filters.year));
    const [companyId, setCompanyId] = useState(filters.company_id ?? '');

    function applyFilters() {
        router.get('/hr-portal/turnover', { year, company_id: companyId }, { preserveState: true });
    }

    const maxMonth = Math.max(...Object.values(byMonth), 1);

    return (
        <AppLayout title="Staff Turnover">
            <Head title="Staff Turnover" />
            {flash?.success && <div className="mb-4 rounded-lg bg-green-50 px-4 py-2.5 text-sm text-green-700">{flash.success}</div>}

            {/* Filters */}
            <div className="mb-5 flex flex-wrap items-end gap-3">
                <div>
                    <label className="mb-1 block text-xs font-medium text-gray-500">Year</label>
                    <select value={year} onChange={e => setYear(e.target.value)} className="h-9 rounded-md border border-gray-200 bg-white px-3 text-sm">
                        {years.map(y => <option key={y} value={y}>{y}</option>)}
                    </select>
                </div>
                {isSuperAdmin && companies.length > 0 && (
                    <div>
                        <label className="mb-1 block text-xs font-medium text-gray-500">Company</label>
                        <select value={companyId} onChange={e => setCompanyId(e.target.value)} className="h-9 rounded-md border border-gray-200 bg-white px-3 text-sm">
                            <option value="">All Companies</option>
                            {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                        </select>
                    </div>
                )}
                <button onClick={applyFilters} className="h-9 rounded-md bg-blue-600 px-4 text-sm font-medium text-white hover:bg-blue-700">Apply</button>
            </div>

            {/* Stats */}
            <div className="mb-5 grid grid-cols-2 gap-3 sm:grid-cols-4">
                {([
                    { label: 'Total Separations', value: stats.total, icon: TrendingDown, color: 'text-red-600 bg-red-50', suffix: '' },
                    { label: 'Turnover Rate', value: `${stats.turnover_rate}%`, icon: Users, color: 'text-amber-600 bg-amber-50', suffix: '' },
                    { label: 'Avg Tenure at Exit', value: `${stats.avg_tenure_months}mo`, icon: Clock, color: 'text-blue-600 bg-blue-50', suffix: '' },
                    { label: 'Rehirable', value: `${stats.rehirable_pct}%`, icon: UserCheck, color: 'text-green-600 bg-green-50', suffix: '' },
                ] as const).map(s => (
                    <div key={s.label} className="rounded-xl border border-gray-100 bg-white p-4 shadow-sm">
                        <div className="flex items-center gap-3">
                            <div className={`flex h-9 w-9 items-center justify-center rounded-lg ${s.color}`}>
                                <s.icon className="h-4 w-4" />
                            </div>
                            <div>
                                <p className="text-xs text-gray-500">{s.label}</p>
                                <p className="text-xl font-bold text-gray-900">{s.value}</p>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            <div className="mb-5 grid grid-cols-1 gap-4 lg:grid-cols-2">
                {/* By type */}
                <div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
                    <h3 className="mb-4 text-sm font-semibold text-gray-800">By Separation Type</h3>
                    {Object.entries(byType).length === 0 ? <p className="text-sm text-gray-400">No data</p> : (
                        <div className="space-y-2">
                            {Object.entries(byType).map(([type, count]) => (
                                <div key={type} className="flex items-center justify-between">
                                    <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${SEP_COLORS[type] ?? 'bg-gray-100 text-gray-600'}`}>{type}</span>
                                    <span className="text-sm font-semibold text-gray-900">{count}</span>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                {/* By month */}
                <div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
                    <h3 className="mb-4 text-sm font-semibold text-gray-800">Monthly Trend ({year})</h3>
                    <div className="flex h-28 items-end gap-1.5">
                        {Object.entries(byMonth).map(([month, count]) => (
                            <div key={month} className="flex flex-1 flex-col items-center gap-1">
                                <div className="w-full rounded-sm bg-blue-500" style={{ height: `${(count / maxMonth) * 96}px`, minHeight: count > 0 ? 4 : 0 }} title={`${month}: ${count}`} />
                                <span className="text-xs text-gray-400">{month.slice(0, 1)}</span>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* Table */}
            <div className="overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                <div className="border-b border-gray-100 px-5 py-3">
                    <h3 className="text-sm font-semibold text-gray-800">Separation Records</h3>
                </div>
                <table className="min-w-full divide-y divide-gray-100 text-sm">
                    <thead className="bg-gray-50">
                        <tr>
                            <th className="px-4 py-3 text-left font-medium text-gray-500">Staff</th>
                            {isSuperAdmin && <th className="px-4 py-3 text-left font-medium text-gray-500">Company</th>}
                            <th className="px-4 py-3 text-left font-medium text-gray-500">Type</th>
                            <th className="px-4 py-3 text-left font-medium text-gray-500">Effective Date</th>
                            <th className="px-4 py-3 text-left font-medium text-gray-500">Reason</th>
                            <th className="px-4 py-3 text-center font-medium text-gray-500">Rehirable</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-50">
                        {separations.length === 0 && <tr><td colSpan={7} className="py-12 text-center text-gray-400">No separations recorded for {year}.</td></tr>}
                        {separations.map(s => (
                            <tr key={s.id} className="hover:bg-gray-50/50">
                                <td className="px-4 py-3">
                                    <p className="font-medium text-gray-900">{s.staff?.full_name ?? '-'}</p>
                                    <p className="text-xs text-gray-400">{s.staff?.staff_no}</p>
                                </td>
                                {isSuperAdmin && <td className="px-4 py-3 text-gray-600">{s.staff?.company?.name ?? '-'}</td>}
                                <td className="px-4 py-3">
                                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${SEP_COLORS[s.separation_type] ?? 'bg-gray-100 text-gray-600'}`}>{s.separation_type}</span>
                                </td>
                                <td className="px-4 py-3 text-gray-600">{s.effective_date}</td>
                                <td className="px-4 py-3 text-gray-600 max-w-xs truncate">{s.reason ?? '-'}</td>
                                <td className="px-4 py-3 text-center">
                                    {s.is_eligible_rehire ? <span className="text-green-600 font-medium text-xs">Yes</span> : <span className="text-red-500 text-xs">No</span>}
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </AppLayout>
    );
}
