"use client";

import { useEffect, useRef } from "react";
import Link from "next/link";
import { ArrowRight, Zap } from "lucide-react";
import { Button } from "@/components/ui/button";
import { FieldGroup } from "@/components/ui/field";
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Spinner } from "@/components/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { FactList } from "@/components/app/page";
import { FormErrorAlert, SelectField, TextareaField, TextField } from "@/components/app/form-fields";
import { cn } from "@/lib/utils";
import { useAuth } from "../auth/auth-context";
import StatusBadge from "../components/ui/status-badge";
import { humanize } from "../lib/format";
import { useUnsavedChangesGuard } from "../lib/useUnsavedChangesGuard";
import { dueText, WORKLIST_TYPE_LABELS } from "../dashboard/useDashboard";
import { quickActionFor, useQuickActionForm } from "./useQuickAction";

export const SEVERITY_TONES = { critical: "danger", warning: "warning", upcoming: "info" };
export const SEVERITY_LABELS = { critical: "Critical", warning: "Warning", upcoming: "Upcoming" };

// Severity dot + screen-reader word, so colour is never the only signal.
export function SeverityDot({ severity, className }) {
  return <span className={cn("inline-flex size-2.5 shrink-0 rounded-full", severity === "critical" ? "bg-destructive" : severity === "warning" ? "bg-warning" : "bg-info", className)} title={SEVERITY_LABELS[severity] || humanize(severity)}>
    <span className="sr-only">{SEVERITY_LABELS[severity] || humanize(severity)}</span>
  </span>;
}

export function SeverityBadge({ severity }) {
  return <StatusBadge status={severity} tone={SEVERITY_TONES[severity] || "neutral"} label={SEVERITY_LABELS[severity] || humanize(severity)} />;
}

/**
 * "Act" button for a worklist row. Rows without an in-place action render nothing (the row's open link is enough);
 * rows the user may not change show a disabled button that says why.
 */
export function QuickActButton({ item, onAct, size = "sm", className }) {
  const { can } = useAuth();
  const action = quickActionFor(item, can);
  if (!action) return null;
  if (!action.allowed) {
    return <Tooltip>
      <TooltipTrigger asChild><span tabIndex={0} className={className}><Button variant="outline" size={size} disabled><Zap /> Act</Button></span></TooltipTrigger>
      <TooltipContent>Your role cannot {action.title.toLowerCase()} ({action.permission}). Open the record to see details.</TooltipContent>
    </Tooltip>;
  }
  return <Button variant="outline" size={size} className={className} onClick={() => onAct(item)} aria-label={`${action.label}: ${item.reason}`}><Zap /> Act</Button>;
}

/** Side sheet with the smallest form that clears a worklist row. `item` null = closed. */
export function QuickActionSheet({ item, onClose }) {
  const { can } = useAuth();
  const action = item ? quickActionFor(item, can) : null;
  // Esc / overlay / X go through the form's unsaved-changes check.
  const requestClose = useRef(null);

  return <Sheet open={Boolean(item && action)} onOpenChange={(open) => { if (!open) (requestClose.current || onClose)(); }}>
    <SheetContent className="w-full gap-0 overflow-y-auto sm:max-w-md">
      {item && action && <QuickActionForm key={`${item.id}:${action.kind}`} item={item} action={action} onClose={onClose} requestClose={requestClose} />}
    </SheetContent>
  </Sheet>;
}

function QuickActionForm({ item, action, onClose, requestClose }) {
  const { form, submit } = useQuickActionForm(item, onClose);
  const guard = useUnsavedChangesGuard(form.formState.isDirty, { interceptLinks: false });
  const close = async () => { if (await guard.confirmDiscard()) onClose(); };
  useEffect(() => {
    requestClose.current = close;
    return () => { requestClose.current = null; };
  });
  const submitting = form.formState.isSubmitting;

  return <form onSubmit={submit} className="flex min-h-full flex-col">
    <SheetHeader className="gap-2 border-b">
      <div className="flex flex-wrap items-center gap-2"><SeverityBadge severity={item.severity} /><span className="text-xs text-muted-foreground">{WORKLIST_TYPE_LABELS[item.type] || humanize(item.type)}</span></div>
      <SheetTitle>{action.label}</SheetTitle>
      <SheetDescription>{item.reason}{item.detail ? ` · ${item.detail}` : ""}</SheetDescription>
    </SheetHeader>

    <div className="grid gap-5 p-4">
      <FactList columns={2} items={[
        ["Record", item.record?.route ? <Link href={item.record.route} className="hover:underline">{item.record.label}</Link> : item.record?.label || "No linked record"],
        ["Owner", item.owner?.name || "Unassigned"],
        ["Due", dueText(item)],
        ["Next action", item.nextAction || "—"],
      ]} />
      <FormErrorAlert form={form} />
      <FieldGroup className="gap-4"><QuickActionFields kind={action.kind} form={form} item={item} /></FieldGroup>
    </div>

    <SheetFooter className="mt-auto flex-row flex-wrap justify-between gap-2 border-t">
      {item.record?.route
        ? <Button type="button" variant="ghost" size="sm" asChild><Link href={item.record.route}>Open record <ArrowRight /></Link></Button>
        : <span />}
      <div className="flex gap-2">
        <Button type="button" variant="outline" onClick={close}>Cancel</Button>
        <Button type="submit" disabled={submitting}>{submitting && <Spinner />} {action.submitLabel}</Button>
      </div>
    </SheetFooter>
  </form>;
}

