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

interface Application {
    id: number;
    applicant_name: string;
    applicant_email: string | null;
    applicant_phone: string | null;
    position_applied: string | null;
    department_applied: string | null;
    type: string;
    status: string;
    notes: string | null;
    created_at: string;
    company: { id: number; name: string } | null;
    reviewer: { id: number; name: string } | null;
}

interface PaginatedApplications {
    data: Application[];
    current_page: number;
    last_page: number;
    total: number;
}

interface Company {
    id: number;
    name: string;
}

interface Props {
    applications: PaginatedApplications;
    companies: Company[];
    statuses: string[];
    filters: { search?: string; status?: string; type?: string; company_id?: string };
}

interface PageProps {
    auth: { user: { role: string } | null };
    flash: { success?: string; error?: string };
    [key: string]: unknown;
}

const STATUS_COLORS: Record<string, string> = {
    pending: 'bg-amber-50 text-amber-700',
    shortlisted: 'bg-blue-50 text-blue-700',
    interviewed: 'bg-violet-50 text-violet-700',
    offered: 'bg-cyan-50 text-cyan-700',
    accepted: 'bg-green-50 text-green-700',
    rejected: 'bg-red-50 text-red-700',
};

const STATUS_FLOW = ['pending', 'shortlisted', 'interviewed', 'offered', 'accepted'];

export default function ApplicationsIndex({ applications, companies, statuses, filters }: Props) {
    const { auth, flash } = usePage<PageProps>().props;
    const isSuperAdmin = auth?.user?.role === 'super_admin';
    const [search, setSearch] = useState(filters.search ?? '');
    const [status, setStatus] = useState(filters.status ?? '');
    const [type, setType] = useState(filters.type ?? '');
    const [companyId, setCompanyId] = useState(filters.company_id ?? '');
    const [editingId, setEditingId] = useState<number | null>(null);
    const [editStatus, setEditStatus] = useState('');
    const [editNotes, setEditNotes] = useState('');

    function applyFilters() {
        router.get('/hr-portal/applications', { search, status, type, company_id: companyId }, { preserveState: true });
    }

    function startEdit(app: Application) {
        setEditingId(app.id);
        setEditStatus(app.status);
        setEditNotes(app.notes ?? '');
    }

    function saveEdit(app: Application) {
        router.patch(`/hr-portal/applications/${app.id}`, { status: editStatus, notes: editNotes }, {
            onSuccess: () => setEditingId(null),
        });
    }

    return (
        <AppLayout title="Applications">
            <Head title="Applications" />

            {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>
            )}

            <div className="space-y-4">
                <div className="flex flex-wrap gap-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
                    <div className="relative flex-1 min-w-48">
                        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
                        <input value={search} onChange={e => setSearch(e.target.value)} onKeyDown={e => e.key === 'Enter' && applyFilters()}
                            placeholder="Search applicant, position..." className="w-full rounded-lg border border-gray-300 pl-9 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                    </div>
                    <select value={status} onChange={e => setStatus(e.target.value)} className="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">All Statuses</option>
                        {statuses.map(s => <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>)}
                    </select>
                    <select value={type} onChange={e => setType(e.target.value)} className="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">All Types</option>
                        <option value="job">Job</option>
                        <option value="trainee">Trainee</option>
                    </select>
                    {isSuperAdmin && (
                        <select value={companyId} onChange={e => setCompanyId(e.target.value)} className="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">All Companies</option>
                            {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                        </select>
                    )}
                    <button onClick={applyFilters} className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">Search</button>
                </div>

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

                <div className="space-y-3">
                    {applications.data.map(app => (
                        <div key={app.id} className="rounded-xl border border-gray-200 bg-white p-4 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">{app.applicant_name}</p>
                                        <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[app.status] ?? 'bg-gray-100 text-gray-600'}`}>
                                            {app.status.charAt(0).toUpperCase() + app.status.slice(1)}
                                        </span>
                                        <span className="rounded-full px-2 py-0.5 text-xs font-medium bg-gray-100 text-gray-600 capitalize">{app.type}</span>
                                    </div>
                                    {app.position_applied && <p className="text-sm text-gray-600 mt-0.5">{app.position_applied}</p>}
                                    <div className="mt-1 flex flex-wrap gap-3 text-xs text-gray-500">
                                        {app.applicant_email && <span>{app.applicant_email}</span>}
                                        {app.applicant_phone && <span>{app.applicant_phone}</span>}
                                        {isSuperAdmin && app.company && <span>· {app.company.name}</span>}
                                        <span>· {new Date(app.created_at).toLocaleDateString()}</span>
                                    </div>
                                    {app.notes && <p className="mt-2 text-xs text-gray-600 bg-gray-50 rounded p-2">{app.notes}</p>}
                                </div>

                                {editingId === app.id ? (
                                    <div className="flex flex-col gap-2 min-w-48">
                                        <select value={editStatus} onChange={e => setEditStatus(e.target.value)}
                                            className="rounded-lg border border-gray-300 px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                                            {statuses.map(s => <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>)}
                                        </select>
                                        <textarea value={editNotes} onChange={e => setEditNotes(e.target.value)} rows={2}
                                            placeholder="Notes..." className="rounded-lg border border-gray-300 px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
                                        <div className="flex gap-2">
                                            <button onClick={() => saveEdit(app)} className="rounded-lg bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700">Save</button>
                                            <button onClick={() => setEditingId(null)} className="rounded-lg border border-gray-300 px-3 py-1.5 text-xs text-gray-600 hover:bg-gray-50">Cancel</button>
                                        </div>
                                    </div>
                                ) : (
                                    <button onClick={() => startEdit(app)}
                                        className="rounded-lg border border-gray-300 px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50">
                                        Update Status
                                    </button>
                                )}
                            </div>

                            {/* Status pipeline */}
                            <div className="mt-3 flex items-center gap-1">
                                {STATUS_FLOW.map((s, i) => (
                                    <div key={s} className="flex items-center gap-1">
                                        {i > 0 && <div className="h-px w-4 bg-gray-200" />}
                                        <div className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                                            app.status === 'rejected' ? 'bg-gray-100 text-gray-400' :
                                            STATUS_FLOW.indexOf(app.status) >= i ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-400'
                                        }`}>{s.charAt(0).toUpperCase() + s.slice(1)}</div>
                                    </div>
                                ))}
                                {app.status === 'rejected' && (
                                    <div className="flex items-center gap-1">
                                        <div className="h-px w-4 bg-gray-200" />
                                        <div className="rounded-full px-2 py-0.5 text-xs font-medium bg-red-600 text-white">Rejected</div>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>

                {applications.data.length === 0 && (
                    <div className="rounded-xl border border-dashed border-gray-300 bg-white py-12 text-center">
                        <FileText className="mx-auto h-8 w-8 text-gray-400" />
                        <p className="mt-2 text-sm text-gray-500">No applications found.</p>
                    </div>
                )}

                {applications.last_page > 1 && (
                    <div className="flex items-center justify-between">
                        <p className="text-sm text-gray-500">Page {applications.current_page} of {applications.last_page}</p>
                        <div className="flex gap-2">
                            <button onClick={() => router.get('/hr-portal/applications', { ...filters, page: applications.current_page - 1 })}
                                disabled={applications.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/applications', { ...filters, page: applications.current_page + 1 })}
                                disabled={applications.current_page === applications.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>
    );
}
