"use client";

import { Suspense, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowRight, CheckCircle2, RefreshCw } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { DataTable } from "@/components/app/data-table";
import { ActiveFilters, FilterCombobox, FilterSelect, SearchInput } from "@/components/app/filters";
import { ListPageSkeleton, PageContent, PageHeader } from "@/components/app/page";
import { SavedViewsBar } from "@/components/app/saved-views";
import { cn } from "@/lib/utils";
import ProtectedRoute from "../auth/protected-route";
import { useAuth } from "../auth/auth-context";
import AppShell from "../components/app-shell";
import { EmptyState, ErrorState, UnauthorizedState } from "../components/ui/page-states";
import { humanize } from "../lib/format";
import { TeachingEmptyState } from "../onboarding/teaching-empty-state";
import { useDebouncedSearch } from "../lib/useDebouncedSearch";
import { dueText, relativeTime, WORKLIST_TYPE_LABELS } from "../dashboard/useDashboard";
import { QuickActButton, QuickActionSheet, SeverityBadge } from "./quick-action-sheet";
import { DUE_TABS, SEVERITY_OPTIONS, TYPE_OPTIONS, useWorklist } from "./useWorklist";

export function WorklistPage() {
  return <ProtectedRoute><AppShell title="Worklist" subtitle="Exceptions">
    {/* useSearchParams needs a Suspense boundary so the page can still be prerendered. */}
    <Suspense fallback={<ListPageSkeleton filters={4} />}><Worklist /></Suspense>
  </AppShell></ProtectedRoute>;
}