const DECISION_OPTIONS = [
  { value: "approved", label: "Approved", description: "Buyer approved this round." },
  { value: "rejected", label: "Rejected", description: "Buyer rejected; a new round is needed." },
  { value: "submitted", label: "Sent to buyer", description: "The sample went out; waiting for the buyer's decision." },
];
const MATERIAL_OPTIONS = [
  { value: "arrived", label: "Arrived", description: "Fully received in the factory." },
  { value: "partial", label: "Partially received" },
  { value: "booked", label: "Booked", description: "Ordered from the supplier; set the promised date." },
  { value: "shortage", label: "Shortage", description: "Not enough material; explain the recovery." },
];
const BLOCKER_OPTIONS = [{ value: "resolved", label: "Resolved" }, { value: "cancelled", label: "Cancelled (not a blocker)" }];
const INSPECTION_OPTIONS = [
  { value: "pass", label: "Pass" },
  { value: "fail", label: "Fail", description: "Needs a corrective action and a reinspection." },
  { value: "in_progress", label: "In progress", description: "Started; the final result comes later." },
];
const PILOT_OPTIONS = [
  { value: "released", label: "Release to bulk" },
  { value: "blocked", label: "Block release" },
  { value: "waived", label: "Waive pilot run" },
];

function QuickActionFields({ kind, form, item }) {
  const { control } = form;
  const material = form.watch("status");
  const result = form.watch("result");
  const decision = form.watch("decision");

  switch (kind) {
    case "complete_milestone":
      return <TextField control={control} name="actual_date" type="date" label="Completed on" description="The actual date; today or earlier." />;
    case "approval_decision":
      // Already with the buyer: only the buyer's answer can be recorded (the API refuses a second "sent").
      return <>
        <SelectField control={control} name="decision" label={item?.quickAction?.state === "submitted" ? "Buyer's decision" : "What happened"}
          options={item?.quickAction?.state === "submitted" ? DECISION_OPTIONS.filter((option) => option.value !== "submitted") : [DECISION_OPTIONS[2], DECISION_OPTIONS[0], DECISION_OPTIONS[1]]} />
        {decision !== "submitted" && <TextField control={control} name="approver_name" label="Decided by (buyer contact)" placeholder="Optional" />}
        <TextareaField control={control} name="comment" label="Comment" placeholder={decision === "submitted" ? "Optional, e.g. courier and tracking number" : "Buyer comments, required for a rejection"} />
      </>;
    case "update_material":
      return <>
        <SelectField control={control} name="status" label="Status" options={MATERIAL_OPTIONS} />
        {["arrived", "partial"].includes(material) && <TextField control={control} name="actual_arrival_date" type="date" label="Arrived on" />}
        {["arrived", "partial"].includes(material) && <TextField control={control} name="received_quantity" type="number" label="Received quantity" placeholder="Optional" inputProps={{ min: 0, step: "any" }} />}
        {["booked", "shortage", "partial"].includes(material) && <TextField control={control} name="promised_arrival_date" type="date" label="Promised arrival" description="Leave empty to keep the current date." />}
        <TextareaField control={control} name="notes" label="Notes" placeholder={material === "shortage" ? "Shortage and recovery plan" : "Optional"} />
      </>;
    case "resolve_blocker":
      return <>
        <SelectField control={control} name="status" label="Outcome" options={BLOCKER_OPTIONS} />
        <TextareaField control={control} name="resolution_note" label="Resolution note" placeholder="What was done, or why it is not a blocker" />
      </>;
    case "inspection_result":
      return <>
        <SelectField control={control} name="result" label="Result" options={INSPECTION_OPTIONS} />
        {result === "fail" && <TextareaField control={control} name="corrective_action_summary" label="Corrective action" placeholder="What the factory must fix before reinspection" />}
        <TextareaField control={control} name="comment" label="Comment" placeholder="Optional" />
      </>;
    case "pilot_decision":
      return <>
        <SelectField control={control} name="release_decision" label="Decision" options={PILOT_OPTIONS} />
        <TextareaField control={control} name="comment" label="Reason" placeholder="Required when blocking or waiving" />
      </>;
    default:
      return null;
  }
}
