"use client";

/**
 * AI Generate modal — collects purpose + audience + CTA + target keyword +
 * extra context, then calls /api/page-studio/generate (data-fed) and hands
 * the result back to the editor via onGenerated(result).
 *
 * The generate route scrapes brand images server-side before calling
 * the LLM, so this modal shows a multi-step progress indicator
 * ("Gathering brand data" → "Scraping images" → "Writing copy")
 * that animates until the single API response returns. The steps
 * are cosmetic — there's one real fetch — but the cue reassures the
 * user that a 20-60s generation is doing real work under the hood.
 */

import { useEffect, useState } from "react";
import { X, Sparkles, Loader2, AlertCircle, Database, ImageIcon, CheckCircle2 } from "lucide-react";
import type { Section, Branding } from "@/lib/page-studio/section-registry";

export interface GenerateResult {
  sections: Section[];
  branding: Branding;
  metaTitle: string;
  metaDescription: string;
  dataFed?: boolean;
  imageCount?: number;
}

interface Props {
  brandId: string;
  open: boolean;
  onClose: () => void;
  onGenerated: (result: GenerateResult) => void;
}

const PURPOSES = [
  { id: "lead_generation", label: "Lead Generation" },
  { id: "service", label: "Service Page" },
  { id: "product", label: "Product Launch" },
  { id: "event", label: "Event" },
  { id: "coming_soon", label: "Coming Soon" },
];

// Progress steps we walk through while the single /generate call
// is running. Timings are approximate — they cap at the "generating
// copy" step so if the API takes longer than usual the UI doesn't
// claim to be "done" before the response arrives.
const STEPS: Array<{ id: string; label: string; delayMs: number }> = [
  { id: "brand",    label: "Gathering brand data",            delayMs: 0 },
  { id: "images",   label: "Scraping images from your site",  delayMs: 1500 },
  { id: "copy",     label: "Writing page copy with AI",       delayMs: 5000 },
  { id: "assemble", label: "Assembling sections",             delayMs: 20000 },
];

