import { Head, Link, router } from '@inertiajs/react';
import { Plus, Trash2, Users } from 'lucide-react';
import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import adminLocations from '@/routes/admin/locations';

type Technician = { id: number; name: string; email: string };

type Props = {
    location: { id: number; name: string };
    assignedIds: number[];
    allTechnicians: Technician[];
};

export default function LocationTechnicians({ location, assignedIds, allTechnicians }: Props) {
    const [selectedIds, setSelectedIds] = useState<number[]>(assignedIds);
    const [addingId, setAddingId] = useState<string>('');
    const [saving, setSaving] = useState(false);

    const assigned   = allTechnicians.filter((t) => selectedIds.includes(t.id));
    const unassigned = allTechnicians.filter((t) => !selectedIds.includes(t.id));

    const remove = (id: number) => setSelectedIds((prev) => prev.filter((x) => x !== id));

    const add = () => {
        const id = Number(addingId);
        if (id && !selectedIds.includes(id)) {
            setSelectedIds((prev) => [...prev, id]);
            setAddingId('');
        }
    };

    const handleSave = () => {
        setSaving(true);
        router.post(
            adminLocations.technicians.sync.url(location.id),
            { technician_ids: selectedIds },
            { onFinish: () => setSaving(false) },
        );
    };

    const capacityLabel =
        selectedIds.length === 0
            ? 'No technicians assigned — defaults to 1 concurrent booking per slot'
            : `${selectedIds.length} technician${selectedIds.length > 1 ? 's' : ''} — up to ${selectedIds.length} concurrent booking${selectedIds.length > 1 ? 's' : ''} per slot`;

    return (
        <>
            <Head title={`Technicians — ${location.name}`} />
            <div className="mx-auto max-w-2xl space-y-6 p-6">
                <PageHeader
                    title="Technicians"
                    description="Assign technicians to increase concurrent booking capacity."
                    actions={
                        <Link href={adminLocations.index.url()}>
                            <Button variant="outline" size="sm">Back to Locations</Button>
                        </Link>
                    }
                />

                <p className="text-sm font-medium text-muted-foreground">{location.name}</p>

                <div className="rounded-xl border bg-card shadow-sm">
                    {/* Capacity indicator */}
                    <div className="flex items-center gap-3 border-b px-5 py-3">
                        <Users className="size-4 shrink-0 text-muted-foreground" />
                        <span className="text-sm text-muted-foreground">{capacityLabel}</span>
                    </div>

                    {/* Assigned technician rows */}
                    <div className="divide-y">
                        {assigned.length === 0 ? (
                            <p className="px-5 py-4 text-sm text-muted-foreground">
                                No technicians assigned yet.
                            </p>
                        ) : (
                            assigned.map((tech) => (
                                <div key={tech.id} className="flex items-center gap-3 px-5 py-3">
                                    <div className="min-w-0 flex-1">
                                        <p className="truncate text-sm font-medium">{tech.name}</p>
                                        <p className="truncate text-xs text-muted-foreground">{tech.email}</p>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={() => remove(tech.id)}
                                        className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-destructive"
                                        title="Remove technician"
                                    >
                                        <Trash2 className="size-3.5" />
                                    </button>
                                </div>
                            ))
                        )}
                    </div>

                    {/* Add technician row */}
                    {unassigned.length > 0 && (
                        <div className="flex items-center gap-2 border-t px-5 py-3">
                            <select
                                value={addingId}
                                onChange={(e) => setAddingId(e.target.value)}
                                className="h-8 flex-1 rounded-md border border-input bg-background px-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
                            >
                                <option value="">Select a technician to add…</option>
                                {unassigned.map((tech) => (
                                    <option key={tech.id} value={tech.id}>
                                        {tech.name} — {tech.email}
                                    </option>
                                ))}
                            </select>
                            <button
                                type="button"
                                onClick={add}
                                disabled={!addingId}
                                className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40"
                            >
                                <Plus className="size-3" />
                                Add
                            </button>
                        </div>
                    )}

                    {/* Footer */}
                    <div className="flex items-center justify-end border-t px-5 py-3">
                        <Button onClick={handleSave} disabled={saving} size="sm">
                            {saving ? 'Saving…' : 'Save technicians'}
                        </Button>
                    </div>
                </div>
            </div>
        </>
    );
}

LocationTechnicians.layout = (page: React.ReactNode) => <AppLayout>{page}</AppLayout>;
