import { Form, Head, router } from '@inertiajs/react';
import {
    ArrowRightLeft,
    CircleCheck,
    Combine,
    Plus,
    Trash2,
    Users,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import TableController from '@/actions/App/Http/Controllers/TableController';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import InputError from '@/components/input-error';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import SubmitSpinner from '@/components/submit-spinner';

type Table = {
    id: number;
    number: string;
    capacity: number;
    status: 'free' | 'occupied' | 'reserved';
    occupied_since: string | null;
    table_group_id: number | null;
};

type Props = {
    tables: Table[];
};

const statusLabels: Record<Table['status'], string> = {
    free: 'Libre',
    occupied: 'Occupée',
    reserved: 'Réservée',
};

const statusBadgeVariant: Record<
    Table['status'],
    'default' | 'secondary' | 'outline'
> = {
    free: 'secondary',
    occupied: 'default',
    reserved: 'outline',
};

const statusCardClass: Record<Table['status'], string> = {
    free: 'border-border',
    occupied: 'border-primary/40 bg-primary/5',
    reserved: 'border-amber-400/50 bg-amber-50 dark:bg-amber-950/20',
};

function useOccupationDuration(occupiedSince: string | null): string | null {
    const [now, setNow] = useState(() => Date.now());

    useEffect(() => {
        if (!occupiedSince) return;
        const interval = setInterval(() => setNow(Date.now()), 30_000);
        return () => clearInterval(interval);
    }, [occupiedSince]);

    if (!occupiedSince) return null;

    const minutes = Math.max(
        0,
        Math.round((now - new Date(occupiedSince).getTime()) / 60_000),
    );

    if (minutes < 60) return `${minutes} min`;

    return `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
}

export default function TablesIndex({ tables }: Props) {
    const [creating, setCreating] = useState(false);
    const [transferring, setTransferring] = useState<Table | null>(null);
    const [merging, setMerging] = useState<Table | null>(null);
    const [deleting, setDeleting] = useState<Table | null>(null);

    const freeTables = tables.filter((t) => t.status === 'free');

    const runAction = (url: string) => {
        router.post(
            url,
            {},
            {
                preserveScroll: true,
                onError: (errors) =>
                    toast.error(errors.domain ?? 'Action impossible.'),
            },
        );
    };

    return (
        <>
            <Head title="Tables" />

            <div className="flex flex-1 flex-col gap-6 p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-xl font-semibold tracking-tight">
                            Tables
                        </h1>
                        <p className="text-muted-foreground text-sm">
                            Vue d'ensemble du plan de salle de votre maquis.
                        </p>
                    </div>

                    <Dialog open={creating} onOpenChange={setCreating}>
                        <DialogTrigger asChild>
                            <Button>
                                <Plus />
                                Nouvelle table
                            </Button>
                        </DialogTrigger>
                        <DialogContent>
                            <Form
                                {...TableController.store.form()}
                                onSuccess={() => {
                                    setCreating(false);
                                    router.reload({ only: ['tables'] });
                                }}
                                resetOnSuccess
                            >
                                {({ processing, errors }) => (
                                    <>
                                        <DialogHeader>
                                            <DialogTitle>
                                                Nouvelle table
                                            </DialogTitle>
                                            <DialogDescription>
                                                Ajoutez une table à votre plan
                                                de salle.
                                            </DialogDescription>
                                        </DialogHeader>
                                        <div className="grid gap-4 py-2">
                                            <div className="grid gap-2">
                                                <Label htmlFor="number">
                                                    Numéro
                                                </Label>
                                                <Input
                                                    id="number"
                                                    name="number"
                                                    placeholder="Ex : T1"
                                                    autoFocus
                                                />
                                                <InputError
                                                    message={errors.number}
                                                />
                                            </div>
                                            <div className="grid gap-2">
                                                <Label htmlFor="capacity">
                                                    Capacité (couverts)
                                                </Label>
                                                <Input
                                                    id="capacity"
                                                    name="capacity"
                                                    type="number"
                                                    min={1}
                                                    max={50}
                                                    defaultValue={4}
                                                />
                                                <InputError
                                                    message={errors.capacity}
                                                />
                                            </div>
                                        </div>
                                        <DialogFooter>
                                            <Button
                                                type="submit"
                                                disabled={processing}
                                            >
                                                <SubmitSpinner
                                                    show={processing}
                                                />
                                                Enregistrer
                                            </Button>
                                        </DialogFooter>
                                    </>
                                )}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                {tables.length === 0 ? (
                    <p className="text-muted-foreground text-sm">
                        Aucune table pour le moment.
                    </p>
                ) : (
                    <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
                        {tables.map((table) => (
                            <TableCard
                                key={table.id}
                                table={table}
                                onOccupy={() =>
                                    runAction(
                                        TableController.occupy.url(table.id),
                                    )
                                }
                                onReserve={() =>
                                    runAction(
                                        TableController.reserve.url(table.id),
                                    )
                                }
                                onFree={() =>
                                    runAction(
                                        TableController.free.url(table.id),
                                    )
                                }
                                onTransfer={() => setTransferring(table)}
                                onMerge={() => setMerging(table)}
                                onDelete={() => setDeleting(table)}
                            />
                        ))}
                    </div>
                )}
            </div>

            <Dialog
                open={transferring !== null}
                onOpenChange={(open) => !open && setTransferring(null)}
            >
                <DialogContent>
                    {transferring && (
                        <Form
                            {...TableController.transfer.form(transferring.id)}
                            onSuccess={() => {
                                setTransferring(null);
                                router.reload({ only: ['tables'] });
                            }}
                        >
                            {({ processing, errors }) => (
                                <>
                                    <DialogHeader>
                                        <DialogTitle>
                                            Transférer la table{' '}
                                            {transferring.number}
                                        </DialogTitle>
                                        <DialogDescription>
                                            Déplacez l'occupation vers une table
                                            libre.
                                        </DialogDescription>
                                    </DialogHeader>
                                    <div className="grid gap-2 py-2">
                                        <Label htmlFor="to">
                                            Table de destination
                                        </Label>
                                        <Select name="to">
                                            <SelectTrigger
                                                id="to"
                                                className="w-full"
                                            >
                                                <SelectValue placeholder="Sélectionnez une table libre" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {freeTables
                                                    .filter(
                                                        (t) =>
                                                            t.id !==
                                                            transferring.id,
                                                    )
                                                    .map((t) => (
                                                        <SelectItem
                                                            key={t.id}
                                                            value={t.id.toString()}
                                                        >
                                                            Table {t.number} (
                                                            {t.capacity}{' '}
                                                            couverts)
                                                        </SelectItem>
                                                    ))}
                                            </SelectContent>
                                        </Select>
                                        <InputError message={errors.to} />
                                    </div>
                                    <DialogFooter>
                                        <Button
                                            type="submit"
                                            disabled={processing}
                                        >
                                            <SubmitSpinner show={processing} />
                                            Transférer
                                        </Button>
                                    </DialogFooter>
                                </>
                            )}
                        </Form>
                    )}
                </DialogContent>
            </Dialog>

            <Dialog
                open={merging !== null}
                onOpenChange={(open) => !open && setMerging(null)}
            >
                <DialogContent>
                    {merging && (
                        <Form
                            {...TableController.merge.form(merging.id)}
                            onSuccess={() => {
                                setMerging(null);
                                router.reload({ only: ['tables'] });
                            }}
                        >
                            {({ processing, errors }) => (
                                <>
                                    <DialogHeader>
                                        <DialogTitle>
                                            Fusionner avec la table{' '}
                                            {merging.number}
                                        </DialogTitle>
                                        <DialogDescription>
                                            Sélectionnez une ou plusieurs tables
                                            libres à fusionner avec celle-ci.
                                        </DialogDescription>
                                    </DialogHeader>
                                    <div className="grid gap-2 py-2">
                                        {freeTables
                                            .filter((t) => t.id !== merging.id)
                                            .map((t) => (
                                                <label
                                                    key={t.id}
                                                    className="flex items-center gap-2 text-sm"
                                                >
                                                    <input
                                                        type="checkbox"
                                                        name="tables[]"
                                                        value={t.id}
                                                        className="accent-primary size-4"
                                                    />
                                                    Table {t.number} (
                                                    {t.capacity} couverts)
                                                </label>
                                            ))}
                                        <InputError message={errors.tables} />
                                    </div>
                                    <DialogFooter>
                                        <Button
                                            type="submit"
                                            disabled={processing}
                                        >
                                            <SubmitSpinner show={processing} />
                                            Fusionner
                                        </Button>
                                    </DialogFooter>
                                </>
                            )}
                        </Form>
                    )}
                </DialogContent>
            </Dialog>

            <AlertDialog
                open={deleting !== null}
                onOpenChange={(open) => !open && setDeleting(null)}
            >
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>
                            Supprimer la table {deleting?.number} ?
                        </AlertDialogTitle>
                        <AlertDialogDescription>
                            Cette action est irréversible. La table ne peut être
                            supprimée que si elle est libre.
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>Annuler</AlertDialogCancel>
                        <AlertDialogAction
                            onClick={() => {
                                if (!deleting) return;
                                router.delete(
                                    TableController.destroy.url(deleting.id),
                                    {
                                        onSuccess: () => setDeleting(null),
                                        onError: (errors) => {
                                            setDeleting(null);
                                            toast.error(
                                                errors.domain ??
                                                    'Impossible de supprimer cette table.',
                                            );
                                        },
                                        preserveScroll: true,
                                    },
                                );
                            }}
                        >
                            Supprimer
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    );
}

function TableCard({
    table,
    onOccupy,
    onReserve,
    onFree,
    onTransfer,
    onMerge,
    onDelete,
}: {
    table: Table;
    onOccupy: () => void;
    onReserve: () => void;
    onFree: () => void;
    onTransfer: () => void;
    onMerge: () => void;
    onDelete: () => void;
}) {
    const duration = useOccupationDuration(table.occupied_since);

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <Card
                    className={`hover:border-primary/60 cursor-pointer gap-2 p-4 transition-colors ${statusCardClass[table.status]}`}
                >
                    <div className="flex items-start justify-between">
                        <span className="text-lg font-semibold">
                            Table {table.number}
                        </span>
                        <Badge variant={statusBadgeVariant[table.status]}>
                            {statusLabels[table.status]}
                        </Badge>
                    </div>
                    <div className="text-muted-foreground flex items-center gap-1 text-sm">
                        <Users className="size-3.5" />
                        {table.capacity} couverts
                    </div>
                    {duration && (
                        <div className="text-muted-foreground text-xs">
                            Occupée depuis {duration}
                        </div>
                    )}
                    {table.table_group_id && (
                        <div className="text-primary flex items-center gap-1 text-xs">
                            <Combine className="size-3.5" />
                            Fusionnée
                        </div>
                    )}
                </Card>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start">
                {table.status === 'free' && (
                    <>
                        <DropdownMenuItem onClick={onOccupy}>
                            <CircleCheck />
                            Marquer occupée
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={onReserve}>
                            Réserver
                        </DropdownMenuItem>
                        <DropdownMenuItem
                            onClick={onDelete}
                            variant="destructive"
                        >
                            <Trash2 />
                            Supprimer
                        </DropdownMenuItem>
                    </>
                )}
                {table.status === 'occupied' && (
                    <>
                        <DropdownMenuItem onClick={onFree}>
                            Libérer
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={onTransfer}>
                            <ArrowRightLeft />
                            Transférer
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={onMerge}>
                            <Combine />
                            Fusionner
                        </DropdownMenuItem>
                    </>
                )}
                {table.status === 'reserved' && (
                    <>
                        <DropdownMenuItem onClick={onOccupy}>
                            <CircleCheck />
                            Marquer occupée
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={onFree}>
                            Annuler la réservation
                        </DropdownMenuItem>
                    </>
                )}
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
