"use client";

import { useState } from "react";
import Link from "next/link";
import { AlertTriangle, ArrowRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { useAuth } from "@/app/auth/auth-context";
import { dueText, toQueryString, useRecordAttention } from "@/app/dashboard/useDashboard";
import { QuickActButton, QuickActionSheet, SeverityDot } from "@/app/worklist/quick-action-sheet";

/**
 * "What needs attention on this record": up to three open worklist rows for a PO (`po` = PO no) or a shipment
 * (`shipment` = shipment no), each with severity, reason, owner, due and an in-place Act. Hidden when nothing is open.
 *
 *   <RecordAttention po={po.poNo} />      <RecordAttention shipment={shipment.shipmentNo} />
 */
export function RecordAttention({ po, shipment, className }) {
  const { can } = useAuth();
  const allowed = can("dashboard.view");
  const attention = useRecordAttention({ po, shipment }, allowed);
  const [acting, setActing] = useState(null);

  if (!allowed || attention.error) return null;
  if (attention.isLoading) {
    return <Card className={cn("gap-0 py-3", className)} aria-busy="true"><CardContent className="grid gap-2 px-4">
      <Skeleton className="h-4 w-40" /><Skeleton className="h-4 w-full" /><Skeleton className="h-4 w-2/3" />
    </CardContent></Card>;
  }
  if (!attention.items.length) return null;

  const more = attention.total - attention.items.length;
  const worklistHref = `/worklist${toQueryString(po ? { po } : { shipment })}`;

  return <Card className={cn("gap-0 border-warning/40 py-3 transition-opacity", attention.isRefreshing && "opacity-60", className)} aria-label="Needs attention">
    <CardContent className="grid min-w-0 grid-cols-1 gap-2 px-4">
      <div className="flex items-center justify-between gap-2">
        <p className="flex items-center gap-2 text-sm font-medium"><AlertTriangle className="size-4 text-warning" aria-hidden="true" /> Needs attention · {attention.total}</p>
        <Button variant="link" size="sm" className="h-auto px-0" asChild><Link href={worklistHref}>{more > 0 ? `+${more} more in worklist` : "Open in worklist"} <ArrowRight /></Link></Button>
      </div>
      <ul className="min-w-0 divide-y">
        {attention.items.map((item) => <li key={item.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 py-2 sm:flex-nowrap">
          <SeverityDot severity={item.severity} />
          <span className="min-w-0 flex-1">
            {item.record?.route
              ? <Link href={item.record.route} className="text-sm font-medium hover:underline">{item.reason}</Link>
              : <span className="text-sm font-medium">{item.reason}</span>}
            <span className="block truncate text-xs text-muted-foreground">{item.owner?.name || "Unassigned"} · <span className={cn(item.daysOverdue > 0 && "text-destructive")}>{dueText(item)}</span>{item.nextAction ? ` · ${item.nextAction}` : ""}</span>
          </span>
          <QuickActButton item={item} onAct={setActing} />
        </li>)}
      </ul>
    </CardContent>
    <QuickActionSheet item={acting} onClose={() => setActing(null)} />
  </Card>;
}
