"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
  CheckCircle2,
  ChevronDown,
  ChevronUp,
  Circle,
  Copy,
  ExternalLink,
  FileText,
  Landmark,
  Lightbulb,
  Users,
} from "lucide-react";
import {
  buildCapabilityStatement,
  FEDERAL_GLOSSARY,
  FEDERAL_WORK_STEPS,
  getFederalWorkContext,
} from "@/lib/federal-work/guide";
import type { Business } from "@/lib/types";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

interface FederalPeer {
  piid: string;
  recipientName: string;
  awardAmount: number;
  state: string | null;
  agency: string;
}

interface FederalWorkGuideProps {
  business: Business;
  onImportSam: () => void;
  samLoading: boolean;
}

function checklistKey(businessId: string) {
  return `brandlxft-federal-checklist-${businessId}`;
}

export function FederalWorkGuide({ business, onImportSam, samLoading }: FederalWorkGuideProps) {
  const ctx = useMemo(() => getFederalWorkContext(business), [business]);
  const [completed, setCompleted] = useState<string[]>([]);
  const [expandedStep, setExpandedStep] = useState<string>("understand");
  const [showGlossary, setShowGlossary] = useState(false);
  const [showCapability, setShowCapability] = useState(false);
  const [peers, setPeers] = useState<FederalPeer[]>([]);
  const [piidPaste, setPiidPaste] = useState<string>("");
  const [peersLoading, setPeersLoading] = useState(false);
  const [copied, setCopied] = useState<string | null>(null);

  const capabilityStatement = useMemo(() => buildCapabilityStatement(business), [business]);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(checklistKey(business.id));
      if (raw) setCompleted(JSON.parse(raw) as string[]);
    } catch {
      /* ignore */
    }
  }, [business.id]);

  useEffect(() => {
    setPeersLoading(true);
    fetch("/api/federal-work/peers", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        industry: business.input.industry,
        industryCategory: business.input.industryCategory,
        location: business.input.location,
      }),
    })
      .then((r) => r.json())
      .then((data: { peers?: FederalPeer[]; piidPaste?: string }) => {
        setPeers(data.peers ?? []);
        setPiidPaste(data.piidPaste ?? "");
      })
      .catch(() => setPeers([]))
      .finally(() => setPeersLoading(false));
  }, [business.input.industry, business.input.industryCategory, business.input.location]);

  const toggleStep = useCallback(
    (stepId: string) => {
      setCompleted((prev) => {
        const next = prev.includes(stepId) ? prev.filter((id) => id !== stepId) : [...prev, stepId];
        localStorage.setItem(checklistKey(business.id), JSON.stringify(next));
        return next;
      });
    },
    [business.id],
  );

  useEffect(() => {
    if (ctx.federalOpportunityCount > 0 && !completed.includes("find")) {
      setCompleted((prev) => {
        if (prev.includes("find")) return prev;
        const next = [...prev, "find"];
        localStorage.setItem(checklistKey(business.id), JSON.stringify(next));
        return next;
      });
    }
  }, [ctx.federalOpportunityCount, completed, business.id]);

  const progress = Math.round(
    (FEDERAL_WORK_STEPS.filter((s) => completed.includes(s.id)).length / FEDERAL_WORK_STEPS.length) * 100,
  );

  const copyText = async (text: string, label: string) => {
    await navigator.clipboard.writeText(text);
    setCopied(label);
    setTimeout(() => setCopied(null), 2000);
  };

  return (
    <div className="space-y-4">
      <Card className="border-emerald-500/25 bg-gradient-to-br from-emerald-500/10 via-slate-900/40 to-indigo-500/5">
        <CardHeader>
          <CardTitle className="flex flex-wrap items-center gap-2 text-lg">
            <Landmark className="h-5 w-5 text-emerald-400" />
            Federal Work — simplified for small business
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm leading-relaxed text-slate-300">
            Most landscaping, plumbing, HVAC, cleaning, and trades shops never hear about federal contracting — yet
            agencies award{" "}
            <span className="font-medium text-emerald-300">
              {ctx.marketStats.smallBusinessContracts > 0
                ? `${ctx.marketStats.smallBusinessContracts.toLocaleString()}+`
                : "thousands of"}
            </span>{" "}
            small contracts ($10K–$250K) in codes matching{" "}
            <span className="text-slate-100">{ctx.industry}</span>
            {ctx.state ? ` in ${ctx.state}` : ""}. BrandLxft walks you through registration, finding bids, and your
            first proposal — in plain English.
          </p>

          <div className="flex flex-wrap items-center gap-3">
            <Badge className="border-emerald-500/30 bg-emerald-500/10 text-emerald-200">
              Checklist {progress}% complete
            </Badge>
            {ctx.isHomeServicesTrade ? (
              <Badge className="border-amber-500/30 bg-amber-500/10 text-amber-200">Home services & trades</Badge>
            ) : null}
            {ctx.federalOpportunityCount > 0 ? (
              <Badge className="border-indigo-500/30 bg-indigo-500/10 text-indigo-200">
                {ctx.federalOpportunityCount} live bid{ctx.federalOpportunityCount === 1 ? "" : "s"} imported
              </Badge>
            ) : null}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Your 6-step path to federal work</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          {FEDERAL_WORK_STEPS.map((step, index) => {
            const done = completed.includes(step.id);
            const open = expandedStep === step.id;
            return (
              <div
                key={step.id}
                className="rounded-xl border border-slate-800/80 bg-slate-950/40"
              >
                <button
                  type="button"
                  className="flex w-full items-start gap-3 p-4 text-left"
                  onClick={() => setExpandedStep(open ? "" : step.id)}
                >
                  <span className="mt-0.5 shrink-0">
                    {done ? (
                      <CheckCircle2 className="h-5 w-5 text-emerald-400" />
                    ) : (
                      <Circle className="h-5 w-5 text-slate-600" />
                    )}
                  </span>
                  <span className="flex-1">
                    <span className="text-xs font-medium uppercase tracking-wide text-slate-500">
                      Step {index + 1}
                    </span>
                    <span className="mt-0.5 block font-medium text-slate-100">{step.title}</span>
                    <span className="mt-1 block text-sm text-slate-400">{step.summary}</span>
                  </span>
                  {open ? (
                    <ChevronUp className="h-4 w-4 shrink-0 text-slate-500" />
                  ) : (
                    <ChevronDown className="h-4 w-4 shrink-0 text-slate-500" />
                  )}
                </button>

                {open ? (
                  <div className="space-y-3 border-t border-slate-800/80 px-4 pb-4 pt-3">
                    <p className="text-sm leading-relaxed text-slate-400">{step.detail}</p>

                    {step.id === "naics" ? (
                      <div className="rounded-lg border border-slate-800 bg-slate-900/60 p-3">
                        <p className="mb-2 text-xs uppercase tracking-wide text-slate-500">
                          Your recommended NAICS codes
                        </p>
                        <ul className="space-y-1.5 text-sm text-slate-300">
                          {ctx.naicsCodes.map((n) => (
                            <li key={n.code}>
                              <span className="font-mono text-emerald-300">{n.code}</span> — {n.label}
                            </li>
                          ))}
                        </ul>
                        <p className="mt-2 text-xs text-slate-500">
                          Add these to your SAM.gov entity profile when registering.
                        </p>
                      </div>
                    ) : null}

                    {step.id === "find" ? (
                      <div className="flex flex-wrap gap-2">
                        <Button size="sm" onClick={onImportSam} disabled={samLoading} className="gap-2">
                          <Landmark className="h-3.5 w-3.5" />
                          {samLoading ? "Searching…" : "Import matched bids"}
                        </Button>
                        {step.href ? (
                          <Link href={step.href} target="_blank" rel="noopener noreferrer">
                            <Button size="sm" variant="outline" className="gap-2">
                              {step.hrefLabel}
                              <ExternalLink className="h-3.5 w-3.5" />
                            </Button>
                          </Link>
                        ) : null}
                      </div>
                    ) : null}

                    {step.id === "capability" ? (
                      <div className="space-y-2">
                        <Button
                          size="sm"
                          variant="outline"
                          className="gap-2"
                          onClick={() => setShowCapability((v) => !v)}
                        >
                          <FileText className="h-3.5 w-3.5" />
                          {showCapability ? "Hide" : "Generate"} capability statement draft
                        </Button>
                        {showCapability ? (
                          <div className="relative">
                            <pre className="max-h-64 overflow-auto rounded-lg border border-slate-800 bg-slate-950 p-3 text-xs leading-relaxed text-slate-300 whitespace-pre-wrap font-sans">
                              {capabilityStatement}
                            </pre>
                            <Button
                              size="sm"
                              variant="outline"
                              className="mt-2 gap-2"
                              onClick={() => copyText(capabilityStatement, "capability")}
                            >
                              <Copy className="h-3.5 w-3.5" />
                              {copied === "capability" ? "Copied!" : "Copy to clipboard"}
                            </Button>
                          </div>
                        ) : null}
                      </div>
                    ) : null}

                    {step.href && step.id !== "find" ? (
                      <Link href={step.href} target="_blank" rel="noopener noreferrer">
                        <Button size="sm" variant="outline" className="gap-2">
                          {step.hrefLabel}
                          <ExternalLink className="h-3.5 w-3.5" />
                        </Button>
                      </Link>
                    ) : null}

                    <Button
                      size="sm"
                      variant={done ? "outline" : "default"}
                      onClick={() => toggleStep(step.id)}
                    >
                      {done ? "Mark incomplete" : "Mark complete"}
                    </Button>
                  </div>
                ) : null}
              </div>
            );
          })}
        </CardContent>
      </Card>

      <div className="grid gap-4 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Users className="h-4 w-4 text-sky-400" />
              Companies like yours winning federal work
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <p className="text-sm text-slate-400">
              Real small-business awards ($25K–$750K){ctx.state ? ` in ${ctx.state}` : ""} from USAspending — proof
              your trade gets federal work.
            </p>
            {peersLoading ? (
              <p className="text-sm text-slate-500">Loading peer examples…</p>
            ) : peers.length === 0 ? (
              <p className="text-sm text-slate-500">No peer examples found — try importing live bids above.</p>
            ) : (
              <ul className="space-y-2">
                {peers.map((p) => (
                  <li
                    key={p.piid}
                    className="rounded-lg border border-slate-800/80 bg-slate-950/50 px-3 py-2 text-sm"
                  >
                    <p className="font-medium text-slate-200">{p.recipientName}</p>
                    <p className="text-xs text-slate-500">
                      PIID <span className="font-mono text-slate-400">{p.piid}</span> · $
                      {p.awardAmount.toLocaleString()}
                      {p.state ? ` · ${p.state}` : ""}
                    </p>
                  </li>
                ))}
              </ul>
            )}
            {piidPaste ? (
              <Button
                size="sm"
                variant="outline"
                className="gap-2"
                onClick={() => copyText(piidPaste, "piids")}
              >
                <Copy className="h-3.5 w-3.5" />
                {copied === "piids" ? "PIIDs copied!" : "Copy PIIDs for SAM.gov Contract Detail"}
              </Button>
            ) : null}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Lightbulb className="h-4 w-4 text-amber-400" />
              Jargon decoder
            </CardTitle>
          </CardHeader>
          <CardContent>
            <button
              type="button"
              className="mb-3 text-sm text-sky-400 hover:underline"
              onClick={() => setShowGlossary((v) => !v)}
            >
              {showGlossary ? "Hide" : "Show"} plain-English definitions
            </button>
            {showGlossary ? (
              <dl className="space-y-2">
                {FEDERAL_GLOSSARY.map((item) => (
                  <div key={item.term} className="rounded-lg border border-slate-800/60 px-3 py-2">
                    <dt className="text-sm font-medium text-slate-200">{item.term}</dt>
                    <dd className="text-sm text-slate-400">{item.plain}</dd>
                  </div>
                ))}
              </dl>
            ) : (
              <p className="text-sm text-slate-500">
                SAM.gov, UEI, NAICS, PIID, set-asides — the acronyms stop most owners from even starting. We translate
                them here.
              </p>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
