"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowRight, BookOpen, Building2, CheckCircle2, EyeOff, FlaskConical, LifeBuoy, ListChecks, MessageCircle, PackagePlus, PartyPopper, Rocket, Undo2,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { FieldGroup } from "@/components/ui/field";
import { Progress } from "@/components/ui/progress";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { FormErrorAlert, TextField } from "@/components/app/form-fields";
import { PageContent, PageHeader, SectionCard } from "@/components/app/page";
import { cn } from "@/lib/utils";
import ProtectedRoute from "../auth/protected-route";
import { useAuth } from "../auth/auth-context";
import AppShell from "../components/app-shell";
import { ErrorState } from "../components/ui/page-states";
import { useAsyncAction } from "../lib/useAsyncAction";
import { FlowMap } from "./flow-map";
import { SampleDataCard } from "./sample-data-card";
import { openQuickOrder, useQuickBuyerForm } from "./useQuickOrderForm";
import { roleTasks } from "./useWelcomeFlow";
import { skipChecklistItem, trackOnboardingEvent, unskipChecklistItem, updateOnboardingMe, useOnboarding } from "./useOnboarding";

export function GetStartedPage() {
  return <ProtectedRoute><AppShell title="Get started"><GetStarted /></AppShell></ProtectedRoute>;
}

// Button label for each checklist item's main action (the server sends the action type and links).
const ACTION_LABELS = {
  organization: "Review",
  first_buyer: "Add a buyer",
  first_order: "Put in a running order",
  plan_order: "Plan it",
  invite_team: "Invite a merchandiser",
};
const SKIP_LABELS = { invite_team: "I work alone for now" };

function GetStarted() {
  const { organization } = useAuth();
  const onboarding = useOnboarding();
  const tracked = useRef(false);
  const data = onboarding.data;

  useEffect(() => {
    if (!data || tracked.current) return;
    tracked.current = true;
    trackOnboardingEvent("get_started_viewed");
  }, [data]);

  if (onboarding.isLoading) return <GetStartedSkeleton />;
  if (!data) return <PageContent className="max-w-6xl"><ErrorState error={onboarding.error} title="Get started could not load" onRetry={onboarding.refresh} backHref="/" backLabel="Back to dashboard" /></PageContent>;

  const orgName = organization?.name || "your buying house";
  const manage = data.me.canManage || data.me.isOwner;
  return manage ? <OwnerHub data={data} orgName={orgName} /> : <RoleHub data={data} orgName={orgName} />;
}

function GetStartedSkeleton() {
  return <PageContent className="max-w-6xl" aria-busy="true">
    <div className="grid gap-2"><Skeleton className="h-8 w-72" /><Skeleton className="h-4 w-full max-w-xl" /><Skeleton className="h-5 w-24 rounded-full" /></div>
    <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_340px]">
      <div className="grid content-start gap-3 rounded-xl border p-6">{Array.from({ length: 5 }).map((_, index) => <div key={index} className="flex items-center gap-3"><Skeleton className="size-9 rounded-full" /><div className="grid flex-1 gap-2"><Skeleton className="h-4 w-1/2" /><Skeleton className="h-3 w-3/4" /></div><Skeleton className="h-8 w-28" /></div>)}</div>
      <div className="grid content-start gap-6"><Skeleton className="h-40 rounded-xl" /><Skeleton className="h-80 rounded-xl" /></div>
    </div>
  </PageContent>;
}

/* ---------- Owner / organization.manage ---------- */

