import { Head, Link, router, useForm } from '@inertiajs/react';
import { ListChecks, Plus } from 'lucide-react';
import { EmptyState } from '@/components/empty-state';
import { Kpi } from '@/components/kpi';
import { PageHeader } from '@/components/page-header';
import { StatusBadge  } from '@/components/status-badge';
import type {StatusTone} from '@/components/status-badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { show as matterShow } from '@/routes/matters';
import { index, show as taskShow, store as taskStore } from '@/routes/tasks';
import { useState } from 'react';

type Option = { value: number | string; label: string };

// ... Row and Props types remain unchanged ...

function CreateTaskModal({ options, can }: { options: Props['options'], can: Props['can'] }) {
    const [open, setOpen] = useState(false);
    const form = useForm({ title: '', description: '', priority: 'normal', assigned_to: '' as string, due_date: '' });

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        form.transform((d) => ({ ...d, assigned_to: d.assigned_to || null, due_date: d.due_date || null }));
        form.post(taskStore().url, { onSuccess: () => { form.reset(); setOpen(false); } });
    };

    if (!can.create) return null;

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild>
                <Button><Plus /> New task</Button>
            </DialogTrigger>
            <DialogContent>
                <DialogHeader><DialogTitle>Create task</DialogTitle></DialogHeader>
                <form onSubmit={submit} className="grid gap-4">
                    <div className="grid gap-2"><Label>Title</Label><Input value={form.data.title} onChange={(e) => form.setData('title', e.target.value)} required /></div>
                    <div className="grid gap-2"><Label>Description</Label><Textarea value={form.data.description} onChange={(e) => form.setData('description', e.target.value)} /></div>
                    <div className="grid grid-cols-2 gap-4">
                        <div className="grid gap-2"><Label>Priority</Label><Select value={form.data.priority} onValueChange={(v) => form.setData('priority', v)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{options.priorities.map(p => <SelectItem key={p.value} value={String(p.value)}>{p.label}</SelectItem>)}</SelectContent></Select></div>
                        <div className="grid gap-2"><Label>Due date</Label><Input type="date" value={form.data.due_date} onChange={(e) => form.setData('due_date', e.target.value)} /></div>
                    </div>
                    <DialogFooter><Button type="submit" disabled={form.processing}>Create task</Button></DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}

export default function TasksIndex({ tasks, scope, filters, kpis, can, options }: Props) {
    // ... existing apply function ...
    const apply = (patch: Record<string, string | undefined>) => {
        router.get(
            index().url,
            { scope: scope === 'firm' ? 'firm' : undefined, status: filters.status || undefined, ...patch },
            { preserveState: true, replace: true },
        );
    };
    
    return (
        <>
            <Head title="My Tasks" />
            <div className="flex flex-col gap-6 p-4">
                <PageHeader
                    title="Tasks"
                    subtitle={scope === 'firm' ? 'Firm-wide task list.' : 'Tasks assigned to you.'}
                    action={
                        <div className="flex gap-2">
                            {can.viewAll && (
                                <div className="w-44">
                                    <Select value={scope} onValueChange={(v) => apply({ scope: v === 'firm' ? 'firm' : undefined })}>
                                        <SelectTrigger><SelectValue /></SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="mine">My tasks</SelectItem>
                                            <SelectItem value="firm">Firm-wide</SelectItem>
                                        </SelectContent>
                                    </Select>
                                </div>
                            )}
                            <CreateTaskModal options={options} can={can} />
                        </div>
                    }
                />
    // ... rest of the component unchanged ...

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <Kpi label="Open" value={kpis.open} />
                    <Kpi label="Due today" value={kpis.due_today} />
                    <Kpi label="Overdue" value={kpis.overdue} />
                    <Kpi label="Completed this week" value={kpis.completed_this_week} />
                </div>

                <Card>
                    <CardContent className="flex flex-wrap items-end gap-3 py-4">
                        <Select value={filters.status || ALL} onValueChange={(v) => apply({ status: v === ALL ? undefined : v })}>
                            <SelectTrigger className="w-44"><SelectValue placeholder="Status" /></SelectTrigger>
                            <SelectContent>
                                <SelectItem value={ALL}>All statuses</SelectItem>
                                {options.statuses.map((s) => (
                                    <SelectItem key={s.value} value={String(s.value)}>{s.label}</SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </CardContent>
                </Card>

                <Card>
                    <CardContent className="p-0">
                        {tasks.length === 0 ? (
                            <EmptyState icon={ListChecks} title="No tasks" description="Tasks assigned to you appear here." />
                        ) : (
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Task</TableHead>
                                        <TableHead>Matter</TableHead>
                                        <TableHead>Due</TableHead>
                                        <TableHead>Priority</TableHead>
                                        <TableHead>Status</TableHead>
                                        <TableHead />
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {tasks.map((t) => (
                                        <TableRow key={t.id}>
                                            <TableCell className="font-medium text-foreground">{t.title}</TableCell>
                                            <TableCell>
                                                {t.matter ? (
                                                    <Link href={matterShow(t.matter.id)} className="hover:text-primary">
                                                        <span className="font-mono text-xs text-muted-foreground">{t.matter.number}</span>
                                                    </Link>
                                                ) : (
                                                    <span className="text-muted-foreground">—</span>
                                                )}
                                            </TableCell>
                                            <TableCell className="whitespace-nowrap">
                                                {t.due_date ?? '—'}
                                                {t.overdue && <StatusBadge tone="danger" className="ml-2">Overdue</StatusBadge>}
                                            </TableCell>
                                            <TableCell><StatusBadge tone={t.priority_tone}>{t.priority_label}</StatusBadge></TableCell>
                                            <TableCell><StatusBadge tone={t.status_tone}>{t.status_label}</StatusBadge></TableCell>
                                            <TableCell className="text-right">
                                                <Button asChild size="xs" variant="ghost">
                                                    <Link href={taskShow(t.id)}>Open</Link>
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}
