import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import AppLayout from '@/Layouts/AppLayout';
import { Clock, CheckCircle, XCircle, ChevronLeft, ChevronRight } from 'lucide-react';

interface PendingChange {
    id: number;
    change_type: string;
    table_name: string;
    field_changes: Record<string, unknown>;
    status: string;
    staff_notes: string | null;
    hr_notes: string | null;
    created_at: string;
    reviewed_at: string | null;
    staff: {
        id: number;
        full_name: string;
        staff_no: string;
        company: { name: string } | null;
    } | null;
    reviewer: { name: string } | null;
}

interface PaginatedChanges {
    data: PendingChange[];
    current_page: number;
    last_page: number;
    total: number;
}

interface Props {
    changes: PaginatedChanges;
    filters: { status?: string };
}

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

const TABLE_LABELS: Record<string, string> = {
    staff: 'Contact / Profile',
    spouses: 'Spouse',
    children: 'Child',
    banking: 'Banking',
};

const CHANGE_TYPE_LABELS: Record<string, string> = {
    update: 'Update',
    create: 'Add',
    delete: 'Remove',
};

export default function PendingChangesIndex({ changes, filters }: Props) {
    const { flash } = usePage<PageProps>().props;
    const [statusFilter, setStatusFilter] = useState(filters.status ?? 'pending');
    const [hrNotes, setHrNotes] = useState<Record<number, string>>({});

    function applyFilter(s: string) {
        setStatusFilter(s);
        router.get('/hr-portal/pending-changes', { status: s }, { preserveState: true });
    }

    function approve(change: PendingChange) {
        router.post(`/hr-portal/pending-changes/${change.id}/approve`, { hr_notes: hrNotes[change.id] ?? '' }, {
            onSuccess: () => setHrNotes(n => { const c = { ...n }; delete c[change.id]; return c; }),
        });
    }

    function reject(change: PendingChange) {
        router.post(`/hr-portal/pending-changes/${change.id}/reject`, { hr_notes: hrNotes[change.id] ?? '' }, {
            onSuccess: () => setHrNotes(n => { const c = { ...n }; delete c[change.id]; return c; }),
        });
    }

    return (
        <AppLayout title="Pending Changes">
            <Head title="Pending Changes" />

            {flash?.success && (
                <div className="mb-4 rounded-lg bg-green-50 border border-green-200 px-4 py-3 text-sm text-green-700">{flash.success}</div>
            )}
            {flash?.error && (
                <div className="mb-4 rounded-lg bg-red-50 border border-red-200 px-4 py-3 text-sm text-red-700">{flash.error}</div>
            )}

            <div className="space-y-4">
                {/* Status tabs */}
                <div className="flex gap-2">
                    {['pending', 'approved', 'rejected'].map(s => (
                        <button key={s} onClick={() => applyFilter(s)}
                            className={`rounded-lg px-4 py-2 text-sm font-medium capitalize transition-colors ${statusFilter === s ? 'bg-blue-600 text-white' : 'border border-gray-300 text-gray-600 hover:bg-gray-50'}`}>
                            {s}
                        </button>
                    ))}
                </div>

                <p className="text-sm text-gray-500">{changes.total} records</p>

                <div className="space-y-3">
                    {changes.data.map(change => (
                        <div key={change.id} className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
                            <div className="flex flex-wrap items-start justify-between gap-3">
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2 flex-wrap">
                                        <p className="font-semibold text-gray-900">{change.staff?.full_name ?? 'Unknown'}</p>
                                        <span className="text-xs text-gray-500 font-mono">{change.staff?.staff_no}</span>
                                        {change.staff?.company && <span className="text-xs text-gray-500">· {change.staff.company.name}</span>}
                                    </div>
                                    <div className="mt-1 flex items-center gap-2 text-xs text-gray-500">
                                        <span className="rounded-full bg-gray-100 px-2 py-0.5 font-medium text-gray-600">
                                            {CHANGE_TYPE_LABELS[change.change_type] ?? change.change_type} {TABLE_LABELS[change.table_name] ?? change.table_name}
                                        </span>
                                        <span>{new Date(change.created_at).toLocaleDateString()}</span>
                                    </div>

                                    {/* Field changes */}
                                    <div className="mt-3 rounded-lg bg-gray-50 p-3">
                                        <p className="mb-2 text-xs font-medium text-gray-700">Proposed Changes:</p>
                                        <div className="grid grid-cols-1 gap-1 sm:grid-cols-2">
                                            {Object.entries(change.field_changes).map(([key, value]) => (
                                                <div key={key} className="flex gap-2 text-xs">
                                                    <span className="font-medium text-gray-600 capitalize">{key.replace(/_/g, ' ')}:</span>
                                                    <span className="text-gray-800">{String(value)}</span>
                                                </div>
                                            ))}
                                        </div>
                                    </div>

                                    {change.staff_notes && (
                                        <p className="mt-2 text-xs text-gray-600 italic">Staff note: "{change.staff_notes}"</p>
                                    )}
                                    {change.hr_notes && (
                                        <p className="mt-2 text-xs text-gray-600">HR note: "{change.hr_notes}"</p>
                                    )}
                                    {change.reviewer && (
                                        <p className="mt-1 text-xs text-gray-400">
                                            {change.status === 'approved' ? 'Approved' : 'Rejected'} by {change.reviewer.name}
                                            {change.reviewed_at ? ` on ${new Date(change.reviewed_at).toLocaleDateString()}` : ''}
                                        </p>
                                    )}
                                </div>

                                {change.status === 'pending' && (
                                    <div className="flex flex-col gap-2 min-w-48">
                                        <textarea
                                            value={hrNotes[change.id] ?? ''}
                                            onChange={e => setHrNotes(n => ({ ...n, [change.id]: e.target.value }))}
                                            placeholder="HR notes (optional)..."
                                            rows={2}
                                            className="rounded-lg border border-gray-300 px-2 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-blue-500"
                                        />
                                        <div className="flex gap-2">
                                            <button onClick={() => approve(change)}
                                                className="flex items-center gap-1.5 rounded-lg bg-green-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-green-700">
                                                <CheckCircle className="h-3.5 w-3.5" /> Approve
                                            </button>
                                            <button onClick={() => reject(change)}
                                                className="flex items-center gap-1.5 rounded-lg bg-red-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-red-700">
                                                <XCircle className="h-3.5 w-3.5" /> Reject
                                            </button>
                                        </div>
                                    </div>
                                )}

                                {change.status !== 'pending' && (
                                    <span className={`rounded-full px-3 py-1 text-xs font-medium ${change.status === 'approved' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'}`}>
                                        {change.status.charAt(0).toUpperCase() + change.status.slice(1)}
                                    </span>
                                )}
                            </div>
                        </div>
                    ))}
                </div>

                {changes.data.length === 0 && (
                    <div className="rounded-xl border border-dashed border-gray-300 bg-white py-12 text-center">
                        <Clock className="mx-auto h-8 w-8 text-gray-400" />
                        <p className="mt-2 text-sm text-gray-500">
                            {statusFilter === 'pending' ? 'No pending changes.' : `No ${statusFilter} changes.`}
                        </p>
                    </div>
                )}

                {changes.last_page > 1 && (
                    <div className="flex items-center justify-between">
                        <p className="text-sm text-gray-500">Page {changes.current_page} of {changes.last_page}</p>
                        <div className="flex gap-2">
                            <button onClick={() => router.get('/hr-portal/pending-changes', { status: statusFilter, page: changes.current_page - 1 })}
                                disabled={changes.current_page === 1}
                                className="flex items-center gap-1 rounded-lg border border-gray-300 px-3 py-1.5 text-sm disabled:opacity-40 hover:bg-gray-50">
                                <ChevronLeft className="h-4 w-4" /> Prev
                            </button>
                            <button onClick={() => router.get('/hr-portal/pending-changes', { status: statusFilter, page: changes.current_page + 1 })}
                                disabled={changes.current_page === changes.last_page}
                                className="flex items-center gap-1 rounded-lg border border-gray-300 px-3 py-1.5 text-sm disabled:opacity-40 hover:bg-gray-50">
                                Next <ChevronRight className="h-4 w-4" />
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </AppLayout>
    );
}