function OwnerHub({ data, orgName }) {
  const router = useRouter();
  const { checklist } = data;
  const [buyerOpen, setBuyerOpen] = useState(false);
  const actions = useAsyncAction();
  const percent = checklist.total ? Math.round((checklist.done / checklist.total) * 100) : 0;
  const neededNow = data.justInTime.filter((item) => !item.done && !item.skipped);

  const runItem = (item) => {
    if (item.action === "quick_order") return openQuickOrder("get_started");
    if (item.action === "quick_buyer") return setBuyerOpen(true);
    return router.push(item.startHref || item.href || "/");
  };

  const hide = () => actions.run("hide", () => updateOnboardingMe({ hide_get_started: true }), { success: "Get started is hidden", successDetail: "Find it again any time: press / and type “Get started”." })
    .then((ok) => { if (ok) router.push("/"); });

  return <PageContent className="max-w-6xl">
    <PageHeader
      title={`Get ${orgName} running`}
      description="Your first order on the board is the big step. Everything else can wait until you need it."
      meta={<>
        <Badge variant="outline" className="tabular-nums">{checklist.done} of {checklist.total} done</Badge>
        <Progress value={percent} aria-label={`${checklist.done} of ${checklist.total} steps done`} className={cn("h-1.5 w-32", checklist.complete && "*:data-[slot=progress-indicator]:bg-success")} />
      </>}
    />

    {checklist.complete && <Card role="status" className="border-success/30 bg-success/5 py-4 motion-safe:animate-in motion-safe:fade-in motion-safe:duration-500">
      <CardContent className="flex flex-col gap-4 px-4 sm:flex-row sm:items-center">
        <span className="grid size-10 shrink-0 place-items-center rounded-full bg-success/15 text-success"><PartyPopper className="size-5" aria-hidden="true" /></span>
        <div className="min-w-0 flex-1">
          <p className="font-medium">{orgName} is running.</p>
          <p className="text-sm text-muted-foreground">Your orders now show risks and next actions on the dashboard.</p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button variant="ghost" size="sm" onClick={hide} disabled={actions.isPending("hide")}>{actions.isPending("hide") ? <Spinner /> : <EyeOff />} Hide Get started from the sidebar</Button>
          <Button size="sm" asChild><Link href="/">Go to dashboard <ArrowRight /></Link></Button>
        </div>
      </CardContent>
    </Card>}

    <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_340px] lg:items-start">
      <div className="grid min-w-0 gap-6">
        {neededNow.length > 0 && <Card className="gap-3 border-warning/40 py-4">
          <CardHeader className="px-4"><CardTitle className="text-base">Needed now</CardTitle><CardDescription>These came up because of what your orders are doing.</CardDescription></CardHeader>
          <CardContent className="grid gap-3 px-4">
            {neededNow.map((item) => <div key={item.key} className="flex flex-col gap-3 rounded-lg border p-3 sm:flex-row sm:items-center">
              <div className="min-w-0 flex-1"><p className="text-sm font-medium">{item.title}</p>{item.why && <p className="text-sm text-muted-foreground">{item.why}</p>}</div>
              <div className="flex flex-wrap gap-2">
                {item.skippable !== false && <Button size="sm" variant="ghost" onClick={() => actions.run(`skip-${item.key}`, () => skipChecklistItem(item.key), { success: "Moved to later", successDetail: "Add it any time under Settings, Payments." })} disabled={actions.isBusy}>I&apos;ll do this later</Button>}
                <Button size="sm" variant="outline" asChild><Link href={item.href || "/settings/payments"}>Open <ArrowRight /></Link></Button>
              </div>
            </div>)}
          </CardContent>
        </Card>}

        <SectionCard title="Set up your house" icon={ListChecks} description="In this order. Each step says why it matters and how long it takes.">
          <ol className="grid divide-y" aria-label="Setup checklist">
            {checklist.items.map((item, index) => <ChecklistRow key={item.key} item={item} index={index} isNext={checklist.next === item.key} onRun={() => runItem(item)} />)}
          </ol>
        </SectionCard>

        {data.sample.status === "loaded" && data.sampleTasks.length > 0 && <SampleTasks tasks={data.sampleTasks} />}

        {data.optional.length > 0 && <SectionCard title="Make it yours (optional)" icon={Rocket} collapsible summary="Starter templates are in place" description="Tailor the defaults when you are ready. Nothing here blocks your orders.">
          <ul className="grid divide-y">
            {data.optional.map((item) => <li key={item.key} className="flex items-center gap-3 py-3 first:pt-0 last:pb-0">
              <span className={cn("grid size-7 shrink-0 place-items-center rounded-full bg-muted text-muted-foreground", (item.done || item.status === "done") && "bg-success/10 text-success")}>
                {item.done || item.status === "done" ? <CheckCircle2 className="size-4" aria-label="Done" /> : <span className="size-1.5 rounded-full bg-current" aria-hidden="true" />}
              </span>
              <div className="min-w-0 flex-1"><p className="text-sm font-medium">{item.title}</p>{item.status && item.status !== "done" && item.status !== "todo" && <p className="text-xs text-muted-foreground">{item.status}</p>}</div>
              {item.href && <Button variant="ghost" size="sm" asChild><Link href={item.href} aria-label={`Open: ${item.title}`}>Open <ArrowRight /></Link></Button>}
            </li>)}
          </ul>
        </SectionCard>}
      </div>

      <aside className="grid min-w-0 gap-6" aria-label="Help and sample data">
        <SampleDataCard />
        <FlowMap />
        <NeedAHand />
      </aside>
    </div>

    <QuickBuyerDialog open={buyerOpen} onOpenChange={setBuyerOpen} />
  </PageContent>;
}

