import { useState } from 'react';
import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { Plus } from 'lucide-react';
import { motion } from 'motion/react';
import { Button } from '@/components/ui/button';
import { StatusBadge } from '@/components/StatusBadge';
import { CreateErrandDialog } from '@/components/CreateErrandDialog';
import { ErrandDetailPanel } from '@/components/ErrandDetailPanel';
import { trpc } from '@/lib/trpc';
import { formatRelativeTime } from '@/lib/utils';

export const Route = createFileRoute('/errands/')({
  component: ErrandsPage,
  validateSearch: (search: Record<string, unknown>) => ({
    selected: typeof search.selected === 'string' ? search.selected : undefined,
  }),
});

function ErrandsPage() {
  const { selected } = Route.useSearch();
  const navigate = useNavigate();
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [selectedErrandId, setSelectedErrandId] = useState<string | null>(selected ?? null);

  const errandsQuery = trpc.errand.list.useQuery();
  const errands = errandsQuery.data ?? [];

  function selectErrand(id: string | null) {
    setSelectedErrandId(id);
    navigate({
      to: '/errands',
      search: id ? { selected: id } : {},
      replace: true,
    });
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3, ease: [0, 0, 0.2, 1] }}
      className="mx-auto max-w-6xl space-y-6"
    >
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="font-display text-2xl font-semibold">Errands</h1>
        <Button size="sm" onClick={() => setCreateDialogOpen(true)}>
          <Plus className="mr-1 h-4 w-4" />
          New Errand
        </Button>
      </div>

      {/* List / Empty state */}
      {errands.length === 0 ? (
        <p className="text-sm text-muted-foreground">
          No errands yet. Click{' '}
          <button
            className="text-primary hover:underline"
            onClick={() => setCreateDialogOpen(true)}
          >
            New Errand
          </button>{' '}
          or run:{' '}
          <code className="rounded bg-muted px-1 py-0.5 text-xs font-mono">
            cw errand start "&lt;description&gt;" --project &lt;id&gt;
          </code>
        </p>
      ) : (
        <div className="overflow-hidden rounded-lg border border-border">
          <table className="w-full text-sm">
            <thead className="border-b border-border bg-muted/50">
              <tr>
                <th className="px-4 py-2.5 text-left font-medium text-muted-foreground">ID</th>
                <th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Description</th>
                <th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Branch</th>
                <th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Status</th>
                <th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Agent</th>
                <th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Created</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {errands.map((e) => (
                <tr
                  key={e.id}
                  className="cursor-pointer hover:bg-muted/40 transition-colors"
                  onClick={() => selectErrand(e.id)}
                >
                  <td className="px-4 py-3 font-mono text-xs text-muted-foreground">
                    {e.id.slice(0, 8)}
                  </td>
                  <td className="px-4 py-3 max-w-[280px] truncate">
                    {e.description.length > 60
                      ? e.description.slice(0, 57) + '…'
                      : e.description}
                  </td>
                  <td className="px-4 py-3 font-mono text-xs text-muted-foreground truncate max-w-[180px]">
                    {e.branch}
                  </td>
                  <td className="px-4 py-3">
                    <StatusBadge status={e.status} />
                  </td>
                  <td className="px-4 py-3 text-muted-foreground">
                    {e.agentAlias ?? '—'}
                  </td>
                  <td className="px-4 py-3 text-muted-foreground whitespace-nowrap">
                    {formatRelativeTime(String(e.createdAt))}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Create dialog */}
      <CreateErrandDialog
        open={createDialogOpen}
        onOpenChange={setCreateDialogOpen}
      />

      {/* Detail slide-over */}
      {selectedErrandId && (
        <ErrandDetailPanel
          errandId={selectedErrandId}
          onClose={() => selectErrand(null)}
        />
      )}
    </motion.div>
  );
}
