"use client";

import { AlertCircle, Layers, ListChecks, Lock, Pencil, Plus, Power, PowerOff, Sparkles, Tags } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
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 } from "@/components/ui/dialog";
import { FieldGroup } from "@/components/ui/field";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { SearchInput } from "@/components/app/filters";
import { FormErrorAlert, TextField } from "@/components/app/form-fields";
import { SectionCard, StatCard } from "@/components/app/page";
import { cn } from "@/lib/utils";
import { useAuth } from "../../auth/auth-context";
import { EmptyState, ErrorState, UnauthorizedState } from "../../components/ui/page-states";
import StatusBadge from "../../components/ui/status-badge";
import { SettingsLayout } from "../settings-layout";
import { useReferenceDataWorkspace, useReferenceTypeCard } from "../useSettings";

export function ReferenceDataSettingsPage() {
  const { can } = useAuth();
  const canView = can("reference_data.view");
  const canManage = can("reference_data.manage");
  const workspace = useReferenceDataWorkspace(canView);
  const forbidden = !canView || workspace.error?.status === 403;

  return <SettingsLayout title="Reference data" description="Focused lists used in buyer, inquiry, PO, quality, shipment, document, and notification workflows. Platform defaults are shared; values you add stay private to this organization.">
    {forbidden && <Card className="py-0"><UnauthorizedState title="Reference data is not available for your role" permission="reference_data.view" backHref="/settings" backLabel="Back to settings" /></Card>}
    {!forbidden && workspace.isLoading && <ReferenceSkeleton />}
    {!forbidden && !workspace.isLoading && workspace.error && !workspace.hasData && <Card className="py-0"><ErrorState error={workspace.error} title="Reference data could not be loaded" onRetry={workspace.retry} /></Card>}
    {!forbidden && !workspace.isLoading && !workspace.error && !workspace.hasData && <Card className="py-0"><EmptyState title="No reference lists yet" detail="Platform defaults have not been seeded. Ask the platform team to add the standard lists." /></Card>}

    {!forbidden && !workspace.isLoading && workspace.hasData && <>
      {workspace.error && <Alert variant="destructive">
        <AlertCircle />
        <AlertDescription className="flex flex-wrap items-center gap-x-3 gap-y-2"><span>Latest changes could not be reloaded: {workspace.error.message}</span><Button variant="outline" size="sm" onClick={workspace.retry}>Reload</Button></AlertDescription>
      </Alert>}

      <section className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4" aria-label="Reference data summary">
        <StatCard label="Lists" icon={ListChecks} value={workspace.summary.typeCount} hint="Reference lists available" />
        <StatCard label="Values" icon={Tags} value={workspace.summary.valueCount} hint={`${workspace.summary.platformCount} platform defaults`} />
        <StatCard label="Your values" icon={Sparkles} value={workspace.summary.customCount} hint="Added or customized here" />
        <StatCard label="Inactive" icon={PowerOff} value={workspace.summary.inactiveCount} hint="Hidden from new forms" />
      </section>

      {!canManage && <Alert><Lock /><AlertDescription>You can view these lists. Adding, customizing, or disabling values needs the reference_data.manage permission.</AlertDescription></Alert>}

      <div className="grid gap-6 xl:grid-cols-[240px_minmax(0,1fr)]">
        <div className="xl:hidden">
          <Select value={workspace.activeGroup} onValueChange={workspace.setActiveGroup}>
            <SelectTrigger className="w-full" aria-label="Reference category"><SelectValue /></SelectTrigger>
            <SelectContent>{workspace.groups.map((group) => <SelectItem key={group.key} value={group.key}>{group.label} · {group.typeCount} lists</SelectItem>)}</SelectContent>
          </Select>
        </div>
        <nav className="hidden xl:block" aria-label="Reference categories">
          <ul className="sticky top-20 grid gap-1">
            {workspace.groups.map((group) => {
              const active = workspace.activeGroup === group.key;
              return <li key={group.key}>
                <button type="button" aria-pressed={active} onClick={() => workspace.setActiveGroup(group.key)} className={cn(
                  "grid w-full gap-0.5 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
                  active ? "bg-muted font-medium" : "text-muted-foreground hover:text-foreground",
                )}>
                  <span className="flex items-center justify-between gap-2"><span className="truncate">{group.label}</span><span className="text-xs font-normal tabular-nums text-muted-foreground">{group.valueCount}</span></span>
                  <span className="text-xs font-normal text-muted-foreground">{group.typeCount} lists</span>
                </button>
              </li>;
            })}
          </ul>
        </nav>

        <div className="flex min-w-0 flex-col gap-4">
          <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
            <div className="min-w-0 space-y-1">
              <h2 className="flex items-center gap-2 text-lg font-semibold"><Layers className="size-4 text-muted-foreground" />{workspace.selectedGroup?.label || "Reference data"}</h2>
              <p className="text-sm text-muted-foreground">{workspace.selectedGroup?.description}</p>
            </div>
            <SearchInput value={workspace.query} onChange={workspace.setQuery} placeholder="Search list, code, or value" />
          </div>
          <div className="flex flex-wrap gap-2 text-xs">
            <Badge variant="outline">{workspace.selectedGroup?.customCount || 0} organization-specific values</Badge>
            <Badge variant="outline">{workspace.selectedGroup?.inactiveCount || 0} inactive values</Badge>
            <Badge variant="outline">{workspace.summary.platformCount} platform defaults available</Badge>
          </div>

          {!workspace.visibleTypes.length && <Card className="py-0"><EmptyState compact filtered={Boolean(workspace.query)} onClearFilters={() => workspace.setQuery("")} title={workspace.query ? "No reference lists match" : "No lists in this category"} detail={workspace.query ? "Clear the search or choose another category." : "Choose another category."} /></Card>}
          {workspace.visibleTypes.map((type) => <ReferenceTypeCard key={type.id} type={type} canManage={canManage} onAdd={workspace.addLabel} onToggle={workspace.toggleValue} onSave={workspace.saveValue} />)}
        </div>
      </div>
    </>}
  </SettingsLayout>;
}