function ChecklistRow({ item, index, isNext, onRun }) {
  const skip = useAsyncAction();
  const done = item.status === "done";
  const skipped = item.status === "skipped";
  const label = ACTION_LABELS[item.key] || "Start";

  if (done) {
    return <li className="flex items-center gap-3 py-3 first:pt-0 last:pb-0">
      <span className="grid size-9 shrink-0 place-items-center rounded-full bg-success/10 text-success"><CheckCircle2 className="size-5" aria-hidden="true" /></span>
      <p className="min-w-0 flex-1 text-sm"><span className="sr-only">Done: </span><span className="font-medium">{item.title}</span>{item.subStatus && <span className="text-muted-foreground"> · {item.subStatus}</span>}</p>
      {item.href && <Button variant="ghost" size="sm" asChild><Link href={item.href} aria-label={`Review: ${item.title}`}>Review</Link></Button>}
    </li>;
  }

  return <li className={cn("flex flex-col gap-3 py-4 first:pt-0 last:pb-0 sm:flex-row sm:items-start", skipped && "opacity-70")}>
    <div className="flex min-w-0 flex-1 gap-3">
      <span className={cn("grid size-9 shrink-0 place-items-center rounded-full border text-sm font-semibold tabular-nums text-muted-foreground", isNext && "border-primary bg-primary text-primary-foreground motion-safe:animate-in motion-safe:zoom-in-90 motion-safe:duration-500")}>{index + 1}</span>
      <div className="grid min-w-0 gap-1">
        <p className="flex flex-wrap items-center gap-2 text-sm font-medium">
          {item.title}
          {item.estimate && !skipped && <Badge variant="secondary" className="h-5 font-normal">{item.estimate}</Badge>}
          {skipped && <Badge variant="outline" className="h-5 font-normal">Later</Badge>}
        </p>
        {item.why && <p className="text-sm text-muted-foreground">{item.why}</p>}
        {item.subStatus && <p className="text-xs font-medium text-info">{item.subStatus}</p>}
        {item.key === "first_order" && isNext && <p className="text-xs text-muted-foreground">Or <Link href="/inquiries/new" className="underline underline-offset-2 hover:text-foreground">start from an inquiry</Link> if the buyer has not confirmed yet.</p>}
      </div>
    </div>
    <div className="flex flex-wrap items-center gap-2 pl-12 sm:pl-0">
      {skipped
        ? <Button variant="ghost" size="sm" onClick={() => skip.run("undo", () => unskipChecklistItem(item.key))} disabled={skip.isBusy}>{skip.isBusy ? <Spinner /> : <Undo2 />} Put it back</Button>
        : item.skippable && <Button variant="ghost" size="sm" onClick={() => skip.run("skip", () => skipChecklistItem(item.key), { success: "Moved to later", successDetail: "It stays on the list; pick it up whenever you are ready." })} disabled={skip.isBusy}>{skip.isBusy && <Spinner />} {SKIP_LABELS[item.key] || "I'll do this later"}</Button>}
      {!skipped && <Button size="sm" variant={isNext ? "default" : "outline"} onClick={onRun}>
        {item.action === "quick_order" ? <PackagePlus /> : item.action === "quick_buyer" ? <Building2 /> : null}{label}{item.action === "link" || !item.action ? <ArrowRight /> : null}
      </Button>}
    </div>
  </li>;
}

