"use client";

import { useState } from "react";
import { ChevronDown, ChevronRight, RefreshCw } from "lucide-react";
import { BriefSchema } from "@/lib/types";
import { AIBriefCard } from "@/components/bills/AIBriefCard";
import { formatDate } from "@/lib/utils";

interface BriefPanelProps {
  briefs?: BriefSchema[] | null;
}

const TYPE_LABEL: Record<string, string> = {
  amendment: "AMENDMENT",
  full: "FULL",
};

function typeBadge(briefType?: string) {
  const label = TYPE_LABEL[briefType ?? ""] ?? (briefType?.toUpperCase() ?? "BRIEF");
  const isAmendment = briefType === "amendment";
  return (
    <span
      className={`text-xs font-mono px-1.5 py-0.5 rounded ${
        isAmendment
          ? "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400"
          : "bg-muted text-muted-foreground"
      }`}
    >
      {label}
    </span>
  );
}

export function BriefPanel({ briefs }: BriefPanelProps) {
  const [historyOpen, setHistoryOpen] = useState(false);
  const [expandedId, setExpandedId] = useState<number | null>(null);

  if (!briefs || briefs.length === 0) {
    return <AIBriefCard brief={null} />;
  }

  const latest = briefs[0];
  const history = briefs.slice(1);
  const isAmendment = latest.brief_type === "amendment";

  return (
    <div className="space-y-3">
      {/* "What Changed" badge row */}
      {isAmendment && (
        <div className="flex items-center gap-2 px-1">
          <RefreshCw className="w-3.5 h-3.5 text-amber-500" />
          <span className="text-sm font-semibold text-amber-600 dark:text-amber-400">
            What Changed
          </span>
          <span className="text-xs text-muted-foreground">·</span>
          <span className="text-xs text-muted-foreground">{formatDate(latest.created_at)}</span>
        </div>
      )}

      {/* Latest brief */}
      <AIBriefCard brief={latest} />

      {/* Version history (only when there are older briefs) */}
      {history.length > 0 && (
        <div className="bg-card border border-border rounded-lg overflow-hidden">
          <button
            onClick={() => setHistoryOpen((o) => !o)}
            className="w-full flex items-center gap-2 px-4 py-3 text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors text-left"
          >
            {historyOpen ? (
              <ChevronDown className="w-3.5 h-3.5 shrink-0" />
            ) : (
              <ChevronRight className="w-3.5 h-3.5 shrink-0" />
            )}
            Version History ({history.length} {history.length === 1 ? "version" : "versions"})
          </button>

          {historyOpen && (
            <div className="border-t border-border divide-y divide-border">
              {history.map((brief) => (
                <div key={brief.id}>
                  <button
                    onClick={() =>
                      setExpandedId((id) => (id === brief.id ? null : brief.id))
                    }
                    className="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-accent/40 transition-colors"
                  >
                    <span className="text-xs text-muted-foreground w-20 shrink-0">
                      {formatDate(brief.created_at)}
                    </span>
                    {typeBadge(brief.brief_type)}
                    <span className="text-xs text-muted-foreground truncate flex-1">
                      {brief.summary?.slice(0, 120) ?? "No summary"}
                      {(brief.summary?.length ?? 0) > 120 ? "…" : ""}
                    </span>
                    {expandedId === brief.id ? (
                      <ChevronDown className="w-3 h-3 text-muted-foreground shrink-0" />
                    ) : (
                      <ChevronRight className="w-3 h-3 text-muted-foreground shrink-0" />
                    )}
                  </button>

                  {expandedId === brief.id && (
                    <div className="px-4 pb-4">
                      <AIBriefCard brief={brief} />
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
