"use client";

import { useState } from "react";
import { Building2, ClipboardList, Factory, FlaskConical, PackageCheck, Receipt, RotateCcw, Ship, Sparkles, Trash2, Users } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
import { confirmAction, notify } from "../components/ui/feedback-store";
import { describeError } from "../lib/useAsyncAction";
import { formatDate } from "../lib/format";
import { loadSampleData, previewSampleRemoval, removeSampleData, useOnboarding } from "./useOnboarding";

const FLASH_KEY = "onboarding.flash";

function flashAfterReload(title, detail) {
  try { window.sessionStorage.setItem(FLASH_KEY, JSON.stringify({ title, detail })); } catch { notify.success(title, detail); }
}

/** Shows a toast queued before a reload (called once by the shell on mount). */
export function showQueuedFlash() {
  try {
    const flash = JSON.parse(window.sessionStorage.getItem(FLASH_KEY) || "null");
    window.sessionStorage.removeItem(FLASH_KEY);
    if (flash?.title) notify.success(flash.title, flash.detail);
  } catch {
    // Nothing queued, or storage blocked.
  }
}

export const SAMPLE_LOADING_TEXT = "Setting up Riverbend Knit, Nordvik Apparel and 7 orders…";

const plural = (count, one, many) => `${count} ${count === 1 ? one : many}`;
const pick = (counts, ...keys) => Number(keys.map((key) => counts?.[key]).find((value) => value !== undefined && value !== null) ?? 0);

// "the 2 sample buyers, 3 sample factories, 4 orders"
function removalSummary(counts) {
  const parts = [
    [pick(counts, "buyers"), "sample buyer", "sample buyers"],
    [pick(counts, "factories"), "sample factory", "sample factories"],
    [pick(counts, "purchaseOrders", "purchase_orders"), "order", "orders"],
  ].filter(([count]) => count > 0).map(([count, one, many]) => plural(count, one, many));
  if (!parts.length) return "all sample records";
  return `the ${parts.length > 1 ? `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}` : parts[0]}`;
}

/**
 * Load and remove the sample buying house (design §3.8, S8). Removal previews what goes and what stays (sample
 * buyers/factories your own records use are kept as normal records), confirms, then deletes in one step.
 */
export function useSampleActions() {
  const [pending, setPending] = useState(null);

  const load = async () => {
    setPending("load");
    try {
      const data = await loadSampleData();
      notify.success("Sample buying house loaded", "Nordvik Apparel and Harbor & Pine are ready. Click anything; nothing here is real.");
      return data;
    } catch (error) {
      notify.error(error?.status === 409 ? "The sample is already loaded" : "The sample could not be loaded", describeError(error));
      return null;
    } finally {
      setPending(null);
    }
  };

  const remove = async () => {
    setPending("remove");
    try {
      const preview = await previewSampleRemoval();
      const kept = preview.kept.map((item) => `${item.name}${item.usedBy?.length ? ` (used by ${item.usedBy.join(", ")})` : ""}`);
      const keptText = kept.length ? ` Kept because your own records use ${kept.length === 1 ? "it" : "them"}: ${kept.join("; ")}. ${kept.length === 1 ? "It stays as a normal record" : "They stay as normal records"}.` : "";
      setPending(null);
      const confirmed = await confirmAction({
        title: "Remove all sample data?",
        message: `This deletes ${removalSummary(preview.counts)} and everything linked to them. Your own records stay exactly as they are.${keptText}`,
        confirmLabel: "Remove sample data",
        tone: "danger",
      });
      if (!confirmed) return null;
      setPending("remove");
      const result = await removeSampleData();
      // Lists and records on screen still show sample rows: reload (or leave a sample record) and toast afterwards.
      flashAfterReload("Sample data removed", "Your workspace now shows only your real records.");
      if (/\/(PO-SAMPLE-|S-INQ-|SHP-SAMPLE-|SMP-)/i.test(window.location.pathname)) window.location.assign("/");
      else window.location.reload();
      return result;
    } catch (error) {
      notify.error("The sample could not be removed", describeError(error));
      return null;
    } finally {
      setPending(null);
    }
  };

  return { load, remove, pending, isLoading: pending === "load", isRemoving: pending === "remove" };
}

