'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import {
  Globe,
  Plus,
  Eye,
  Pencil,
  Trash2,
  ExternalLink,
  FileText,
  RefreshCw,
} from 'lucide-react';

interface LandingPageItem {
  id: string;
  business_name: string;
  business_slug: string;
  config_json: string;
  status: string;
  published_url: string | null;
  a2p_registration_id: string | null;
  created_at: string;
  updated_at: string;
}

const statusColors: Record<string, { bg: string; text: string; dot: string }> = {
  draft: { bg: 'bg-slate-500/10', text: 'text-slate-400', dot: 'bg-slate-400' },
  published: { bg: 'bg-green-500/10', text: 'text-green-400', dot: 'bg-green-400' },
  active: { bg: 'bg-cyan-500/10', text: 'text-cyan-400', dot: 'bg-cyan-400' },
};

export default function LandingPagesPage() {
  const [pages, setPages] = useState<LandingPageItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [deleting, setDeleting] = useState<string | null>(null);

  const fetchPages = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/landing-pages');
      const data = await res.json();
      setPages(data.pages || []);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchPages();
  }, [fetchPages]);

  async function handleDelete(id: string) {
    if (!confirm('Delete this landing page set? This cannot be undone.')) return;
    setDeleting(id);
    try {
      await fetch(`/api/landing-pages/${id}`, { method: 'DELETE' });
      setPages((prev) => prev.filter((p) => p.id !== id));
    } catch {
      // ignore
    } finally {
      setDeleting(null);
    }
  }

  async function handleDownload(id: string, slug: 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 = `${slug}-${file.name}`;
          a.click();
          URL.revokeObjectURL(url);
        }
      }
    } catch {
      // ignore
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <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>
            Landing Pages
          </h1>
          <p className="mt-1 text-sm text-slate-400">
            Generate TCPA-compliant opt-in pages for your A2P campaigns
          </p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={fetchPages}
            className="flex items-center gap-2 rounded-lg border border-slate-700 bg-slate-800/50 px-4 py-2.5 text-sm font-medium text-slate-300 hover:bg-slate-700/50 transition-colors"
          >
            <RefreshCw className="h-4 w-4" />
            Refresh
          </button>
          <Link
            href="/landing-pages/create"
            className="flex items-center gap-2 rounded-lg bg-cyan-500 px-4 py-2.5 text-sm font-semibold text-white hover:bg-cyan-400 transition-colors shadow-lg shadow-cyan-500/20"
          >
            <Plus className="h-4 w-4" />
            Generate New
          </Link>
        </div>
      </div>

      {/* Loading */}
      {loading && (
        <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>
      )}

      {/* Empty State */}
      {!loading && pages.length === 0 && (
        <div className="rounded-2xl border border-slate-800/60 bg-[#0d1321] p-12 text-center">
          <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-slate-800/50 mx-auto mb-4">
            <FileText className="h-8 w-8 text-slate-500" />
          </div>
          <h3 className="text-lg font-semibold text-white mb-2">No Landing Pages Yet</h3>
          <p className="text-sm text-slate-400 mb-6 max-w-md mx-auto">
            Generate TCPA-compliant opt-in pages with privacy policy and terms of service — ready for your A2P registration.
          </p>
          <Link
            href="/landing-pages/create"
            className="inline-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"
          >
            <Plus className="h-4 w-4" />
            Create Your First Landing Page
          </Link>
        </div>
      )}

      {/* Grid */}
      {!loading && pages.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
          {pages.map((page) => {
            const status = statusColors[page.status] || statusColors.draft;
            return (
              <div
                key={page.id}
                className="group rounded-2xl border border-slate-800/60 bg-[#0d1321] overflow-hidden hover:border-slate-700/60 transition-all"
              >
                {/* Preview iframe */}
                <div className="relative h-48 bg-slate-900 overflow-hidden">
                  <iframe
                    src={`/api/landing-pages/${page.id}/preview`}
                    className="w-[200%] h-[200%] origin-top-left scale-50 pointer-events-none"
                    title={`Preview: ${page.business_name}`}
                    sandbox=""
                  />
                  <div className="absolute inset-0 bg-gradient-to-b from-transparent to-[#0d1321]/80" />
                </div>

                {/* Content */}
                <div className="p-5">
                  <div className="flex items-start justify-between mb-3">
                    <div>
                      <h3 className="text-base font-semibold text-white group-hover:text-cyan-400 transition-colors">
                        {page.business_name}
                      </h3>
                      <p className="text-xs text-slate-500 font-mono mt-0.5">
                        /{page.business_slug}
                      </p>
                    </div>
                    <span
                      className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium ${status.bg} ${status.text}`}
                    >
                      <span className={`h-1.5 w-1.5 rounded-full ${status.dot}`} />
                      {page.status.charAt(0).toUpperCase() + page.status.slice(1)}
                    </span>
                  </div>

                  {page.published_url && (
                    <a
                      href={page.published_url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1 text-xs text-cyan-400 hover:text-cyan-300 mb-3"
                    >
                      <ExternalLink className="h-3 w-3" />
                      {page.published_url}
                    </a>
                  )}

                  <p className="text-xs text-slate-500 mb-4">
                    Created {new Date(page.created_at).toLocaleDateString()}
                  </p>

                  {/* Actions */}
                  <div className="flex items-center gap-2">
                    <a
                      href={`/api/landing-pages/${page.id}/preview`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center gap-1.5 rounded-lg border border-slate-700 bg-slate-800/50 px-3 py-1.5 text-xs font-medium text-slate-300 hover:bg-slate-700/50 transition-colors"
                    >
                      <Eye className="h-3 w-3" />
                      Preview
                    </a>
                    <Link
                      href={`/landing-pages/create?edit=${page.id}`}
                      className="flex items-center gap-1.5 rounded-lg border border-slate-700 bg-slate-800/50 px-3 py-1.5 text-xs font-medium text-slate-300 hover:bg-slate-700/50 transition-colors"
                    >
                      <Pencil className="h-3 w-3" />
                      Edit
                    </Link>
                    <button
                      onClick={() => handleDownload(page.id, page.business_slug)}
                      className="flex items-center gap-1.5 rounded-lg border border-slate-700 bg-slate-800/50 px-3 py-1.5 text-xs font-medium text-slate-300 hover:bg-slate-700/50 transition-colors"
                    >
                      <FileText className="h-3 w-3" />
                      Download
                    </button>
                    <button
                      onClick={() => handleDelete(page.id)}
                      disabled={deleting === page.id}
                      className="ml-auto flex items-center gap-1.5 rounded-lg border border-red-900/30 bg-red-500/5 px-3 py-1.5 text-xs font-medium text-red-400 hover:bg-red-500/10 transition-colors disabled:opacity-50"
                    >
                      <Trash2 className="h-3 w-3" />
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
