"use client";

import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import type { FormCDraft } from "@/lib/sag/form-c";
import { snapshotForAgentCall } from "@/lib/agents/context-snapshot";

interface Props {
  draft: FormCDraft;
  pitchSlug: string;
}

type SectionOverrides = Record<string, string>;

export function FormCEditor({ draft, pitchSlug }: Props) {
  const [overrides, setOverrides] = useLocalStorage<Record<string, SectionOverrides>>(
    "sag.form-c.overrides",
    {}
  );
  const [editingId, setEditingId] = useState<string | null>(null);
  const [askingAgent, setAskingAgent] = useState<string | null>(null);

  const myOverrides = overrides[pitchSlug] ?? {};

  function setSectionContent(sectionId: string, content: string) {
    setOverrides({
      ...overrides,
      [pitchSlug]: { ...myOverrides, [sectionId]: content },
    });
  }

  function resetSection(sectionId: string) {
    const next = { ...myOverrides };
    delete next[sectionId];
    setOverrides({ ...overrides, [pitchSlug]: next });
  }

  async function expandViaAgent(sectionId: string, currentContent: string, label: string) {
    setAskingAgent(sectionId);
    try {
      const resp = await fetch("/api/agents/compliance", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          messages: [
            {
              role: "user",
              content: `I'm drafting SEC Reg CF Form C for a SAG portfolio company (${pitchSlug}). Expand the following section into the level of detail SEC counsel would expect. Keep the existing structure but flesh out placeholders. Section: ${label}.\n\nCurrent draft:\n\n${currentContent}\n\nReturn the expanded section in Markdown. Be specific about NC + federal regulatory references and flag anything that genuinely needs a securities attorney to nail down.`,
            },
          ],
          contextSnapshot: snapshotForAgentCall(),
        }),
      });
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.error || "Compliance Agent failed");
      setSectionContent(sectionId, data.message);
      setEditingId(sectionId);
    } catch (e) {
      alert("Agent failed: " + (e instanceof Error ? e.message : "unknown"));
    } finally {
      setAskingAgent(null);
    }
  }

  function exportMarkdown() {
    const lines: string[] = [];
    lines.push(`# SEC Form C — ${pitchSlug}`);
    lines.push(`As of: ${draft.asOfDate}`);
    lines.push("");
    lines.push(
      "_DRAFT — not for SEC filing without securities-counsel review. Generated by the SAG Corporate Business Manager._"
    );
    lines.push("");
    for (const s of draft.sections) {
      const content = myOverrides[s.id] ?? s.content;
      lines.push(`## ${s.label}`);
      lines.push("");
      lines.push(content);
      lines.push("");
    }
    const blob = new Blob([lines.join("\n")], { type: "text/markdown;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `form-c-draft-${pitchSlug}-${draft.asOfDate}.md`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-6">
      <Card className="border-yellow-500/30 bg-yellow-50/30 dark:bg-yellow-900/10">
        <CardContent className="p-5 flex items-center justify-between flex-wrap gap-3">
          <div>
            <Badge variant="warning">Draft only</Badge>
            <h2 className="mt-2 text-base font-semibold">SEC Reg CF Form C — pre-filing draft</h2>
            <p className="text-xs text-muted-foreground max-w-2xl mt-1">
              Generated from this pitch’s data. Sections marked <Badge variant="warning" className="text-[10px]">needs input</Badge> require human review. <strong>Do not file without securities counsel.</strong>
            </p>
          </div>
          <Button variant="brand" size="sm" onClick={exportMarkdown}>Export Markdown</Button>
        </CardContent>
      </Card>

      {draft.sections.map((section) => {
        const overridden = myOverrides[section.id] != null;
        const content = overridden ? myOverrides[section.id] : section.content;
        const isEditing = editingId === section.id;
        const isAskingAgent = askingAgent === section.id;

        return (
          <Card key={section.id} className={overridden ? "border-blue-500/30 bg-blue-50/30 dark:bg-blue-900/10" : ""}>
            <CardContent className="p-5">
              <div className="flex items-start justify-between gap-3 mb-3 flex-wrap">
                <div>
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    {section.requiresHumanInput && <Badge variant="warning" className="text-[10px]">Needs input</Badge>}
                    {overridden && <Badge variant="info" className="text-[10px]">Edited</Badge>}
                  </div>
                  <h3 className="text-base font-semibold">{section.label}</h3>
                </div>
                <div className="flex items-center gap-2">
                  <Button
                    variant="ghost"
                    size="sm"
                    disabled={isAskingAgent}
                    onClick={() => expandViaAgent(section.id, content, section.label)}
                  >
                    {isAskingAgent ? "Drafting..." : "✨ Expand via Compliance Agent"}
                  </Button>
                  <Button variant="ghost" size="sm" onClick={() => setEditingId(isEditing ? null : section.id)}>
                    {isEditing ? "Done" : "Edit"}
                  </Button>
                  {overridden && (
                    <Button variant="ghost" size="sm" onClick={() => resetSection(section.id)}>
                      Reset
                    </Button>
                  )}
                </div>
              </div>

              {isEditing ? (
                <textarea
                  className="w-full rounded-md border border-input bg-background p-3 text-sm font-mono"
                  value={content}
                  onChange={(e) => setSectionContent(section.id, e.target.value)}
                  rows={Math.max(8, content.split("\n").length + 1)}
                  onBlur={() => setEditingId(null)}
                  autoFocus
                />
              ) : (
                <div className="prose prose-sm dark:prose-invert max-w-none">
                  <pre className="whitespace-pre-wrap font-sans text-sm leading-relaxed bg-transparent p-0">
                    {content}
                  </pre>
                </div>
              )}
            </CardContent>
          </Card>
        );
      })}

      <Card className="border-dashed">
        <CardContent className="p-5">
          <h3 className="text-base font-semibold">Pre-filing checklist</h3>
          <ul className="mt-3 space-y-2 text-sm">
            <li>☐ Engage SEC / Reg CF-experienced securities counsel</li>
            <li>☐ Decide on FINRA-registered intermediary (Wefunder vs. Republic vs. StartEngine)</li>
            <li>☐ Decide on security type (membership interest vs. SAFE vs. Crowd SAFE)</li>
            <li>☐ Engage CPA for required financial statements (tier depends on raise size)</li>
            <li>☐ Run bad-actor disclosure checks on all principals</li>
            <li>☐ Draft + counsel-review risk factors (Section XI)</li>
            <li>☐ Disclose all related-party transactions (Section XII)</li>
            <li>☐ Prepare exhibits (Articles, Operating Agreement, financials)</li>
            <li>☐ File Form C with SEC EDGAR through the intermediary</li>
            <li>☐ Launch on intermediary platform — 21-day minimum offering period</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}
