// src/components/keywords/brief-panel.tsx
"use client";

import { ChevronRightIcon, CopyIcon } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Pill } from "@/components/ui/pill";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { KeywordBrief } from "@/lib/keywords/ytg-types";
import { cn } from "@/lib/utils";

/** A labelled block (no per-section collapse) — laid out inside a columns grid. */
function Block({
  title,
  count,
  children,
}: {
  title: string;
  count?: number;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-1">
      <div className="font-medium text-sm">
        {title}
        {count != null ? (
          <span className="text-muted-foreground text-xs"> ({count})</span>
        ) : null}
      </div>
      {children}
    </div>
  );
}

function BulletList({ items }: { items: string[] }) {
  return (
    <ul className="list-disc space-y-1 pl-4 text-muted-foreground text-sm">
      {items.map((it) => (
        <li key={it}>{it}</li>
      ))}
    </ul>
  );
}

function Chips({ label, items }: { label: string; items: string[] }) {
  function copy() {
    void navigator.clipboard?.writeText(items.join(", ")).catch(() => {});
  }
  return (
    <Block title={label} count={items.length}>
      <Button
        size="sm"
        variant="ghost"
        onClick={copy}
        aria-label={`Copier ${label}`}
        className="-ml-2 mb-1 h-7"
      >
        <CopyIcon className="size-3.5" /> Copier
      </Button>
      <div className="flex flex-wrap gap-1">
        {items.map((t) => (
          <span
            key={t}
            className="rounded-md border border-border/60 bg-muted/40 px-1.5 py-0.5 text-xs"
          >
            {t}
          </span>
        ))}
      </div>
    </Block>
  );
}

/** One country's brief: a single collapse, content laid out in 2 columns. */
function CountryBrief({ brief }: { brief: KeywordBrief }) {
  const [open, setOpen] = useState(true);
  return (
    <Collapsible open={open} onOpenChange={setOpen}>
      <CollapsibleTrigger className="flex w-full items-center gap-2 py-1.5 text-left">
        <ChevronRightIcon
          className={cn(
            "size-4 shrink-0 text-muted-foreground transition-transform",
            open && "rotate-90",
          )}
          aria-hidden
        />
        <span className="font-medium">{brief.query}</span>
        <span className="text-muted-foreground text-xs">{brief.language}</span>
        {brief.primaryIntent ? (
          <Pill accent="primary">{brief.primaryIntent}</Pill>
        ) : null}
      </CollapsibleTrigger>
      <CollapsibleContent className="pt-2">
        <div className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
          {brief.objectives.length ? (
            <Block title="Objectifs" count={brief.objectives.length}>
              <BulletList items={brief.objectives} />
            </Block>
          ) : null}
          {brief.keySubjects.length ? (
            <Block title="Sujets clés" count={brief.keySubjects.length}>
              <BulletList items={brief.keySubjects} />
            </Block>
          ) : null}
          {brief.questions.length ? (
            <Block title="Questions" count={brief.questions.length}>
              <BulletList items={brief.questions} />
            </Block>
          ) : null}
          {brief.tone.length || brief.style.length ? (
            <Block title="Ton & style">
              {brief.tone.length ? <BulletList items={brief.tone} /> : null}
              {brief.style.length ? <BulletList items={brief.style} /> : null}
            </Block>
          ) : null}
          {brief.valueProps.length ? (
            <Block title="Value props" count={brief.valueProps.length}>
              <BulletList items={brief.valueProps} />
            </Block>
          ) : null}
        </div>
        <div className="mt-5 grid gap-x-8 gap-y-4 sm:grid-cols-2">
          {brief.topTerms.length ? (
            <Chips label="Top terms" items={brief.topTerms} />
          ) : null}
          {brief.entities.length ? (
            <Chips label="Entités" items={brief.entities} />
          ) : null}
          {brief.twoGrams.length ? (
            <Chips label="2-grams" items={brief.twoGrams} />
          ) : null}
          {brief.threeGrams.length ? (
            <Chips label="3-grams" items={brief.threeGrams} />
          ) : null}
        </div>
      </CollapsibleContent>
    </Collapsible>
  );
}

export function BriefPanel({
  briefs,
}: {
  briefs: Record<string, KeywordBrief>;
}) {
  const entries = Object.entries(briefs);
  // Hooks must run unconditionally — compute initial tab before any early return.
  const [active, setActive] = useState(entries[0]?.[0] ?? "");
  if (entries.length === 0) return null;
  return (
    <Tabs value={active} onValueChange={setActive}>
      <TabsList>
        {entries.map(([country]) => (
          <TabsTrigger key={country} value={country}>
            {country}
          </TabsTrigger>
        ))}
      </TabsList>
      {entries.map(([country, brief]) => (
        <TabsContent key={country} value={country} className="mt-3">
          <CountryBrief brief={brief} />
        </TabsContent>
      ))}
    </Tabs>
  );
}