const COUNT_ROWS = [
  { keys: ["buyers"], one: "buyer", many: "buyers", icon: Building2 },
  { keys: ["factories"], one: "factory", many: "factories", icon: Factory },
  { keys: ["inquiries"], one: "inquiry", many: "inquiries", icon: ClipboardList },
  { keys: ["purchaseOrders", "purchase_orders"], one: "order", many: "orders", icon: PackageCheck },
  { keys: ["shipments"], one: "shipment", many: "shipments", icon: Ship },
  { keys: ["invoices"], one: "invoice", many: "invoices", icon: Receipt },
  { keys: ["users"], one: "teammate", many: "teammates", icon: Users },
];

/** Right-column card on Get started: load, see what is in it, remove. Hidden for users who cannot manage the org. */
export function SampleDataCard({ className }) {
  const { data } = useOnboarding({ enabled: false });
  const actions = useSampleActions();
  if (!data) return null;
  const { sample, me } = data;
  const canManage = me.canManage || me.isOwner;
  if (!canManage && sample.status !== "loaded") return null;

  if (actions.isLoading) {
    return <Card className={cn("gap-3", className)} aria-busy="true">
      <CardHeader><CardTitle className="flex items-center gap-2 text-base"><FlaskConical className="size-4 text-muted-foreground" /> Sample buying house</CardTitle></CardHeader>
      <CardContent className="flex items-center gap-3 text-sm text-muted-foreground" role="status"><Spinner /> {SAMPLE_LOADING_TEXT}</CardContent>
    </Card>;
  }

  if (sample.status === "removed") {
    const removedAt = data.profile?.sampleRemovedAt;
    return <p className={cn("flex flex-wrap items-center gap-x-1 px-1 text-xs text-muted-foreground", className)}>
      Sample removed{removedAt ? ` on ${formatDate(removedAt)}` : ""} ·
      {canManage && <Button variant="link" size="sm" className="h-auto p-0 text-xs" onClick={actions.load}><RotateCcw className="size-3" /> Load again</Button>}
    </p>;
  }

  if (sample.status === "loaded") {
    const rows = COUNT_ROWS.map((row) => ({ ...row, count: pick(sample.counts, ...row.keys) })).filter((row) => row.count > 0);
    return <Card className={cn("gap-4 border-info/30", className)}>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-base"><FlaskConical className="size-4 text-info" /> Sample buying house</CardTitle>
        <CardDescription>Made-up records to click through{sample.loadedAt ? `, loaded ${formatDate(sample.loadedAt)}` : ""}. Your setup progress ignores them.</CardDescription>
        <CardAction><Badge variant="info">Loaded</Badge></CardAction>
      </CardHeader>
      {rows.length > 0 && <CardContent>
        <ul className="grid grid-cols-2 gap-2 text-sm">
          {rows.map((row) => <li key={row.one} className="flex items-center gap-2 rounded-md bg-muted/40 px-2.5 py-1.5">
            <row.icon className="size-3.5 text-muted-foreground" aria-hidden="true" />
            <span className="tabular-nums">{plural(row.count, row.one, row.many)}</span>
          </li>)}
        </ul>
      </CardContent>}
      {canManage && <CardFooter>
        <Button variant="outline" size="sm" onClick={actions.remove} disabled={actions.isRemoving}>{actions.isRemoving ? <Spinner /> : <Trash2 />} Remove sample data</Button>
      </CardFooter>}
    </Card>;
  }

  return <Card className={cn("gap-4", className)}>
    <CardHeader>
      <CardTitle className="flex items-center gap-2 text-base"><Sparkles className="size-4 text-muted-foreground" /> See a full buying house in action</CardTitle>
      <CardDescription>Two made-up buyers and seven orders at every stage, from inquiry to payment. Click anything; remove it in one click.</CardDescription>
    </CardHeader>
    <CardFooter>
      <Button variant="outline" size="sm" onClick={actions.load}><FlaskConical /> Load sample data</Button>
    </CardFooter>
  </Card>;
}
