import SearchInput from '@/Components/SearchInput';
import SelectInput from '@/Components/SelectInput';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/Components/ui/table';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import RestockAction from '@/Pages/DrugPrescription/RestockAction';
import { Head, Link } from '@inertiajs/react';
import { useMemo, useState } from 'react';

interface RestockRow {
    id: number;
    patient_id: number;
    patient_name: string;
    drug_name: string;
    available_doses: number;
    package_quantity: number;
    last_restocked_at: string | null;
}

interface RestockDashboardProps {
    prescriptions: RestockRow[];
}

function formatDate(value: string | null): string {
    if (!value) {
        return 'Mai';
    }

    return new Date(value).toLocaleDateString('it', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
    });
}

export default function RestockDashboard({
    prescriptions,
}: RestockDashboardProps) {
    const [search, setSearch] = useState('');
    const [patientFilter, setPatientFilter] = useState('all');

    const patientOptions = useMemo(() => {
        const byId = new Map<number, string>();
        prescriptions.forEach((row) =>
            byId.set(row.patient_id, row.patient_name),
        );

        return [
            { value: 'all', label: 'Tutti i pazienti' },
            ...Array.from(byId, ([id, name]) => ({
                value: String(id),
                label: name,
            })).sort((a, b) => a.label.localeCompare(b.label)),
        ];
    }, [prescriptions]);

    const filtered = useMemo(() => {
        const query = search.trim().toLowerCase();

        return prescriptions.filter((row) => {
            const matchesSearch =
                !query ||
                row.patient_name.toLowerCase().includes(query) ||
                row.drug_name.toLowerCase().includes(query);
            const matchesPatient =
                patientFilter === 'all' ||
                String(row.patient_id) === patientFilter;

            return matchesSearch && matchesPatient;
        });
    }, [prescriptions, search, patientFilter]);

    return (
        <AuthenticatedLayout
            backLink={route('dashboard')}
            backLinkLabel="Dashboard"
        >
            <Head title="Farmaci da riordinare" />

            <div className="py-2">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
                    <div className="overflow-hidden sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <div className="scroll-m-20 text-4xl font-light tracking-tight lg:text-5xl">
                                Farmaci da riordinare
                            </div>
                            <p className="mt-2 text-zinc-500">
                                Tutti i farmaci sotto soglia dei pazienti che
                                gestisci.
                            </p>

                            <div className="container mx-auto py-10">
                                <div className="flex flex-wrap items-end gap-3 pb-4">
                                    <SearchInput
                                        value={search}
                                        onChange={(e) =>
                                            setSearch(e.target.value)
                                        }
                                        placeholder="Cerca paziente o farmaco"
                                        className="min-w-[220px] grow"
                                    />
                                    <div className="w-64">
                                        <label className="mb-1 block text-xs text-zinc-500">
                                            Paziente
                                        </label>
                                        <SelectInput
                                            value={patientFilter}
                                            options={patientOptions}
                                            onChange={setPatientFilter}
                                        />
                                    </div>
                                </div>
                                <div className="overflow-x-auto rounded-md border bg-white">
                                    <Table>
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead>Paziente</TableHead>
                                                <TableHead>Farmaco</TableHead>
                                                <TableHead>
                                                    Dosi disponibili
                                                </TableHead>
                                                <TableHead>
                                                    Ultimo riassortimento
                                                </TableHead>
                                                <TableHead className="text-right">
                                                    Azione
                                                </TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {filtered.length ? (
                                                filtered.map((row) => (
                                                    <TableRow key={row.id}>
                                                        <TableCell className="font-medium">
                                                            <Link
                                                                href={route(
                                                                    'dashboard.personal',
                                                                    {
                                                                        target: row.patient_id,
                                                                    },
                                                                )}
                                                                className="underline hover:text-neutral-600"
                                                            >
                                                                {
                                                                    row.patient_name
                                                                }
                                                            </Link>
                                                        </TableCell>
                                                        <TableCell>
                                                            {row.drug_name}
                                                        </TableCell>
                                                        <TableCell>
                                                            {
                                                                row.available_doses
                                                            }
                                                        </TableCell>
                                                        <TableCell>
                                                            {formatDate(
                                                                row.last_restocked_at,
                                                            )}
                                                        </TableCell>
                                                        <TableCell className="text-right">
                                                            <RestockAction
                                                                prescriptionId={
                                                                    row.id
                                                                }
                                                                drugName={
                                                                    row.drug_name
                                                                }
                                                                availableDoses={
                                                                    row.available_doses
                                                                }
                                                                packageQuantity={
                                                                    row.package_quantity
                                                                }
                                                            />
                                                        </TableCell>
                                                    </TableRow>
                                                ))
                                            ) : (
                                                <TableRow>
                                                    <TableCell
                                                        colSpan={5}
                                                        className="h-24 text-center"
                                                    >
                                                        {prescriptions.length
                                                            ? 'Nessun risultato per i filtri applicati.'
                                                            : 'Nessun farmaco da riordinare.'}
                                                    </TableCell>
                                                </TableRow>
                                            )}
                                        </TableBody>
                                    </Table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