function ReferenceSkeleton() {
  return <div className="grid gap-6" aria-hidden="true">
    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">{Array.from({ length: 4 }).map((_, index) => <Skeleton key={index} className="h-24 rounded-xl" />)}</div>
    <div className="grid gap-6 xl:grid-cols-[240px_minmax(0,1fr)]">
      <div className="hidden gap-2 xl:grid">{Array.from({ length: 6 }).map((_, index) => <Skeleton key={index} className="h-12" />)}</div>
      <div className="grid gap-4"><Skeleton className="h-9 w-72" />{Array.from({ length: 2 }).map((_, index) => <Skeleton key={index} className="h-64 rounded-xl" />)}</div>
    </div>
  </div>;
}

function ReferenceTypeCard({ type, canManage, onAdd, onToggle, onSave }) {
  const card = useReferenceTypeCard(type, { onAdd, onSave, onToggle });
  const values = type.values || [];
  const own = values.filter((value) => value.organization_id !== null).length;
  const addError = card.errorFor("add");
  const title = type.code === "product_category" ? "Inquiry / product categories" : type.name;
  const colCount = canManage ? 5 : 4;

  return <SectionCard
    id={`reference-${type.code}`}
    title={title}
    icon={ListChecks}
    description={type.description}
    collapsible
    summary={`${values.length} values${own ? ` · ${own} yours` : ""}`}
    actions={<Badge variant="outline" className="font-mono">{type.code}</Badge>}
    contentClassName="grid gap-3"
  >
    <div className="overflow-x-auto rounded-lg border">
      <Table>
        <TableHeader className="bg-muted/50">
          <TableRow className="hover:bg-transparent">
            <TableHead className="h-9 text-xs">Value</TableHead>
            <TableHead className="h-9 text-xs">Code</TableHead>
            <TableHead className="h-9 text-xs">Source</TableHead>
            <TableHead className="h-9 text-xs">Status</TableHead>
            {canManage && <TableHead className="h-9 text-right text-xs"><span className="sr-only">Actions</span></TableHead>}
          </TableRow>
        </TableHeader>
        <TableBody>
          {!values.length && <TableRow className="hover:bg-transparent"><TableCell colSpan={colCount} className="py-6 text-center text-sm text-muted-foreground">No values in this list yet.</TableCell></TableRow>}
          {values.map((value) => {
            const mine = value.organization_id !== null;
            const rowError = card.errorFor(value.id);
            const toggling = card.isPending(`toggle:${value.id}`);
            return [
              <TableRow key={value.id} className={cn(!value.is_active && "text-muted-foreground")}>
                <TableCell className="font-medium">{value.label}</TableCell>
                <TableCell><code className="rounded bg-muted px-1.5 py-0.5 text-xs">{value.code}</code></TableCell>
                <TableCell>{value.isOverride ? <Badge variant="info">Customized</Badge> : mine ? <Badge variant="secondary">Yours</Badge> : <Badge variant="outline">Platform</Badge>}</TableCell>
                <TableCell><StatusBadge status={value.is_active ? "active" : "inactive"} tone={value.is_active ? "success" : "neutral"} /></TableCell>
                {canManage && <TableCell className="text-right">
                  <div className="flex justify-end gap-1">
                    <Button variant="ghost" size="sm" disabled={Boolean(card.pending)} onClick={() => card.beginEdit(value)}><Pencil /> {mine ? "Edit" : "Customize"}</Button>
                    <Button variant="ghost" size="sm" disabled={Boolean(card.pending)} onClick={() => card.toggle(value)} className={cn(value.is_active && "text-destructive hover:text-destructive")}>
                      {toggling ? <Spinner /> : value.is_active ? <PowerOff /> : <Power />} {value.is_active ? "Disable" : "Enable"}
                    </Button>
                  </div>
                </TableCell>}
              </TableRow>,
              rowError && <TableRow key={`${value.id}-error`} className="hover:bg-transparent">
                <TableCell colSpan={colCount} className="py-2 text-xs text-destructive" role="alert"><AlertCircle className="mr-1 inline size-3.5" />{rowError}</TableCell>
              </TableRow>,
            ];
          })}
        </TableBody>
      </Table>
    </div>

    {canManage && <div className="grid gap-1.5">
      <InputGroup className="sm:max-w-md">
        <InputGroupInput value={card.label} disabled={card.isPending("add")} onChange={(event) => card.setLabel(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); card.add(); } }} placeholder={`Add a value to ${type.name}`} aria-label={`New ${type.name} value`} aria-invalid={Boolean(addError)} />
        <InputGroupAddon align="inline-end">
          <InputGroupButton variant="secondary" disabled={Boolean(card.pending)} onClick={card.add}>{card.isPending("add") ? <Spinner /> : <Plus />} Add</InputGroupButton>
        </InputGroupAddon>
      </InputGroup>
      {addError ? <p className="text-xs text-destructive" role="alert">{addError}</p> : <p className="text-xs text-muted-foreground">The code is generated from the label; edit it afterwards if you need a specific one.</p>}
    </div>}

    <EditValueDialog card={card} type={type} />
  </SectionCard>;
}

