"use client";

/**
 * Onboarding Wizard (/onboarding)
 * ---------------------------------
 * 5-step guided setup for new users:
 *   1. Create Organization
 *   2. Create Brand + Website
 *   3. Install Site Tag
 *   4. Connect Integrations
 *   5. Complete → go to AI Website Intake
 *
 * Steps 1-2 call POST /api/onboarding in one shot.
 * Step 3 shows the Site Tag snippet.
 * Step 4 shows integration options (can be skipped).
 * Step 5 directs to /website-upload for AI intake.
 */

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  Building2, Globe, Code2, Plug, Sparkles, ArrowRight, ArrowLeft,
  CheckCircle2, Loader2, Copy, Zap,
} from "lucide-react";
import IndustrySearch from "@/components/industry-search";

type Step = 1 | 2 | 3 | 4 | 5;

const STEPS = [
  { num: 1, label: "Organization", icon: Building2 },
  { num: 2, label: "Brand & Website", icon: Globe },
  { num: 3, label: "Install Tag", icon: Code2 },
  { num: 4, label: "Integrations", icon: Plug },
  { num: 5, label: "Complete", icon: Sparkles },
];

export default function OnboardingPage() {
  const router = useRouter();
  const [step, setStep] = useState<Step>(1);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);

  // Form state
  const [orgName, setOrgName] = useState("");
  const [brandName, setBrandName] = useState("");
  const [domain, setDomain] = useState("");
  const [industry, setIndustry] = useState("");

  // Results from API
  const [siteTag, setSiteTag] = useState<{ siteId: string; snippet: string } | null>(null);
  const [brandId, setBrandId] = useState<string | null>(null);

  // ── Step 1+2: Create org + brand + website + site tag ──
  async function handleCreate() {
    if (!brandName.trim() || !domain.trim()) {
      setError("Brand name and domain are required.");
      return;
    }
    setError(null);
    setSaving(true);

    try {
      const res = await fetch("/api/onboarding", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          orgName: orgName.trim() || undefined,
          brandName: brandName.trim(),
          domain: domain.trim(),
          industry: industry.trim() || undefined,
        }),
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Something went wrong");
        setSaving(false);
        return;
      }

      setBrandId(data.brand?.id ?? null);

      // Site tag is auto-created by the API
      if (data.siteTag) {
        setSiteTag(data.siteTag);
      }

      setStep(3);
    } catch {
      setError("Network error — please try again");
    }
    setSaving(false);
  }

  function copySnippet() {
    if (!siteTag?.snippet) return;
    navigator.clipboard.writeText(siteTag.snippet);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-6">
      <div className="w-full max-w-xl">

        {/* Logo */}
        <div className="text-center mb-8">
          <img src="/meseo-logo-dark.png" alt="meSEO" className="w-36 mx-auto mb-3 object-contain" />
          <h1 className="text-xl font-bold text-slate-900">Set up meSEO</h1>
          <p className="text-sm text-slate-500 mt-1">Takes about 2 minutes</p>
        </div>

        {/* Progress bar */}
        <div className="flex items-center gap-1 mb-8">
          {STEPS.map((s) => (
            <div key={s.num} className="flex-1 flex flex-col items-center gap-1.5">
              <div className={`w-full h-1.5 rounded-full transition-colors ${
                s.num < step ? "bg-green-500" : s.num === step ? "bg-brand-500" : "bg-slate-200"
              }`} />
              <span className={`text-[10px] font-semibold ${
                s.num <= step ? "text-slate-700" : "text-slate-400"
              }`}>{s.label}</span>
            </div>
          ))}
        </div>

        {/* Card */}
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">

          {/* ── Step 1: Organization ── */}
          {step === 1 && (
            <div className="p-6 space-y-5">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center">
                  <Building2 className="w-5 h-5 text-brand-600" />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-slate-900">Your Organization</h2>
                  <p className="text-xs text-slate-500">This is your workspace — it holds all your brands.</p>
                </div>
              </div>

              <div>
                <label className="text-xs font-semibold text-slate-600 block mb-1.5">Organization Name</label>
                <input
                  type="text"
                  value={orgName}
                  onChange={(e) => setOrgName(e.target.value)}
                  placeholder="e.g. My Agency, Acme Inc"
                  className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-500/30 focus:border-brand-300"
                />
                <p className="text-[10px] text-slate-400 mt-1">Optional — we&apos;ll generate one if you skip this.</p>
              </div>

              <button
                onClick={() => setStep(2)}
                className="w-full py-3 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 transition-colors flex items-center justify-center gap-2"
              >
                Next <ArrowRight className="w-4 h-4" />
              </button>
            </div>
          )}

          {/* ── Step 2: Brand + Website ── */}
          {step === 2 && (
            <div className="p-6 space-y-5">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center">
                  <Globe className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-slate-900">Your Brand & Website</h2>
                  <p className="text-xs text-slate-500">The website you want to track and optimize.</p>
                </div>
              </div>

              {error && (
                <div className="bg-red-50 border border-red-200 rounded-xl px-4 py-3 text-sm text-red-700">
                  {error}
                </div>
              )}

              <div>
                <label className="text-xs font-semibold text-slate-600 block mb-1.5">Brand Name *</label>
                <input
                  type="text"
                  value={brandName}
                  onChange={(e) => setBrandName(e.target.value)}
                  placeholder="e.g. Acme Corp"
                  className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-500/30 focus:border-brand-300"
                />
              </div>

              <div>
                <label className="text-xs font-semibold text-slate-600 block mb-1.5">Website Domain *</label>
                <input
                  type="text"
                  value={domain}
                  onChange={(e) => setDomain(e.target.value)}
                  placeholder="e.g. acme.com"
                  className="w-full px-4 py-2.5 rounded-xl border border-slate-200 text-sm text-slate-800 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-500/30 focus:border-brand-300"
                />
              </div>

              <div>
                <label className="text-xs font-semibold text-slate-600 block mb-1.5">Industry</label>
                <IndustrySearch
                  value={industry}
                  onChange={(ind) => setIndustry(ind)}
                />
                <p className="text-[10px] text-slate-400 mt-1">Optional — helps the AI give better recommendations.</p>
              </div>

              <div className="flex gap-2">
                <button
                  onClick={() => setStep(1)}
                  className="px-4 py-3 border border-slate-200 text-slate-600 text-sm font-semibold rounded-xl hover:bg-slate-50 transition-colors flex items-center gap-1"
                >
                  <ArrowLeft className="w-4 h-4" /> Back
                </button>
                <button
                  onClick={handleCreate}
                  disabled={saving}
                  className="flex-1 py-3 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 disabled:opacity-50 transition-colors flex items-center justify-center gap-2"
                >
                  {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <ArrowRight className="w-4 h-4" />}
                  {saving ? "Creating..." : "Create & Continue"}
                </button>
              </div>
            </div>
          )}

          {/* ── Step 3: Install Site Tag ── */}
          {step === 3 && (
            <div className="p-6 space-y-5">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-green-50 flex items-center justify-center">
                  <Code2 className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-slate-900">Install meSEO Site Tag</h2>
                  <p className="text-xs text-slate-500">Start collecting Machine Enhancing data from your website.</p>
                </div>
              </div>

              {siteTag ? (
                <>
                  <div>
                    <p className="text-xs text-slate-600 mb-2">
                      Paste this snippet into the <code className="text-brand-600 bg-brand-50 px-1 rounded">&lt;head&gt;</code> of your website:
                    </p>
                    <pre className="bg-slate-900 text-slate-200 text-xs leading-relaxed rounded-xl p-4 overflow-x-auto">
                      {siteTag.snippet}
                    </pre>
                  </div>
                  <button
                    onClick={copySnippet}
                    className={`w-full py-2.5 rounded-xl text-sm font-semibold transition-colors flex items-center justify-center gap-2 ${
                      copied ? "bg-green-600 text-white" : "bg-slate-100 text-slate-700 hover:bg-slate-200"
                    }`}
                  >
                    {copied ? <CheckCircle2 className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                    {copied ? "Copied!" : "Copy Snippet"}
                  </button>
                  <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-2">
                    <Zap className="w-3.5 h-3.5 text-blue-500 shrink-0 mt-0.5" />
                    <p className="text-xs text-blue-700">
                      <span className="font-semibold">Auto-tracks:</span> page views, sessions, phone clicks, form submissions, outbound clicks. No personal data captured.
                    </p>
                  </div>
                </>
              ) : (
                <div className="bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 text-xs text-amber-700">
                  Site Tag will be set up after you complete onboarding. You can install it later from the Site Tag page.
                </div>
              )}

              <div className="flex gap-2">
                <button
                  onClick={() => setStep(4)}
                  className="flex-1 py-3 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 transition-colors flex items-center justify-center gap-2"
                >
                  Next <ArrowRight className="w-4 h-4" />
                </button>
                <button
                  onClick={() => setStep(4)}
                  className="px-4 py-3 text-slate-500 text-sm font-semibold hover:text-slate-700 transition-colors"
                >
                  Skip for now
                </button>
              </div>
            </div>
          )}

          {/* ── Step 4: Integrations ── */}
          {step === 4 && (
            <div className="p-6 space-y-5">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-violet-50 flex items-center justify-center">
                  <Plug className="w-5 h-5 text-violet-600" />
                </div>
                <div>
                  <h2 className="text-lg font-bold text-slate-900">Connect Integrations</h2>
                  <p className="text-xs text-slate-500">Optional — you can connect these anytime from Settings.</p>
                </div>
              </div>

              <div className="space-y-2">
                {[
                  { name: "Google Search Console", desc: "Search keywords, clicks, and impressions", id: "gsc" },
                  { name: "Google Analytics (GA4)", desc: "Traffic, sessions, and user behavior", id: "ga4" },
                  { name: "Google Business Profile", desc: "Local visibility, reviews, map pack", id: "gbp" },
                  { name: "Bing Webmaster Tools", desc: "Bing search data and indexing", id: "bing" },
                ].map((integration) => (
                  <div key={integration.id} className="flex items-center gap-3 px-4 py-3 bg-slate-50 rounded-xl border border-slate-100">
                    <div className="flex-1">
                      <p className="text-sm font-semibold text-slate-800">{integration.name}</p>
                      <p className="text-xs text-slate-500">{integration.desc}</p>
                    </div>
                    <button
                      onClick={() => { /* Phase 2: trigger OAuth flow */ }}
                      className="px-3 py-1.5 text-xs font-semibold text-brand-700 bg-brand-50 border border-brand-200 rounded-lg hover:bg-brand-100 transition-colors"
                    >
                      Connect
                    </button>
                  </div>
                ))}
              </div>

              <div className="flex gap-2">
                <button
                  onClick={() => setStep(3)}
                  className="px-4 py-3 border border-slate-200 text-slate-600 text-sm font-semibold rounded-xl hover:bg-slate-50 transition-colors flex items-center gap-1"
                >
                  <ArrowLeft className="w-4 h-4" /> Back
                </button>
                <button
                  onClick={() => setStep(5)}
                  className="flex-1 py-3 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 transition-colors flex items-center justify-center gap-2"
                >
                  Next <ArrowRight className="w-4 h-4" />
                </button>
                <button
                  onClick={() => setStep(5)}
                  className="px-4 py-3 text-slate-500 text-sm font-semibold hover:text-slate-700 transition-colors"
                >
                  Skip
                </button>
              </div>
            </div>
          )}

          {/* ── Step 5: Complete ── */}
          {step === 5 && (
            <div className="p-6 space-y-5 text-center">
              <div className="w-14 h-14 rounded-2xl bg-green-50 flex items-center justify-center mx-auto">
                <CheckCircle2 className="w-7 h-7 text-green-600" />
              </div>

              <div>
                <h2 className="text-lg font-bold text-slate-900">You&apos;re all set!</h2>
                <p className="text-sm text-slate-500 mt-1">
                  Your workspace is ready. Your Site Tag is collecting data.
                </p>
              </div>

              <div className="bg-brand-50 border border-brand-100 rounded-xl px-4 py-3">
                <p className="text-xs text-brand-700">
                  <span className="font-semibold">One more thing:</span> Tell us about your business so our AI can give you personalized recommendations, content briefs, and competitor insights.
                </p>
              </div>

              <div className="space-y-2">
                <button
                  onClick={() => router.push("/website-upload")}
                  className="w-full py-3 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 transition-colors flex items-center justify-center gap-2"
                >
                  <Sparkles className="w-4 h-4" />
                  Complete AI Website Intake
                </button>
                <button
                  onClick={() => router.push("/dashboard")}
                  className="w-full py-2.5 text-slate-500 text-sm font-semibold hover:text-slate-700 transition-colors"
                >
                  Skip to Dashboard →
                </button>
              </div>

              <p className="text-[10px] text-slate-400">
                You can always complete the AI intake later from the sidebar.
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