function Worklist() {
  const router = useRouter();
  const { can } = useAuth();
  const allowed = can("dashboard.view");
  const list = useWorklist(allowed);
  const { filters, update, worklist } = list;
  const [acting, setActing] = useState(null);
  const [search, setSearch] = useDebouncedSearch(filters.search, (value) => update({ search: value.trim() }));
  const clearAll = () => { setSearch(""); list.clear(); };

  const columns = useMemo(() => [
    {
      id: "severity", header: "Severity", enableSorting: false, meta: { mobile: "badge" },
      cell: ({ row }) => <SeverityBadge severity={row.original.severity} />,
    },
    {
      id: "reason", header: "Reason", enableSorting: false, meta: { className: "min-w-56 whitespace-normal", mobile: "title" },
      cell: ({ row }) => <div className="grid gap-0.5">
        <span className="font-medium">{row.original.reason}</span>
        <span className="text-xs font-normal text-muted-foreground">{WORKLIST_TYPE_LABELS[row.original.type] || humanize(row.original.type)}{row.original.detail ? ` · ${row.original.detail}` : ""}</span>
      </div>,
    },
    {
      id: "record", header: "Record", enableSorting: false, meta: { mobile: "subtitle" },
      cell: ({ row }) => row.original.record
        ? <Link href={row.original.record.route} className="group inline-grid">
          <span className="font-medium group-hover:underline">{row.original.record.label}</span>
          <span className="text-xs text-muted-foreground">{humanize(row.original.record.type, "Record")}</span>
        </Link>
        : <span className="text-muted-foreground">No linked record</span>,
    },
    { id: "owner", header: "Owner", enableSorting: false, cell: ({ row }) => row.original.owner?.name || <span className="text-destructive">Unassigned</span> },
    {
      id: "due", header: "Due", enableSorting: false,
      cell: ({ row }) => <span className={cn("whitespace-nowrap", row.original.daysOverdue > 0 && "text-destructive")}>{dueText(row.original)}</span>,
    },
    { id: "nextAction", header: "Next action", enableSorting: false, meta: { className: "min-w-48 max-w-72 whitespace-normal" }, cell: ({ row }) => <span className="text-sm">{row.original.nextAction}</span> },
    {
      id: "actions", header: () => <span className="sr-only">Actions</span>, enableSorting: false, meta: { align: "right" },
      cell: ({ row }) => <div className="flex items-center justify-end gap-1">
        <QuickActButton item={row.original} onAct={setActing} />
        {row.original.record?.route && <Button variant="ghost" size="icon-sm" asChild><Link href={row.original.record.route} aria-label={`Open ${row.original.record.label}`}><ArrowRight /></Link></Button>}
      </div>,
    },
  ], []);

  if (!allowed) {
    return <PageContent><UnauthorizedState title="The worklist is not available for your role" permission="dashboard.view" /></PageContent>;
  }

  const { summary } = worklist;
  const summaryText = worklist.isLoading ? "Counting open items…" : worklist.error ? "Counts unavailable." : `${summary.total} open · ${summary.critical} critical.`;
  const byDue = summary.byDue || {};
  const updated = worklist.generatedAt || worklist.fetchedAt;

  return <PageContent>
    <PageHeader
      title="Exception worklist"
      description={`${summaryText} Every row says why it is here, who owns it, and the next action. Use Act to clear it without leaving the list.`}
      actions={<Tooltip>
        <TooltipTrigger asChild>
          <Button variant="outline" size="icon-sm" onClick={worklist.refresh} disabled={worklist.isRefreshing} aria-label="Refresh worklist">{worklist.isRefreshing ? <Spinner /> : <RefreshCw />}</Button>
        </TooltipTrigger>
        <TooltipContent>Refresh · updated {updated ? relativeTime(updated) : "now"}</TooltipContent>
      </Tooltip>}
    />

    <div className="flex flex-col gap-3">
      <div className="overflow-x-auto overflow-y-hidden">
        <Tabs value={filters.due || "all"} onValueChange={(value) => update({ due: value === "all" ? "" : value })}>
          <TabsList aria-label="Due">
            {DUE_TABS.map((tab) => <TabsTrigger key={tab.label} value={tab.value || "all"} className="px-3">
              {tab.label}
              {tab.countKey && byDue[tab.countKey] > 0 && <Badge variant={tab.countKey === "overdue" ? "danger" : "secondary"} className="ml-1 h-5 px-1.5 tabular-nums">{byDue[tab.countKey]}</Badge>}
            </TabsTrigger>)}
          </TabsList>
        </Tabs>
      </div>
      <div className="flex flex-wrap items-center gap-2">
        <SearchInput value={search} onChange={setSearch} placeholder="Search reason, PO, or owner…" />
        <FilterSelect label="Severity" value={filters.severity} onChange={(severity) => update({ severity })} options={SEVERITY_OPTIONS} allLabel="Any" />
        <FilterSelect label="Type" value={filters.type} onChange={(type) => update({ type })} options={TYPE_OPTIONS} allLabel="All types" />
        <FilterCombobox label="Owner" value={filters.ownerId} onChange={(ownerId) => update({ ownerId, mine: "" })} options={list.ownerOptions} allLabel="Anyone" searchPlaceholder="Search people…" />
        <FilterCombobox label="Buyer" value={filters.buyer} onChange={(buyer) => update({ buyer })} options={list.buyerOptions} allLabel="All buyers" searchPlaceholder="Search buyers…" />
        <FilterCombobox label="Factory" value={filters.factory} onChange={(factory) => update({ factory })} options={list.factoryOptions} allLabel="All factories" searchPlaceholder="Search factories…" />
      </div>
      <ActiveFilters chips={list.chips} onRemove={(key) => { if (key === "search") setSearch(""); list.removeFilter(key); }} onClear={clearAll} emptyText={filters.due === "upcoming" ? "Showing work due in the next 7 days that is not late yet." : "Showing every open exception you are allowed to see."} />
      <SavedViewsBar module="worklist" noun="the worklist" filters={list.savedFilters} onApply={(view) => router.replace(`/worklist${Object.keys(view.filters || {}).length ? `?${new URLSearchParams(view.filters)}` : ""}`, { scroll: false })} applyDefault />
    </div>

    <DataTable
      columns={columns}
      data={worklist.items}
      getRowId={(row) => String(row.id)}
      isLoading={worklist.isLoading}
      isRefreshing={worklist.isRefreshing}
      error={worklist.error}
      errorState={<ErrorState compact error={worklist.error} title="The worklist could not load" onRetry={worklist.refresh} />}
      emptyState={list.hasFilters
        ? <EmptyState filtered onClearFilters={clearAll} title="No exceptions match these filters" detail="Overdue TNA milestones, approvals, materials, blockers, inspections, production and shipment risks, and costing follow-ups appear here automatically." />
        : <TeachingEmptyState k="worklist" icon={CheckCircle2} showSample={false} />}
      pagination={list.pagination}
      onPageChange={(page) => update({ page: String(page) })}
      noun="items"
    />

    <p className="text-xs text-muted-foreground">Calculated {updated ? relativeTime(updated) : "now"} from live orders, pre-production, production, quality, shipment, costing, and payment data. Critical items come first, then by due date.</p>

    <QuickActionSheet item={acting} onClose={() => setActing(null)} />
  </PageContent>;
}