function EditValueDialog({ card, type }) {
  const value = card.editing;
  const saving = Boolean(value && card.isPending(`save:${value.id}`));
  const platform = value?.organization_id === null;

  return <Dialog open={Boolean(value)} onOpenChange={(open) => { if (!open) card.cancelEdit(); }}>
    <DialogContent className="sm:max-w-md">
      <form onSubmit={card.saveEdit} className="grid gap-5" noValidate>
        <DialogHeader>
          <DialogTitle>{platform ? "Customize value" : "Edit value"}</DialogTitle>
          <DialogDescription>{platform
            ? `This creates an organization override of the platform default in ${type.name}. Other organizations keep the original.`
            : `Changes apply to ${type.name} in your organization. Records that already use this value keep it.`}</DialogDescription>
        </DialogHeader>
        <FormErrorAlert form={card.form} />
        <FieldGroup>
          <TextField control={card.form.control} name="label" label="Label" description="What people see in dropdowns." inputProps={{ autoFocus: true, disabled: saving }} />
          <TextField control={card.form.control} name="code" label="Code" description="Stable key used in exports and integrations." inputProps={{ className: "font-mono", disabled: saving }} />
        </FieldGroup>
        <DialogFooter>
          <Button type="button" variant="outline" disabled={saving} onClick={card.cancelEdit}>Cancel</Button>
          <Button type="submit" disabled={saving}>{saving && <Spinner />} Save value</Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>;
}