export default function AiGenerateModal({ brandId, open, onClose, onGenerated }: Props) {
  const [purpose, setPurpose] = useState("lead_generation");
  const [targetKeyword, setTargetKeyword] = useState("");
  const [targetAudience, setTargetAudience] = useState("");
  const [primaryCta, setPrimaryCta] = useState("Get Started");
  const [additionalContext, setAdditionalContext] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [stepIndex, setStepIndex] = useState(0);

  // Walk the progress steps while loading. Cleared on close / unmount.
  useEffect(() => {
    if (!loading) return;
    setStepIndex(0);
    const timers: ReturnType<typeof setTimeout>[] = [];
    for (let i = 1; i < STEPS.length; i++) {
      timers.push(setTimeout(() => setStepIndex((n) => Math.max(n, i)), STEPS[i].delayMs));
    }
    return () => { for (const t of timers) clearTimeout(t); };
  }, [loading]);

  if (!open) return null;

  async function submit() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/page-studio/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, purpose, targetKeyword, targetAudience, primaryCta, additionalContext }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || `HTTP ${res.status}`);
      }
      const data = (await res.json()) as GenerateResult;
      onGenerated(data);
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Generation failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-slate-200 px-5 py-4">
          <div className="flex items-center gap-2">
            <Sparkles className="w-4 h-4 text-brand-600" />
            <h2 className="font-bold text-slate-900">Generate Page with AI</h2>
          </div>
          <button onClick={onClose} disabled={loading} className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500 disabled:opacity-50"><X className="w-4 h-4" /></button>
        </div>

        {loading ? (
          <div className="p-6">
            <div className="flex items-center gap-2 mb-4 text-sm font-semibold text-slate-900">
              <Loader2 className="w-4 h-4 animate-spin text-brand-600" />
              Building your landing page
            </div>
            <ol className="space-y-2.5">
              {STEPS.map((step, i) => {
                const done = i < stepIndex;
                const active = i === stepIndex;
                return (
                  <li key={step.id} className="flex items-center gap-3 text-xs">
                    <span className={`w-5 h-5 rounded-full flex items-center justify-center shrink-0 ${
                      done ? "bg-emerald-100 text-emerald-700"
                      : active ? "bg-brand-100 text-brand-700"
                      : "bg-slate-100 text-slate-400"
                    }`}>
                      {done ? <CheckCircle2 className="w-3 h-3" />
                        : active ? <Loader2 className="w-3 h-3 animate-spin" />
                        : <span className="w-1.5 h-1.5 rounded-full bg-current" />}
                    </span>
                    <span className={done ? "text-slate-500 line-through decoration-slate-300"
                      : active ? "text-slate-900 font-semibold"
                      : "text-slate-400"}>
                      {step.label}
                    </span>
                  </li>
                );
              })}
            </ol>
            <p className="mt-4 text-[11px] text-slate-500 leading-relaxed">
              The AI is analysing your brand, scraping images from your website, and writing
              complete copy for every section. This usually takes 20-45 seconds.
            </p>
          </div>
        ) : (
          <>
            {/* Data-fed indicator */}
            <div className="mx-5 mt-4 space-y-2">
              <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-teal-50 border border-teal-200">
                <Database className="w-3.5 h-3.5 text-teal-600 shrink-0" />
                <p className="text-[11px] text-teal-700">
                  <span className="font-semibold">Data-fed generation:</span> AI uses your brand&apos;s real keywords, conversions, reviews, and search data.
                </p>
              </div>
              <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-violet-50 border border-violet-200">
                <ImageIcon className="w-3.5 h-3.5 text-violet-600 shrink-0" />
                <p className="text-[11px] text-violet-700">
                  <span className="font-semibold">Real brand images:</span> We scrape your site and the AI places them in hero, team, and service sections.
                </p>
              </div>
            </div>

            <div className="p-5 space-y-4">
              <div>
                <label className="block text-[11px] font-semibold text-slate-600 mb-1">Purpose</label>
                <select value={purpose} onChange={(e) => setPurpose(e.target.value)} className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg bg-white">
                  {PURPOSES.map((p) => <option key={p.id} value={p.id}>{p.label}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-slate-600 mb-1">Target Keyword <span className="text-slate-400 font-normal">(optional — uses top keyword if empty)</span></label>
                <input type="text" value={targetKeyword} onChange={(e) => setTargetKeyword(e.target.value)} placeholder="e.g. emergency plumber houston" className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-slate-600 mb-1">Target Audience</label>
                <input type="text" value={targetAudience} onChange={(e) => setTargetAudience(e.target.value)} placeholder="e.g. homeowners needing HVAC repair" className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-slate-600 mb-1">Primary CTA</label>
                <input type="text" value={primaryCta} onChange={(e) => setPrimaryCta(e.target.value)} className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-slate-600 mb-1">Additional Context</label>
                <textarea rows={3} value={additionalContext} onChange={(e) => setAdditionalContext(e.target.value)} placeholder="e.g. Focus on emergency services, 24/7 availability" className="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500/40 focus:border-blue-500" />
              </div>

              {error && (
                <div className="flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700">
                  <AlertCircle className="w-3.5 h-3.5 mt-0.5 shrink-0" />
                  <span>{error}</span>
                </div>
              )}
            </div>
          </>
        )}

        <div className="flex items-center justify-end gap-2 border-t border-slate-200 px-5 py-3 bg-slate-50">
          <button onClick={onClose} disabled={loading} className="px-4 py-2 text-xs font-semibold text-slate-600 hover:text-slate-900 disabled:opacity-50">Cancel</button>
          <button
            onClick={submit}
            disabled={loading}
            className="flex items-center gap-1.5 px-4 py-2 bg-gradient-to-r from-brand-600 to-violet-600 text-white text-xs font-semibold rounded-lg hover:from-brand-700 hover:to-violet-700 disabled:opacity-60"
          >
            {loading ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Sparkles className="w-3.5 h-3.5" />}
            {loading ? "Generating…" : "Generate"}
          </button>
        </div>
      </div>
    </div>
  );
}
