'use client';

import { useState, useEffect, useRef, useCallback, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import {
  Globe,
  ArrowLeft,
  Sparkles,
  Download,
  Send,
  Eye,
  FileText,
  Shield,
  Loader2,
} from 'lucide-react';

interface FormData {
  businessName: string;
  businessSlug: string;
  useCase: string;
  messageFrequency: string;
  contactEmail: string;
  contactPhone: string;
  brandColor: string;
  logoUrl: string;
}

const defaultForm: FormData = {
  businessName: '',
  businessSlug: '',
  useCase: '',
  messageFrequency: 'up to 5 messages per week',
  contactEmail: '',
  contactPhone: '',
  brandColor: '#3B82F6',
  logoUrl: '',
};

function CreateLandingPageInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const editId = searchParams.get('edit');

  const [form, setForm] = useState<FormData>(defaultForm);
  const [previewHtml, setPreviewHtml] = useState('');
  const [activeTab, setActiveTab] = useState<'optin' | 'privacy' | 'terms'>('optin');
  const [saving, setSaving] = useState(false);
  const [generating, setGenerating] = useState(false);
  const [generatedId, setGeneratedId] = useState<string | null>(editId);
  const [slugManual, setSlugManual] = useState(false);

  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const iframeRef = useRef<HTMLIFrameElement>(null);

  // Auto-generate slug from business name
  useEffect(() => {
    if (!slugManual && form.businessName) {
      const slug = form.businessName
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/^-+|-+$/g, '')
        .substring(0, 50);
      setForm((prev) => ({ ...prev, businessSlug: slug }));
    }
  }, [form.businessName, slugManual]);

  // Load existing page if editing
  useEffect(() => {
    if (!editId) return;
    (async () => {
      try {
        const res = await fetch(`/api/landing-pages/${editId}`);
        const data = await res.json();
        if (data.page) {
          const config = JSON.parse(data.page.config_json);
          setForm({
            businessName: config.businessName || '',
            businessSlug: config.businessSlug || '',
            useCase: config.useCase || '',
            messageFrequency: config.messageFrequency || 'up to 5 messages per week',
            contactEmail: config.contactEmail || '',
            contactPhone: config.contactPhone || '',
            brandColor: config.brandColor || '#3B82F6',
            logoUrl: config.logoUrl || '',
          });
          setSlugManual(true);
          setGeneratedId(editId);
        }
      } catch {
        // ignore
      }
    })();
  }, [editId]);

  // Debounced live preview
  const updatePreview = useCallback(async (data: FormData) => {
    if (!data.businessName) {
      setPreviewHtml('');
      return;
    }
    try {
      const res = await fetch('/api/landing-pages/generate-preview', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      const html = await res.text();
      setPreviewHtml(html);
    } catch {
      // ignore
    }
  }, []);

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => updatePreview(form), 300);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [form, updatePreview]);

  function handleChange(field: keyof FormData, value: string) {
    if (field === 'businessSlug') setSlugManual(true);
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  async function handleGenerate() {
    setGenerating(true);
    try {
      if (generatedId && editId) {
        // Update existing
        await fetch(`/api/landing-pages/${generatedId}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form),
        });
      } else {
        // Create new
        const res = await fetch('/api/landing-pages', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form),
        });
        const data = await res.json();
        if (data.id) setGeneratedId(data.id);
      }
    } catch {
      // ignore
    } finally {
      setGenerating(false);
    }
  }

  async function handlePublish() {
    if (!generatedId) {
      await handleGenerate();
      return;
    }
    setSaving(true);
    try {
      await fetch(`/api/landing-pages/${generatedId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, status: 'published' }),
      });
      router.push('/landing-pages');
    } catch {
      // ignore
    } finally {
      setSaving(false);
    }
  }

  async function handleDownload() {
    const id = generatedId;
    if (!id) {
      // Generate first, then download
      setGenerating(true);
      try {
        const res = await fetch('/api/landing-pages', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form),
        });
        const data = await res.json();
        if (data.id) {
          setGeneratedId(data.id);
          await doDownload(data.id);
        }
      } catch {
        // ignore
      } finally {
        setGenerating(false);
      }
      return;
    }
    await doDownload(id);
  }

  async function doDownload(id: string) {
    try {
      const res = await fetch(`/api/landing-pages/${id}/download`);
      const data = await res.json();
      if (data.files) {
        for (const file of data.files as { name: string; content: string }[]) {
          const blob = new Blob([file.content], { type: 'text/html' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `${data.slug || 'landing'}-${file.name}`;
          a.click();
          URL.revokeObjectURL(url);
        }
      }
    } catch {
      // ignore
    }
  }

  const isValid = form.businessName && form.useCase && form.messageFrequency && form.contactEmail && form.contactPhone;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            href="/landing-pages"
            className="flex h-9 w-9 items-center justify-center rounded-lg border border-slate-700 bg-slate-800/50 text-slate-400 hover:text-white hover:bg-slate-700/50 transition-colors"
          >
            <ArrowLeft className="h-4 w-4" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-white flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-cyan-500/10 border border-cyan-500/20">
                <Globe className="h-5 w-5 text-cyan-400" />
              </div>
              {editId ? 'Edit Landing Page' : 'Generate Landing Page'}
            </h1>
            <p className="mt-1 text-sm text-slate-400">
              Create TCPA-compliant opt-in pages with privacy policy and terms
            </p>
          </div>
        </div>
      </div>

      {/* Split Layout */}
      <div className="flex gap-6" style={{ minHeight: 'calc(100vh - 200px)' }}>
        {/* Left: Form (60%) */}
        <div className="w-[60%] space-y-5">
          <div className="rounded-2xl border border-slate-800/60 bg-[#0d1321] p-6">
            <h2 className="text-lg font-semibold text-white mb-5 flex items-center gap-2">
              <FileText className="h-5 w-5 text-cyan-400" />
              Business Information
            </h2>

            <div className="space-y-4">
              {/* Business Name */}
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1.5">
                  Business Name <span className="text-red-400">*</span>
                </label>
                <input
                  type="text"
                  value={form.businessName}
                  onChange={(e) => handleChange('businessName', e.target.value)}
                  placeholder="Acme Fitness Studio"
                  className="w-full rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
                />
              </div>

              {/* Business Slug */}
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1.5">
                  Business Slug
                </label>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-slate-500">/</span>
                  <input
                    type="text"
                    value={form.businessSlug}
                    onChange={(e) => handleChange('businessSlug', e.target.value)}
                    placeholder="acme-fitness-studio"
                    className="flex-1 rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500 font-mono"
                  />
                </div>
              </div>

              {/* Use Case */}
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1.5">
                  Use Case Description <span className="text-red-400">*</span>
                </label>
                <textarea
                  value={form.useCase}
                  onChange={(e) => handleChange('useCase', e.target.value)}
                  placeholder="Class schedule updates, booking confirmations, and membership reminders for our fitness studio members."
                  rows={3}
                  className="w-full rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500 resize-none"
                />
              </div>

              {/* Message Frequency */}
              <div>
                <label className="block text-sm font-medium text-slate-300 mb-1.5">
                  Message Frequency <span className="text-red-400">*</span>
                </label>
                <input
                  type="text"
                  value={form.messageFrequency}
                  onChange={(e) => handleChange('messageFrequency', e.target.value)}
                  placeholder="up to 5 messages per week"
                  className="w-full rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
                />
              </div>

              {/* Contact Row */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-300 mb-1.5">
                    Contact Email <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="email"
                    value={form.contactEmail}
                    onChange={(e) => handleChange('contactEmail', e.target.value)}
                    placeholder="support@acme.com"
                    className="w-full rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-300 mb-1.5">
                    Contact Phone <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="tel"
                    value={form.contactPhone}
                    onChange={(e) => handleChange('contactPhone', e.target.value)}
                    placeholder="+15551234567"
                    className="w-full rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
                  />
                </div>
              </div>

              {/* Brand Color + Logo */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-300 mb-1.5">
                    Brand Color
                  </label>
                  <div className="flex items-center gap-3">
                    <input
                      type="color"
                      value={form.brandColor}
                      onChange={(e) => handleChange('brandColor', e.target.value)}
                      className="h-10 w-14 cursor-pointer rounded-lg border border-slate-700 bg-slate-800/50 p-1"
                    />
                    <input
                      type="text"
                      value={form.brandColor}
                      onChange={(e) => handleChange('brandColor', e.target.value)}
                      className="flex-1 rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white font-mono focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-300 mb-1.5">
                    Logo URL <span className="text-slate-600">(optional)</span>
                  </label>
                  <input
                    type="url"
                    value={form.logoUrl}
                    onChange={(e) => handleChange('logoUrl', e.target.value)}
                    placeholder="https://example.com/logo.png"
                    className="w-full rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:border-cyan-500 focus:outline-none focus:ring-1 focus:ring-cyan-500"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Generated Pages Info */}
          <div className="rounded-2xl border border-slate-800/60 bg-[#0d1321] p-6">
            <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
              <Shield className="h-5 w-5 text-cyan-400" />
              Generated Pages
            </h2>
            <div className="grid grid-cols-3 gap-3">
              {[
                { label: 'Opt-In Page', desc: 'Phone input + consent checkbox', icon: Globe },
                { label: 'Privacy Policy', desc: 'TCPA-compliant privacy policy', icon: FileText },
                { label: 'Terms of Service', desc: 'SMS program terms', icon: Shield },
              ].map((item) => (
                <div
                  key={item.label}
                  className="rounded-xl border border-slate-800/60 bg-slate-800/20 p-4"
                >
                  <item.icon className="h-5 w-5 text-cyan-400 mb-2" />
                  <p className="text-sm font-medium text-white">{item.label}</p>
                  <p className="text-xs text-slate-500 mt-1">{item.desc}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-3">
            <button
              onClick={handleGenerate}
              disabled={!isValid || generating}
              className="flex items-center gap-2 rounded-lg bg-cyan-500 px-5 py-2.5 text-sm font-semibold text-white hover:bg-cyan-400 transition-colors shadow-lg shadow-cyan-500/20 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {generating ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Sparkles className="h-4 w-4" />
              )}
              {generatedId ? 'Regenerate Pages' : 'Generate Pages'}
            </button>
            <button
              onClick={handleDownload}
              disabled={!isValid}
              className="flex items-center gap-2 rounded-lg border border-slate-700 bg-slate-800/50 px-5 py-2.5 text-sm font-medium text-slate-300 hover:bg-slate-700/50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Download className="h-4 w-4" />
              Download Files
            </button>
            <button
              onClick={handlePublish}
              disabled={!isValid || saving}
              className="flex items-center gap-2 rounded-lg bg-green-600 px-5 py-2.5 text-sm font-semibold text-white hover:bg-green-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
              Publish
            </button>
          </div>
        </div>

        {/* Right: Live Preview (40%) */}
        <div className="w-[40%]">
          <div className="sticky top-6 rounded-2xl border border-slate-800/60 bg-[#0d1321] overflow-hidden">
            {/* Browser Chrome */}
            <div className="flex items-center gap-2 px-4 py-3 bg-slate-800/50 border-b border-slate-800/60">
              <div className="flex items-center gap-1.5">
                <div className="h-3 w-3 rounded-full bg-red-500/60" />
                <div className="h-3 w-3 rounded-full bg-yellow-500/60" />
                <div className="h-3 w-3 rounded-full bg-green-500/60" />
              </div>
              <div className="flex-1 ml-3 rounded-md bg-slate-900/60 border border-slate-700/50 px-3 py-1">
                <span className="text-xs text-slate-500 font-mono">
                  {form.businessSlug ? `https://${form.businessSlug}.yourdomain.com` : 'https://your-page.com'}
                </span>
              </div>
            </div>

            {/* Tab Bar */}
            <div className="flex border-b border-slate-800/60">
              {(['optin', 'privacy', 'terms'] as const).map((tab) => {
                const labels = { optin: 'Opt-In', privacy: 'Privacy', terms: 'Terms' };
                return (
                  <button
                    key={tab}
                    onClick={() => setActiveTab(tab)}
                    className={`flex-1 px-4 py-2 text-xs font-medium transition-colors ${
                      activeTab === tab
                        ? 'text-cyan-400 border-b-2 border-cyan-400 bg-cyan-500/5'
                        : 'text-slate-500 hover:text-slate-300'
                    }`}
                  >
                    {labels[tab]}
                  </button>
                );
              })}
            </div>

            {/* Preview */}
            <div className="relative" style={{ height: '600px' }}>
              {previewHtml ? (
                <iframe
                  ref={iframeRef}
                  srcDoc={activeTab === 'optin' ? previewHtml : `
                    <div style="display:flex;align-items:center;justify-content:center;height:100vh;font-family:Inter,sans-serif;background:#f9fafb;">
                      <div style="text-align:center;color:#6b7280;">
                        <p style="font-size:14px;font-weight:600;margin-bottom:4px;">${activeTab === 'privacy' ? 'Privacy Policy' : 'Terms of Service'}</p>
                        <p style="font-size:12px;">Generate pages to preview this document</p>
                      </div>
                    </div>
                  `}
                  className="w-full h-full border-0"
                  title="Landing page preview"
                  sandbox="allow-same-origin"
                />
              ) : (
                <div className="flex flex-col items-center justify-center h-full text-center p-8">
                  <Eye className="h-10 w-10 text-slate-700 mb-4" />
                  <p className="text-sm font-medium text-slate-500">Live Preview</p>
                  <p className="text-xs text-slate-600 mt-1">
                    Start filling in the form to see a real-time preview
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function CreateLandingPage() {
  return (
    <Suspense fallback={
      <div className="flex items-center justify-center py-20">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-cyan-500 border-t-transparent" />
      </div>
    }>
      <CreateLandingPageInner />
    </Suspense>
  );
}
