"use client";

import { useState, useEffect, useRef } from "react";
import { ChevronDown, ChevronRight, Copy, Check, Loader2, PenLine } from "lucide-react";
import type { BriefSchema, CitedPoint } from "@/lib/types";
import { billsAPI } from "@/lib/api";
import { useIsFollowing } from "@/lib/hooks/useFollows";

interface DraftLetterPanelProps {
  billId: string;
  brief: BriefSchema;
  chamber?: string;
}

type Stance = "yes" | "no" | null;
type Tone = "short" | "polite" | "firm";

function pointText(p: string | CitedPoint): string {
  return typeof p === "string" ? p : p.text;
}

function pointKey(p: string | CitedPoint, i: number): string {
  return `${i}-${typeof p === "string" ? p.slice(0, 40) : p.text.slice(0, 40)}`;
}

function chamberToRecipient(chamber?: string): "house" | "senate" {
  return chamber?.toLowerCase() === "senate" ? "senate" : "house";
}

export function DraftLetterPanel({ billId, brief, chamber }: DraftLetterPanelProps) {
  const [open, setOpen] = useState(false);
  const existing = useIsFollowing("bill", billId);
  const [stance, setStance] = useState<Stance>(null);
  const prevModeRef = useRef<string | undefined>(undefined);

  // Keep stance in sync with follow mode changes (including unfollow → null)
  useEffect(() => {
    const newMode = existing?.follow_mode;
    if (newMode === prevModeRef.current) return;
    prevModeRef.current = newMode;
    if (newMode === "pocket_boost") setStance("yes");
    else if (newMode === "pocket_veto") setStance("no");
    else setStance(null);
  }, [existing?.follow_mode]);

  const recipient = chamberToRecipient(chamber);
  const [tone, setTone] = useState<Tone>("polite");
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [includeCitations, setIncludeCitations] = useState(true);
  const [zipCode, setZipCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [draft, setDraft] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  const keyPoints = brief.key_points ?? [];
  const risks = brief.risks ?? [];
  const allPoints = [
    ...keyPoints.map((p, i) => ({ group: "key" as const, index: i, text: pointText(p), raw: p })),
    ...risks.map((p, i) => ({ group: "risk" as const, index: keyPoints.length + i, text: pointText(p), raw: p })),
  ];

  function togglePoint(globalIndex: number) {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(globalIndex)) {
        next.delete(globalIndex);
      } else if (next.size < 3) {
        next.add(globalIndex);
      }
      return next;
    });
  }

  async function handleGenerate() {
    if (selected.size === 0 || stance === null) return;

    const selectedPoints = allPoints
      .filter((p) => selected.has(p.index))
      .map((p) => {
        if (includeCitations && typeof p.raw !== "string" && p.raw.citation) {
          return `${p.text} (${p.raw.citation})`;
        }
        return p.text;
      });

    setLoading(true);
    setError(null);
    setDraft(null);

    try {
      const result = await billsAPI.generateDraft(billId, {
        stance,
        recipient,
        tone,
        selected_points: selectedPoints,
        include_citations: includeCitations,
        zip_code: zipCode.trim() || undefined,
      });
      setDraft(result.draft);
    } catch (err: unknown) {
      const detail =
        err &&
        typeof err === "object" &&
        "response" in err &&
        err.response &&
        typeof err.response === "object" &&
        "data" in err.response &&
        err.response.data &&
        typeof err.response.data === "object" &&
        "detail" in err.response.data
          ? String((err.response.data as { detail: string }).detail)
          : "Failed to generate letter. Please try again.";
      setError(detail);
    } finally {
      setLoading(false);
    }
  }

  async function handleCopy() {
    if (!draft) return;
    await navigator.clipboard.writeText(draft);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <div className="bg-card border border-border rounded-lg overflow-hidden">
      <button
        onClick={() => setOpen((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"
      >
        {open ? (
          <ChevronDown className="w-3.5 h-3.5 shrink-0" />
        ) : (
          <ChevronRight className="w-3.5 h-3.5 shrink-0" />
        )}
        <PenLine className="w-3.5 h-3.5 shrink-0" />
        Draft a letter to your {recipient === "senate" ? "senator" : "representative"}
      </button>

      {open && (
        <div className="border-t border-border px-4 py-4 space-y-4">
          {/* Stance + Tone */}
          <div className="flex flex-wrap gap-4">
            <div className="space-y-1">
              <p className="text-xs font-medium text-muted-foreground">Stance</p>
              <div className="flex rounded-md overflow-hidden border border-border text-xs">
                {(["yes", "no"] as ("yes" | "no")[]).map((s) => (
                  <button
                    key={s}
                    onClick={() => setStance(s)}
                    className={`px-3 py-1.5 font-medium transition-colors ${
                      stance === s
                        ? s === "yes"
                          ? "bg-green-600 text-white"
                          : "bg-red-600 text-white"
                        : "bg-background text-muted-foreground hover:bg-accent/50"
                    }`}
                  >
                    {s === "yes" ? "Support (Vote YES)" : "Oppose (Vote NO)"}
                  </button>
                ))}
              </div>
              {stance === null && (
                <p className="text-[10px] text-amber-500 mt-1">Select a position to continue</p>
              )}
            </div>

            <div className="space-y-1">
              <p className="text-xs font-medium text-muted-foreground">Tone</p>
              <select
                value={tone}
                onChange={(e) => setTone(e.target.value as Tone)}
                className="text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground"
              >
                <option value="short">Short</option>
                <option value="polite">Polite</option>
                <option value="firm">Firm</option>
              </select>
            </div>
          </div>

          {/* Point selector */}
          <div className="space-y-1">
            <p className="text-xs font-medium text-muted-foreground">
              Select up to 3 points to include
              {selected.size > 0 && (
                <span className="ml-1 text-muted-foreground">({selected.size}/3)</span>
              )}
            </p>
            <div className="border border-border rounded-md divide-y divide-border">
              {keyPoints.length > 0 && (
                <>
                  <p className="px-3 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/40">
                    Key Points
                  </p>
                  {keyPoints.map((p, i) => {
                    const globalIndex = i;
                    const isChecked = selected.has(globalIndex);
                    const isDisabled = !isChecked && selected.size >= 3;
                    return (
                      <label
                        key={pointKey(p, i)}
                        className={`flex items-start gap-2.5 px-3 py-2 cursor-pointer transition-colors ${
                          isDisabled ? "opacity-40 cursor-not-allowed" : "hover:bg-accent/40"
                        }`}
                      >
                        <input
                          type="checkbox"
                          checked={isChecked}
                          disabled={isDisabled}
                          onChange={() => togglePoint(globalIndex)}
                          className="mt-0.5 shrink-0"
                        />
                        <span className="text-xs text-foreground leading-snug">{pointText(p)}</span>
                      </label>
                    );
                  })}
                </>
              )}

              {risks.length > 0 && (
                <>
                  <p className="px-3 py-1.5 text-xs font-semibold text-muted-foreground bg-muted/40">
                    Concerns
                  </p>
                  {risks.map((p, i) => {
                    const globalIndex = keyPoints.length + i;
                    const isChecked = selected.has(globalIndex);
                    const isDisabled = !isChecked && selected.size >= 3;
                    return (
                      <label
                        key={pointKey(p, keyPoints.length + i)}
                        className={`flex items-start gap-2.5 px-3 py-2 cursor-pointer transition-colors ${
                          isDisabled ? "opacity-40 cursor-not-allowed" : "hover:bg-accent/40"
                        }`}
                      >
                        <input
                          type="checkbox"
                          checked={isChecked}
                          disabled={isDisabled}
                          onChange={() => togglePoint(globalIndex)}
                          className="mt-0.5 shrink-0"
                        />
                        <span className="text-xs text-foreground leading-snug">{pointText(p)}</span>
                      </label>
                    );
                  })}
                </>
              )}
            </div>
          </div>

          {/* Options row */}
          <div className="flex flex-wrap items-center gap-4">
            <div className="space-y-0.5">
              <input
                type="text"
                value={zipCode}
                onChange={(e) => setZipCode(e.target.value)}
                placeholder="ZIP code"
                maxLength={10}
                className="text-xs bg-background border border-border rounded px-2 py-1.5 text-foreground w-28 placeholder:text-muted-foreground"
              />
              <p className="text-[10px] text-muted-foreground">optional · not stored</p>
            </div>

            <label className="flex items-center gap-1.5 cursor-pointer text-xs text-muted-foreground">
              <input
                type="checkbox"
                checked={includeCitations}
                onChange={(e) => setIncludeCitations(e.target.checked)}
                className="shrink-0"
              />
              Include citations
            </label>
          </div>

          {/* Generate button */}
          <button
            onClick={handleGenerate}
            disabled={loading || selected.size === 0 || stance === null}
            className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground text-xs font-medium rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {loading && <Loader2 className="w-3.5 h-3.5 animate-spin" />}
            {loading ? "Generating…" : "Generate letter"}
          </button>

          {error && (
            <p className="text-xs text-destructive">{error}</p>
          )}

          {/* Draft output */}
          {draft && (
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <p className="text-xs text-muted-foreground italic">Edit before sending</p>
                <button
                  onClick={handleCopy}
                  className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
                >
                  {copied ? (
                    <>
                      <Check className="w-3.5 h-3.5 text-green-500" />
                      <span className="text-green-500">Copied!</span>
                    </>
                  ) : (
                    <>
                      <Copy className="w-3.5 h-3.5" />
                      Copy
                    </>
                  )}
                </button>
              </div>
              <textarea
                readOnly
                value={draft}
                rows={10}
                className="w-full text-xs bg-muted/30 border border-border rounded-md px-3 py-2 text-foreground resize-y font-sans leading-relaxed"
              />
            </div>
          )}

          {/* Footer */}
          <p className="text-[10px] text-muted-foreground border-t border-border pt-3">
            Based only on the bill&apos;s cited text · We don&apos;t store your location
          </p>
        </div>
      )}
    </div>
  );
}
