import { useMutation, useQueryClient, type UseQueryResult } from "@tanstack/react-query";
import { Link, type LinkProps } from "@tanstack/react-router";
import { Download, Loader2 } from "lucide-react";
import { useState, type ReactNode } from "react";
import { toast } from "sonner";
import { Field, TextArea } from "./form";
import { EmptyState, ErrorState, TableSkeleton } from "./states";
import { Button } from "@/components/ui/button";
import { downloadFile } from "@/api/http";
import { useAccess } from "@/lib/access";
import { cn } from "@/lib/utils";

/** Loading, error and empty states for one query. */
export function View<T>({
  q,
  skeleton,
  empty,
  isEmpty,
  children,
}: {
  q: UseQueryResult<T, Error>;
  skeleton?: ReactNode;
  empty?: { title: string; text: string };
  isEmpty?: (d: T) => boolean;
  children: (d: T) => ReactNode;
}) {
  if (q.isPending) return <>{skeleton ?? <TableSkeleton cols={5} rows={6} />}</>;
  if (q.isError) return <ErrorState error={q.error} onRetry={() => void q.refetch()} />;
  if (empty && (isEmpty ? isEmpty(q.data) : Array.isArray(q.data) && q.data.length === 0))
    return (
      <div className="rounded-xl border bg-card">
        <EmptyState {...empty} />
      </div>
    );
  return <>{children(q.data)}</>;
}

/** Plain table; prefix a header with ">" to right-align it. */
export function Tbl({
  head,
  children,
  caption,
}: {
  head: string[];
  children: ReactNode;
  caption?: string;
}) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-left text-[13px] tabular [&_td]:px-4 [&_td]:py-2 [&_tbody_tr]:border-t">
        {caption && <caption className="sr-only">{caption}</caption>}
        <thead className="bg-surface-2 text-[12.5px] text-muted-foreground">
          <tr>
            {head.map((h, i) => (
              <th
                key={i}
                scope="col"
                className={cn(
                  "whitespace-nowrap px-4 py-2 font-semibold",
                  h.startsWith(">") && "text-right",
                )}
              >
                {h.replace(/^>/, "")}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>{children}</tbody>
      </table>
    </div>
  );
}

/** Mutation + success toast + cache refresh. Errors toast; forms can also read `error`. */
export function useAct<V, R>(
  fn: (v: V) => Promise<R>,
  o: {
    success?: string | ((r: R) => string);
    refresh?: string[];
    onDone?: (r: R) => void;
    onError?: (e: Error) => void;
  } = {},
) {
  const qc = useQueryClient();
  return useMutation<R, Error, V>({
    mutationFn: (v) => fn(v),
    onSuccess: (r) => {
      if (o.success) toast.success(typeof o.success === "string" ? o.success : o.success(r));
      (o.refresh ?? []).forEach((k) => void qc.invalidateQueries({ queryKey: [k] }));
      o.onDone?.(r);
    },
    onError: (e) => {
      if (o.onError) o.onError(e);
      else toast.error(e.message);
    },
  });
}

/** Approve / reject with a note. Rejecting always needs one. */
export function DecisionBox({
  onDecide,
  pending,
  approve = "Approve",
  reject = "Reject",
}: {
  onDecide: (d: "approve" | "reject", note: string) => void;
  pending: boolean;
  approve?: string;
  reject?: string;
}) {
  const [note, setNote] = useState("");
  const [err, setErr] = useState<string>();
  return (
    <div className="space-y-2">
      <Field label="Note" error={err} help={`Required to ${reject.toLowerCase()}.`}>
        <TextArea
          value={note}
          onChange={(v) => {
            setNote(v);
            setErr(undefined);
          }}
          rows={2}
          maxLength={500}
        />
      </Field>
      <div className="flex flex-wrap gap-2">
        <Button size="sm" disabled={pending} onClick={() => onDecide("approve", note)}>
          {approve}
        </Button>
        <Button
          size="sm"
          variant="outline"
          disabled={pending}
          onClick={() =>
            note.trim()
              ? onDecide("reject", note)
              : setErr(`Write a note before you ${reject.toLowerCase()}.`)
          }
        >
          {reject}
        </Button>
      </div>
    </div>
  );
}

/** Links between pages of one module; hidden items need a permission the user lacks. */
export function SubNav({
  pid,
  items,
}: {
  pid: string;
  items: { to: NonNullable<LinkProps["to"]>; label: string; perm?: string; exact?: boolean }[];
}) {
  const { access } = useAccess();
  const shown = items.filter((i) => !i.perm || access?.permissions.includes(i.perm));
  if (shown.length < 2) return null;
  return (
    <nav aria-label="Section" className="mb-5 flex gap-1 overflow-x-auto border-b">
      {shown.map((i) => (
        <Link
          key={i.to}
          to={i.to}
          params={{ pid } as never}
          activeOptions={{ exact: !!i.exact }}
          className="whitespace-nowrap border-b-2 border-transparent px-3 py-2 text-[13px] font-medium text-muted-foreground hover:text-foreground"
          activeProps={{ className: "!border-primary !text-foreground" }}
        >
          {i.label}
        </Link>
      ))}
    </nav>
  );
}

/** Authenticated file download (templates, exports, evidence). */
export function DownloadButton({
  path,
  children,
  size = "sm",
  variant = "outline",
}: {
  path: string;
  children: ReactNode;
  size?: "sm" | "default";
  variant?: "outline" | "default" | "ghost";
}) {
  const m = useMutation({
    mutationFn: () => downloadFile(path),
    onError: (e) => toast.error(e.message),
  });
  return (
    <Button
      type="button"
      size={size}
      variant={variant}
      disabled={m.isPending}
      onClick={() => m.mutate()}
    >
      {m.isPending ? <Loader2 className="animate-spin" /> : <Download />}
      {children}
    </Button>
  );
}

export function Dl({ items, cols = 3 }: { items: [string, ReactNode][]; cols?: 1 | 2 | 3 }) {
  return (
    <dl
      className={cn(
        "grid gap-x-6 gap-y-4 text-[13px]",
        cols === 3 ? "sm:grid-cols-3" : cols === 2 ? "sm:grid-cols-2" : "",
      )}
    >
      {items.map(([l, v]) => (
        <div key={l}>
          <dt className="text-[12px] text-muted-foreground">{l}</dt>
          <dd className="break-words font-medium">{v === undefined || v === "" ? "—" : v}</dd>
        </div>
      ))}
    </dl>
  );
}
