"use client";

import { useState } from "react";
import { CheckCircle2, Eye, EyeOff, Save, Loader2 } from "lucide-react";

const SECTIONS = [
  { id: "caveats", label: "Caveats & Data Limitations", desc: "Internal data quality notes" },
  { id: "methodology", label: "Methodology", desc: "How the analysis was conducted" },
  { id: "predictions", label: "Outlook / Predictions", desc: "Projected metrics and forecasts" },
  { id: "timeline", label: "Event Timeline", desc: "Anomaly and event markers" },
] as const;

export function SaveClientPanel({ analysisJobId, onSaved }: { analysisJobId: string; onSaved?: () => void }) {
  const [hidden, setHidden] = useState<Set<string>>(new Set());
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  function toggle(id: string) {
    setHidden(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  }

  async function save() {
    setSaving(true);
    try {
      const res = await fetch("/api/analysis/client-version", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ analysisJobId, hiddenSections: [...hidden] }),
      });
      if (res.ok) {
        setSaved(true);
        onSaved?.();
        setTimeout(() => setSaved(false), 3000);
      }
    } catch { /* save failed */ }
    setSaving(false);
  }

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
        <Save className="w-3.5 h-3.5 text-brand-600" />
        <h3 className="text-sm font-bold text-slate-800">Save for Client</h3>
      </div>
      <div className="px-4 py-3 space-y-2">
        <p className="text-[11px] text-slate-500 mb-2">
          Choose which sections to include in the client-facing version. Hidden sections will not appear in shared links or client exports.
        </p>
        {SECTIONS.map(s => {
          const isHidden = hidden.has(s.id);
          return (
            <button key={s.id} onClick={() => toggle(s.id)} className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-lg border transition-colors text-left ${isHidden ? "border-red-200 bg-red-50/50" : "border-slate-200 hover:bg-slate-50"}`}>
              {isHidden ? <EyeOff className="w-3.5 h-3.5 text-red-400 shrink-0" /> : <Eye className="w-3.5 h-3.5 text-green-500 shrink-0" />}
              <div className="flex-1 min-w-0">
                <p className="text-xs font-semibold text-slate-700">{s.label}</p>
                <p className="text-[10px] text-slate-400">{s.desc}</p>
              </div>
              <span className={`text-[9px] font-semibold px-1.5 py-0.5 rounded ${isHidden ? "bg-red-100 text-red-600" : "bg-green-100 text-green-600"}`}>
                {isHidden ? "Hidden" : "Visible"}
              </span>
            </button>
          );
        })}

        <p className="text-[10px] text-slate-400 pt-1">
          Executive Summary, Key Metrics, Findings, Recommendations, and Sources are always included.
        </p>
      </div>
      <div className="px-4 py-3 border-t border-slate-100">
        <button onClick={save} disabled={saving || saved} className={`w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-semibold transition-colors ${saved ? "bg-green-600 text-white" : "bg-brand-600 text-white hover:bg-brand-700"} disabled:opacity-70`}>
          {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : saved ? <CheckCircle2 className="w-4 h-4" /> : <Save className="w-4 h-4" />}
          {saving ? "Saving..." : saved ? "Saved for Client" : `Save Client Version${hidden.size > 0 ? ` (${hidden.size} hidden)` : ""}`}
        </button>
      </div>
    </div>
  );
}