function SampleTasks({ tasks }) {
  const done = tasks.filter((task) => task.done).length;
  return <SectionCard title="Try it on the sample" icon={FlaskConical} description="Five things to try on the made-up orders. Nothing you do here touches real data." actions={<Badge variant="secondary" className="tabular-nums">{done} of {tasks.length}</Badge>}>
    <ol className="grid gap-2">
      {tasks.map((task, index) => <li key={task.key}>
        <Link href={task.href || "/"} className="group flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50">
          <span className={cn("grid size-7 shrink-0 place-items-center rounded-full bg-muted text-xs font-medium tabular-nums text-muted-foreground", task.done && "bg-success/10 text-success")}>
            {task.done ? <CheckCircle2 className="size-4" aria-label="Done" /> : index + 1}
          </span>
          <span className={cn("min-w-0 flex-1 text-sm", task.done && "text-muted-foreground")}>{task.title}</span>
          <ArrowRight className="size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5 motion-reduce:transition-none" aria-hidden="true" />
        </Link>
      </li>)}
    </ol>
  </SectionCard>;
}

function NeedAHand() {
  const whatsapp = process.env.NEXT_PUBLIC_SUPPORT_WHATSAPP;
  return <Card className="gap-4">
    <CardHeader>
      <CardTitle className="flex items-center gap-2 text-base"><LifeBuoy className="size-4 text-muted-foreground" /> Need a hand?</CardTitle>
      <CardDescription>Trade words explained in plain language, with Bangla hints if you turn them on.</CardDescription>
    </CardHeader>
    <CardContent className="flex flex-wrap gap-2">
      <Button variant="outline" size="sm" asChild><Link href="/help/glossary"><BookOpen /> Open the glossary</Link></Button>
      {whatsapp && <Button variant="outline" size="sm" asChild><a href={`https://wa.me/${whatsapp.replace(/[^0-9]/g, "")}`} target="_blank" rel="noreferrer"><MessageCircle /> Talk to us on WhatsApp</a></Button>}
    </CardContent>
  </Card>;
}

function QuickBuyerDialog({ open, onOpenChange }) {
  const { form, submit, guard } = useQuickBuyerForm(() => onOpenChange(false));
  const isSubmitting = form.formState.isSubmitting;

  return <Dialog open={open} onOpenChange={guard.guardOpenChange(onOpenChange)}>
    <DialogContent className="sm:max-w-md">
      <form onSubmit={submit} noValidate className="grid gap-5">
        <DialogHeader>
          <DialogTitle>Add a buyer you work with</DialogTitle>
          <DialogDescription>Just the name for now. We make a short code from it; add contacts and rules on the buyer page later.</DialogDescription>
        </DialogHeader>
        <FormErrorAlert form={form} />
        <FieldGroup>
          <TextField control={form.control} name="name" label="Buyer name" placeholder="e.g. Nordvik Apparel AB" inputProps={{ autoFocus: true, autoComplete: "organization" }} />
        </FieldGroup>
        <DialogFooter>
          <Button type="button" variant="outline" asChild><Link href="/buyers/new">Full buyer profile</Link></Button>
          <Button type="submit" disabled={isSubmitting}>{isSubmitting ? <Spinner /> : <Building2 />} Add buyer</Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>;
}

