"use client";

import { Check } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { SIMILAR_ACCOUNT_CONFIDENCE_LABELS, type ResearchMap, type SuggestedTag } from "@/lib/types/research";

interface SuggestedTagsPickerProps {
  tags: SuggestedTag[];
  selected: string[];
  onToggle: (tag: string) => void;
  onSelectAllAccounts?: () => void;
  /** 置入模式不顯示相似帳號標籤 */
  hideAccounts?: boolean;
  researchMap?: ResearchMap | null;
}

function TagRow({
  item,
  isSelected,
  onToggle,
  confidence,
}: {
  item: SuggestedTag;
  isSelected: boolean;
  onToggle: () => void;
  confidence?: "high" | "medium" | "low" | null;
}) {
  const confidenceLabel = confidence ? SIMILAR_ACCOUNT_CONFIDENCE_LABELS[confidence] : null;
  const confidenceColor =
    confidence === "high"
      ? "bg-emerald-500/10 text-emerald-600 border-emerald-200"
      : confidence === "medium"
        ? "bg-amber-500/10 text-amber-600 border-amber-200"
        : "bg-muted text-muted-foreground border-border";

  return (
    <button
      type="button"
      onClick={onToggle}
      className={cn(
        "flex w-full items-start gap-3 px-3 py-2.5 text-left transition-colors",
        isSelected ? "bg-accent" : "bg-card hover:bg-muted/60"
      )}
    >
      <div
        className={cn(
          "mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded border",
          isSelected
            ? "border-primary bg-primary text-primary-foreground"
            : "border-border bg-input"
        )}
      >
        {isSelected && <Check className="h-2.5 w-2.5" strokeWidth={3} />}
      </div>
      <div className="min-w-0 flex-1">
        <div className="flex flex-wrap items-center gap-1.5">
          <p className="text-[13px] font-medium text-foreground">{item.tag}</p>
          {confidenceLabel && (
            <Badge variant="outline" className={cn("px-1.5 py-0 text-[10px]", confidenceColor)}>
              {confidenceLabel}
            </Badge>
          )}
          {item.searchType && (
            <Badge variant="secondary" className="px-1.5 py-0 text-[10px]">
              {item.searchType}
            </Badge>
          )}
          {item.searchIntent && (
            <Badge variant="outline" className="px-1.5 py-0 text-[10px]">
              {item.searchIntent}
            </Badge>
          )}
        </div>
        {item.reason && (
          <p className={cn("page-lead !mt-0.5", !isSelected && "line-clamp-1")}>{item.reason}</p>
        )}
      </div>
    </button>
  );
}

export function SuggestedTagsPicker({
  tags,
  selected,
  onToggle,
  onSelectAllAccounts,
  hideAccounts = false,
  researchMap,
}: SuggestedTagsPickerProps) {
  const accountConfidence = new Map(
    (researchMap?.similarAccounts ?? []).map((a) => [`@${a.username.toLowerCase()}`, a.confidence])
  );
  const accountTags = hideAccounts
    ? []
    : tags.filter((t) => t.searchType === "帳號" || t.tag.startsWith("@"));
  const keywordTags = tags.filter((t) => t.searchType !== "帳號" && !t.tag.startsWith("@"));

  return (
    <div className="space-y-4">
      {accountTags.length > 0 && (
        <div className="overflow-hidden rounded-lg border border-border">
          <div className="flex items-center justify-between gap-2 border-b border-border bg-muted/40 px-3 py-2">
            <div>
              <p className="text-[12px] font-semibold text-foreground">相似帳號</p>
              <p className="text-[11px] text-muted-foreground">
                勾選後才會進該帳號找貼文；未勾選則只搜關鍵字與網路補充
              </p>
            </div>
            {onSelectAllAccounts && (
              <Button type="button" size="sm" variant="outline" className="h-7 shrink-0 text-[11px]" onClick={onSelectAllAccounts}>
                全選帳號
              </Button>
            )}
          </div>
          <div className="divide-y divide-border">
            {accountTags.map((item) => (
              <TagRow
                key={item.tag}
                item={item}
                isSelected={selected.includes(item.tag)}
                onToggle={() => onToggle(item.tag)}
                confidence={accountConfidence.get(item.tag.toLowerCase())}
              />
            ))}
          </div>
        </div>
      )}

      {keywordTags.length > 0 && (
        <div className="overflow-hidden rounded-lg border border-border">
          {accountTags.length > 0 && (
            <div className="border-b border-border bg-muted/40 px-3 py-2">
              <p className="text-[12px] font-semibold text-foreground">關鍵字標籤</p>
              <p className="text-[11px] text-muted-foreground">全站搜尋受眾討論、痛點與求助</p>
            </div>
          )}
          <div className="divide-y divide-border">
            {keywordTags.map((item) => (
              <TagRow
                key={item.tag}
                item={item}
                isSelected={selected.includes(item.tag)}
                onToggle={() => onToggle(item.tag)}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}