import { Head, router, useForm } from '@inertiajs/react';
import { Award, ArrowLeft, RefreshCw, CheckCircle2 } from 'lucide-react';
import { useState, useMemo } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';

interface Project {
    id: number;
    name: string;
    key: string;
}

interface LicenceMaster {
    id: number;
    name: string;
    required_for: string | null;
}

interface LicenceMapping {
    project_id: number;
    licence_id: number;
    is_required: boolean;
    start_date: string | null;
    end_date: string | null;
    status: string;
    remarks: string | null;
}

interface Props {
    projects: Project[];
    activeProjectId: number | null;
    licences: LicenceMaster[];
    mappings: Record<number, LicenceMapping>;
}

export default function ProjectLicencesPage({
    projects,
    activeProjectId: initialActiveProjectId,
    licences,
    mappings,
}: Props) {
    const [selectedProjectId, setSelectedProjectId] = useState<number | ''>(
        initialActiveProjectId || '',
    );

    // Form for updating mapping
    const form = useForm({
        project_id: '',
        licence_id: '',
        is_required: true,
        start_date: '',
        end_date: '',
        status: 'pending',
        remarks: '',
    });

    const handleProjectChange = (id: number | '') => {
        setSelectedProjectId(id);
        router.get(
            '/project-licences',
            { project_id: id },
            { preserveState: true },
        );
    };

    const handleSave = (licenceId: number, currentMapping?: LicenceMapping) => {
        if (!selectedProjectId) {
            toast.error('Please select a project first.');
            return;
        }

        // We use the mapping from the page state or defaults
        const rowElement = document.getElementById(`row-${licenceId}`);
        if (!rowElement) return;

        const isRequiredVal = (rowElement.querySelector('[name="is_required"]') as HTMLInputElement)?.checked;
        const statusVal = (rowElement.querySelector('[name="status"]') as HTMLSelectElement)?.value || 'pending';
        const startDateVal = (rowElement.querySelector('[name="start_date"]') as HTMLInputElement)?.value || '';
        const endDateVal = (rowElement.querySelector('[name="end_date"]') as HTMLInputElement)?.value || '';
        const remarksVal = (rowElement.querySelector('[name="remarks"]') as HTMLInputElement)?.value || '';

        router.post(
            '/project-licences',
            {
                project_id: selectedProjectId,
                licence_id: licenceId,
                is_required: isRequiredVal ? 1 : 0,
                status: statusVal,
                start_date: startDateVal || null,
                end_date: endDateVal || null,
                remarks: remarksVal || null,
            },
            {
                onSuccess: () => {
                    toast.success('Licence mapping updated successfully.');
                },
                onError: () => {
                    toast.error('Failed to update licence mapping.');
                },
            },
        );
    };

    return (
        <>
            <Head title="Project Licence Management" />
            <div className="space-y-6 p-6">
                {/* Header */}
                <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                    <div className="flex items-center gap-3">
                        <div className="flex size-10 items-center justify-center rounded-xl bg-indigo-50 text-indigo-600 dark:bg-indigo-950/50 dark:text-indigo-400">
                            <Award className="size-5" />
                        </div>
                        <div>
                            <h1 className="text-xl font-extrabold text-zinc-900 dark:text-zinc-50">
                                Project Licence Management
                            </h1>
                            <p className="text-xs text-zinc-500 font-medium">
                                Configure and track clearances and licenses on a project-by-project basis.
                            </p>
                        </div>
                    </div>
                </div>

                {/* Project Selector Card */}
                <Card className="rounded-2xl border-zinc-200/60 p-5 dark:border-zinc-800/60">
                    <div className="max-w-xs space-y-1.5">
                        <Label htmlFor="project-select" className="text-xs font-bold text-zinc-500">
                            Select Active Project
                        </Label>
                        <select
                            id="project-select"
                            className="h-9 w-full rounded-md border bg-card px-2.5 py-1 text-sm font-medium focus:outline-none"
                            value={selectedProjectId}
                            onChange={(e) =>
                                handleProjectChange(
                                    e.target.value
                                        ? Number(e.target.value)
                                        : '',
                                )
                            }
                        >
                            <option value="">-- Choose a Project --</option>
                            {projects.map((p) => (
                                <option key={p.id} value={p.id}>
                                    [{p.key}] {p.name}
                                </option>
                            ))}
                        </select>
                    </div>
                </Card>

                {/* Licences Mapping Table */}
                {selectedProjectId ? (
                    <Card className="overflow-hidden rounded-2xl border-zinc-200/60 shadow-sm dark:border-zinc-800/60">
                        <div className="overflow-x-auto">
                            <table className="w-full border-collapse text-left text-xs">
                                <thead>
                                    <tr className="border-b border-zinc-100 bg-zinc-50/50 text-zinc-500 dark:border-zinc-800/50 dark:bg-zinc-900/20">
                                        <th className="p-4 font-bold">Licence Name</th>
                                        <th className="p-4 font-bold">Required</th>
                                        <th className="p-4 font-bold">Status</th>
                                        <th className="p-4 font-bold">Start Date</th>
                                        <th className="p-4 font-bold">End Date</th>
                                        <th className="p-4 font-bold">Remarks</th>
                                        <th className="p-4 font-bold text-right">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800/50">
                                    {licences.map((licence) => {
                                        const mapping = mappings[licence.id];
                                        return (
                                            <tr
                                                key={licence.id}
                                                id={`row-${licence.id}`}
                                                className="hover:bg-zinc-50/40 dark:hover:bg-zinc-900/10"
                                            >
                                                <td className="p-4 font-semibold text-zinc-900 dark:text-zinc-100">
                                                    <div>{licence.name}</div>
                                                    {licence.required_for && (
                                                        <span className="mt-0.5 inline-block rounded bg-zinc-100 px-1 py-0.5 text-[10px] text-zinc-500 dark:bg-zinc-800">
                                                            Required for: {licence.required_for}
                                                        </span>
                                                    )}
                                                </td>
                                                <td className="p-4">
                                                    <input
                                                        type="checkbox"
                                                        name="is_required"
                                                        defaultChecked={
                                                            mapping
                                                                ? mapping.is_required
                                                                : true
                                                        }
                                                        className="size-4 rounded border-zinc-300 text-indigo-600 focus:ring-indigo-500"
                                                    />
                                                </td>
                                                <td className="p-4">
                                                    <select
                                                        name="status"
                                                        defaultValue={
                                                            mapping
                                                                ? mapping.status
                                                                : 'pending'
                                                        }
                                                        className="h-8 rounded border bg-card px-2 py-0.5 text-xs"
                                                    >
                                                        <option value="pending">Pending</option>
                                                        <option value="applied">Applied</option>
                                                        <option value="approved">Approved</option>
                                                        <option value="rejected">Rejected</option>
                                                        <option value="expired">Expired</option>
                                                    </select>
                                                </td>
                                                <td className="p-4">
                                                    <input
                                                        type="date"
                                                        name="start_date"
                                                        defaultValue={
                                                            mapping?.start_date
                                                                ? mapping.start_date.substring(
                                                                      0,
                                                                      10,
                                                                  )
                                                                : ''
                                                        }
                                                        className="h-8 rounded border bg-transparent px-2 py-1 text-xs"
                                                    />
                                                </td>
                                                <td className="p-4">
                                                    <input
                                                        type="date"
                                                        name="end_date"
                                                        defaultValue={
                                                            mapping?.end_date
                                                                ? mapping.end_date.substring(
                                                                      0,
                                                                      10,
                                                                  )
                                                                : ''
                                                        }
                                                        className="h-8 rounded border bg-transparent px-2 py-1 text-xs"
                                                    />
                                                </td>
                                                <td className="p-4">
                                                    <input
                                                        type="text"
                                                        name="remarks"
                                                        placeholder="Add comments..."
                                                        defaultValue={
                                                            mapping
                                                                ? mapping.remarks ||
                                                                  ''
                                                                : ''
                                                        }
                                                        className="h-8 w-44 rounded border bg-transparent px-2.5 py-1 text-xs"
                                                    />
                                                </td>
                                                <td className="p-4 text-right">
                                                    <Button
                                                        size="sm"
                                                        className="h-8 rounded-lg bg-indigo-600 px-3 text-xs font-bold text-white hover:bg-indigo-700"
                                                        onClick={() =>
                                                            handleSave(
                                                                licence.id,
                                                                mapping,
                                                            )
                                                        }
                                                    >
                                                        Save
                                                    </Button>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    </Card>
                ) : (
                    <div className="flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-zinc-200 py-12 text-center dark:border-zinc-800">
                        <Award className="size-10 text-zinc-300 dark:text-zinc-700" />
                        <h3 className="mt-4 text-sm font-bold text-zinc-900 dark:text-zinc-100">
                            No Project Selected
                        </h3>
                        <p className="mt-1 text-xs text-zinc-500">
                            Please select a project from the dropdown list above to configure licence compliance mappings.
                        </p>
                    </div>
                )}
            </div>
        </>
    );
}