/* ---------- Staff (no organization.manage): their own first things ---------- */

function RoleHub({ data, orgName }) {
  const tasks = roleTasks(data, data.me.roleFocus);
  const done = tasks.filter((task) => task.done).length;

  return <PageContent className="max-w-6xl">
    <PageHeader title={`Your first things at ${orgName}`} description="Small steps to get comfortable. Each one takes about a minute." meta={<Badge variant="outline" className="tabular-nums">{done} of {tasks.length} done</Badge>} />
    <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_340px] lg:items-start">
      <SectionCard title="Your first things" icon={ListChecks}>
        <ol className="grid gap-2">
          {tasks.map((task, index) => <li key={task.key}>
            <Link href={task.href || "/"} className="group flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50">
              <span className={cn("grid size-8 shrink-0 place-items-center rounded-full bg-muted text-sm font-medium tabular-nums text-muted-foreground", task.done && "bg-success/10 text-success")}>
                {task.done ? <CheckCircle2 className="size-4" aria-label="Done" /> : index + 1}
              </span>
              <span className={cn("min-w-0 flex-1 text-sm font-medium", task.done && "text-muted-foreground")}>{task.title}</span>
              <ArrowRight className="size-4 text-muted-foreground" aria-hidden="true" />
            </Link>
          </li>)}
        </ol>
      </SectionCard>
      <aside className="grid min-w-0 gap-6" aria-label="Help">
        <FlowMap />
        <NeedAHand />
      </aside>
    </div>
  </PageContent>;
}

/* ---------- Dashboard card (replaces the old SetupCard) ---------- */

/** "3 of 5 · Next: Plan your first order". Hidden once complete or when the user hid Get started. */
export function GetStartedCard({ className }) {
  const router = useRouter();
  const { organization } = useAuth();
  const { data } = useOnboarding();
  if (!data || data.me.hideGetStarted) return null;
  const manage = data.me.canManage || data.me.isOwner;

  const tasks = manage ? data.checklist.items : roleTasks(data, data.me.roleFocus);
  const done = manage ? data.checklist.done : tasks.filter((task) => task.done).length;
  const total = manage ? data.checklist.total : tasks.length;
  const complete = manage ? data.checklist.complete : done >= total;
  if (complete || !total) return null;
  const next = manage ? tasks.find((item) => item.key === data.checklist.next) || tasks.find((item) => item.status === "next" || item.status === "todo") : tasks.find((task) => !task.done);
  const percent = Math.round((done / total) * 100);

  const cont = () => {
    if (!next) return router.push("/get-started");
    if (next.action === "quick_order") return openQuickOrder("dashboard_card");
    if (next.action === "quick_buyer") return router.push("/get-started");
    return router.push(next.startHref || next.href || "/get-started");
  };

  return <Card className={cn("gap-3 py-4", className)}>
    <CardContent className="flex flex-col gap-4 px-4 sm:flex-row sm:items-center">
      <span className="grid size-10 shrink-0 place-items-center rounded-full bg-primary/10 text-primary"><Rocket className="size-5" aria-hidden="true" /></span>
      <div className="grid min-w-0 flex-1 gap-1.5">
        <p className="text-sm font-medium">{manage ? `Get ${organization?.name || "your house"} running` : "Your first things"} · <span className="tabular-nums">{done} of {total}</span></p>
        <Progress value={percent} aria-label={`${done} of ${total} done`} className="h-1.5 max-w-sm" />
        {next && <p className="text-xs text-muted-foreground">Next: {next.title}</p>}
      </div>
      <div className="flex gap-2">
        <Button variant="outline" size="sm" asChild><Link href="/get-started">All steps</Link></Button>
        {next && <Button size="sm" onClick={cont}>Continue <ArrowRight /></Button>}
      </div>
    </CardContent>
  </Card>;
}
