import React, { useState, useEffect } from "react";
import { 
  Globe, 
  Key, 
  ShieldCheck, 
  Layers, 
  ShoppingBag, 
  RefreshCw, 
  ExternalLink, 
  CheckCircle2, 
  Building2, 
  Users, 
  Mail, 
  Phone, 
  MapPin, 
  DollarSign, 
  Edit3, 
  Plus, 
  Save, 
  Share2, 
  Radio, 
  Sparkles, 
  FileText, 
  Zap, 
  Check, 
  X, 
  Search, 
  Filter, 
  Copy, 
  Lock, 
  Server, 
  BarChart3, 
  Send,
  AlertCircle
} from "lucide-react";
import { Employee } from "../types";

interface PortalMarketingHubProps {
  currentUser?: Employee;
}

export interface RentedModuleCatalogItem {
  id: string;
  code: string;
  name: string;
  category: string;
  description: string;
  monthlyPrice: number;
  priceUnit: string;
  popularBadge: string;
  features: string[];
  demoUrl: string;
  status: "ACTIVE_RENTAL" | "DRAFT" | "COMING_SOON";
}

export const PortalMarketingHub: React.FC<PortalMarketingHubProps> = ({ currentUser }) => {
  const [activeSubTab, setActiveSubTab] = useState<"catalog" | "sso" | "company_profile" | "leads">("catalog");
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncStatusToast, setSyncStatusToast] = useState<string | null>(null);

  // Catalog State
  const [modules, setModules] = useState<RentedModuleCatalogItem[]>([]);
  const [loadingCatalog, setLoadingCatalog] = useState(true);
  const [editingModule, setEditingModule] = useState<RentedModuleCatalogItem | null>(null);
  const [searchCatalogQuery, setSearchCatalogQuery] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("ALL");

  // Leads State
  const [leads, setLeads] = useState<any[]>([]);
  const [newLeadModalOpen, setNewLeadModalOpen] = useState(false);
  const [newLeadForm, setNewLeadForm] = useState({
    clientName: "",
    contactPerson: "",
    email: "",
    phone: "",
    requestedModules: ["HRIS-GPS-QR"],
    estimatedUsers: 25,
    notes: ""
  });

  // Fetch catalog & leads from backend server API
  const fetchPortalData = async () => {
    setLoadingCatalog(true);
    try {
      const catRes = await fetch("/api/portal/catalog");
      if (catRes.ok) {
        const catData = await catRes.json();
        if (catData.modules) {
          setModules(catData.modules);
        }
      }

      const leadsRes = await fetch("/api/portal/leads");
      if (leadsRes.ok) {
        const leadsData = await leadsRes.json();
        if (leadsData.leads) {
          setLeads(leadsData.leads);
        }
      }
    } catch (e) {
      console.error("Error fetching portal data:", e);
    } finally {
      setLoadingCatalog(false);
    }
  };

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

  // Handle Publishing Catalog to https://median-cloud.web.id
  const handlePublishCatalogToPortal = async () => {
    setIsSyncing(true);
    try {
      const res = await fetch("/api/portal/catalog/publish", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ updatedModules: modules })
      });
      const data = await res.json();
      if (data.success) {
        setSyncStatusToast(data.message || "Katalog modul sewa berhasil dipublikasikan & disinkronkan ke https://median-cloud.web.id!");
        setTimeout(() => setSyncStatusToast(null), 7000);
      }
    } catch (e: any) {
      alert("Gagal mempublikasikan katalog: " + e.message);
    } finally {
      setIsSyncing(false);
    }
  };

  // Trigger manual sync handshake
  const handleTriggerSyncHandshake = async () => {
    setIsSyncing(true);
    try {
      const res = await fetch("/api/portal/sync-status", { method: "POST" });
      const data = await res.json();
      if (data.success) {
        setSyncStatusToast("Handshake Sukses! " + data.details);
        setTimeout(() => setSyncStatusToast(null), 8000);
      }
    } catch (e: any) {
      alert("Error sync handshake: " + e.message);
    } finally {
      setIsSyncing(false);
    }
  };

  // Submit new lead inquiry
  const handleCreateLeadInquiry = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await fetch("/api/portal/leads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newLeadForm)
      });
      const data = await res.json();
      if (data.success) {
        setLeads(prev => [data.lead, ...prev]);
        setNewLeadModalOpen(false);
        setSyncStatusToast("Pengajuan sewa modul baru berhasil dicatat dari Portal!");
        setTimeout(() => setSyncStatusToast(null), 6000);
      }
    } catch (err: any) {
      alert("Gagal mencatat inquiry: " + err.message);
    }
  };

  const handleUpdateModuleInCatalog = () => {
    if (!editingModule) return;
    setModules(prev => prev.map(m => m.id === editingModule.id ? editingModule : m));
    setEditingModule(null);
    setSyncStatusToast(`Modul "${editingModule.name}" diperbarui di draft lokal. Klik "Publish Ke Portal" untuk menyinkronkan live!`);
    setTimeout(() => setSyncStatusToast(null), 6000);
  };

  const categories = Array.from(new Set(modules.map(m => m.category)));

  const filteredModules = modules.filter(m => {
    const matchesSearch = m.name.toLowerCase().includes(searchCatalogQuery.toLowerCase()) || 
                          m.code.toLowerCase().includes(searchCatalogQuery.toLowerCase()) ||
                          m.description.toLowerCase().includes(searchCatalogQuery.toLowerCase());
    const matchesCategory = categoryFilter === "ALL" || m.category === categoryFilter;
    return matchesSearch && matchesCategory;
  });

  return (
    <div className="space-y-6 animate-fade-in pb-12">
      {/* Top Banner Header */}
      <div className="bg-gradient-to-r from-slate-950 via-[#081329] to-slate-950 border border-sky-500/30 rounded-2xl p-6 sm:p-8 shadow-2xl relative overflow-hidden">
        <div className="absolute top-0 right-0 w-96 h-96 bg-sky-500/10 rounded-full blur-3xl pointer-events-none"></div>

        <div className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6 relative z-10">
          <div className="space-y-2">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="px-3 py-1 bg-sky-500/20 text-sky-300 border border-sky-400/40 text-xs font-mono font-bold uppercase rounded-lg flex items-center gap-1.5 shadow-sm">
                <Globe className="w-3.5 h-3.5 text-sky-400 animate-pulse" />
                PORTAL SSO & MARKETING HUB (https://median-cloud.web.id)
              </span>
              <span className="px-2.5 py-1 bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 text-xs font-mono font-extrabold uppercase rounded-lg flex items-center gap-1">
                <Radio className="w-3.5 h-3.5 text-emerald-400 animate-ping" />
                PYTHON DJANGO SSO & SUPABASE DB: ACTIVE
              </span>
            </div>

            <h1 className="text-2xl sm:text-4xl font-black text-white tracking-tight">
              Portal & Catalog Synchronization Hub
            </h1>
            <p className="text-sm text-slate-300 max-w-3xl leading-relaxed">
              Pusat kendali integrasi antara Corporate Backend <strong>https://ems.median-cloud.web.id</strong> dengan Portal Utama <strong>https://median-cloud.web.id</strong> & Provider SSO Python Django <strong>https://auth.median-cloud.web.id</strong> terhubung ke Database Supabase PostgreSQL.
            </p>
          </div>

          <div className="flex items-center gap-3 shrink-0">
            <button
              onClick={handleTriggerSyncHandshake}
              disabled={isSyncing}
              className="px-4 py-3 bg-slate-900 hover:bg-slate-800 border border-slate-700 text-sky-300 font-bold text-xs uppercase rounded-xl transition-all flex items-center gap-2 cursor-pointer shadow-md disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 text-sky-400 ${isSyncing ? "animate-spin" : ""}`} />
              <span>Cek Handshake Sync</span>
            </button>

            <a
              href="https://median-cloud.web.id"
              target="_blank"
              rel="noopener noreferrer"
              className="px-5 py-3 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl shadow-lg shadow-sky-500/30 transition-all flex items-center gap-2 border border-sky-300 cursor-pointer"
            >
              <ExternalLink className="w-4 h-4 stroke-[3]" />
              <span>Buka Portal (median-cloud.web.id)</span>
            </a>
          </div>
        </div>

        {/* Sync Status Toast Alert */}
        {syncStatusToast && (
          <div className="mt-5 p-4 bg-emerald-950/80 border border-emerald-500/50 rounded-xl text-xs font-mono text-emerald-200 flex items-center justify-between gap-3 animate-fade-in shadow-xl">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
              <span>{syncStatusToast}</span>
            </div>
            <button onClick={() => setSyncStatusToast(null)} className="text-emerald-400 hover:text-white">
              <X className="w-4 h-4" />
            </button>
          </div>
        )}
      </div>

      {/* Primary Sub-Navigation Tabs */}
      <div className="flex items-center gap-2 border-b border-slate-800 pb-2 overflow-x-auto">
        <button
          onClick={() => setActiveSubTab("catalog")}
          className={`px-5 py-3 rounded-xl font-mono text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
            activeSubTab === "catalog"
              ? "bg-sky-500 text-slate-950 font-black shadow-lg shadow-sky-500/30"
              : "bg-slate-900/80 hover:bg-slate-800 text-slate-300 border border-slate-800"
          }`}
        >
          <ShoppingBag className="w-4 h-4" />
          <span>Katalog Modul Sewa ({modules.length})</span>
        </button>

        <button
          onClick={() => setActiveSubTab("sso")}
          className={`px-5 py-3 rounded-xl font-mono text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
            activeSubTab === "sso"
              ? "bg-sky-500 text-slate-950 font-black shadow-lg shadow-sky-500/30"
              : "bg-slate-900/80 hover:bg-slate-800 text-slate-300 border border-slate-800"
          }`}
        >
          <Key className="w-4 h-4" />
          <span>Single Sign-On (SSO Median ID)</span>
        </button>

        <button
          onClick={() => setActiveSubTab("company_profile")}
          className={`px-5 py-3 rounded-xl font-mono text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
            activeSubTab === "company_profile"
              ? "bg-sky-500 text-slate-950 font-black shadow-lg shadow-sky-500/30"
              : "bg-slate-900/80 hover:bg-slate-800 text-slate-300 border border-slate-800"
          }`}
        >
          <Building2 className="w-4 h-4" />
          <span>Profil Perusahaan & Web Marketing</span>
        </button>

        <button
          onClick={() => setActiveSubTab("leads")}
          className={`px-5 py-3 rounded-xl font-mono text-xs font-bold uppercase transition-all flex items-center gap-2 whitespace-nowrap cursor-pointer ${
            activeSubTab === "leads"
              ? "bg-sky-500 text-slate-950 font-black shadow-lg shadow-sky-500/30"
              : "bg-slate-900/80 hover:bg-slate-800 text-slate-300 border border-slate-800"
          }`}
        >
          <Mail className="w-4 h-4" />
          <span>Inquiry Sewa dari Portal ({leads.length})</span>
        </button>
      </div>

      {/* TAB 1: KATALOG MODUL SEWA ENTERPRISE */}
      {activeSubTab === "catalog" && (
        <div className="space-y-6 animate-fade-in">
          {/* Controls Bar */}
          <div className="bg-[#081026] border border-[#1e293b] p-4 rounded-2xl flex flex-col md:flex-row items-center justify-between gap-4">
            <div className="flex items-center gap-3 w-full md:w-auto">
              <div className="relative flex-1 md:w-72">
                <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  placeholder="Cari modul sewa..."
                  value={searchCatalogQuery}
                  onChange={e => setSearchCatalogQuery(e.target.value)}
                  className="w-full bg-[#0b132b] border border-slate-800 rounded-xl pl-9 pr-4 py-2 text-xs text-white placeholder-slate-500 focus:outline-none focus:border-sky-500 font-mono"
                />
              </div>

              <select
                value={categoryFilter}
                onChange={e => setCategoryFilter(e.target.value)}
                className="bg-[#0b132b] border border-slate-800 text-slate-200 text-xs font-mono rounded-xl px-3 py-2 focus:outline-none focus:border-sky-500"
              >
                <option value="ALL">Semua Kategori ({modules.length})</option>
                {categories.map((cat, i) => (
                  <option key={i} value={cat}>{cat}</option>
                ))}
              </select>
            </div>

            <div className="flex items-center gap-3 w-full md:w-auto justify-end">
              <span className="text-xs text-slate-400 font-mono hidden sm:inline">
                API Endpoint: <code className="text-sky-300 font-bold">/api/portal/catalog</code>
              </span>

              <button
                onClick={handlePublishCatalogToPortal}
                disabled={isSyncing}
                className="px-5 py-2.5 bg-gradient-to-r from-emerald-500 to-teal-500 hover:from-emerald-400 hover:to-teal-400 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl shadow-lg shadow-emerald-500/20 transition-all flex items-center gap-2 cursor-pointer border border-emerald-300 disabled:opacity-50"
              >
                <Share2 className="w-4 h-4 stroke-[3]" />
                <span>Publish Katalog ke Portal (median-cloud.web.id)</span>
              </button>
            </div>
          </div>

          {/* Catalog Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
            {filteredModules.map((item) => (
              <div 
                key={item.id}
                className="bg-[#081026] border border-[#1e293b] hover:border-sky-500/50 p-5 rounded-2xl space-y-4 flex flex-col justify-between transition-all group hover:shadow-xl hover:shadow-sky-500/10"
              >
                <div className="space-y-3">
                  <div className="flex items-start justify-between gap-2">
                    <span className="px-2.5 py-0.5 bg-sky-500/20 text-sky-300 border border-sky-400/40 text-[10px] font-mono font-bold uppercase rounded">
                      {item.category}
                    </span>
                    <span className="px-2 py-0.5 bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 text-[10px] font-mono font-extrabold uppercase rounded">
                      {item.popularBadge}
                    </span>
                  </div>

                  <div>
                    <div className="text-[11px] font-mono text-slate-400 font-bold uppercase tracking-wider">
                      CODE: {item.code}
                    </div>
                    <h3 className="text-base font-black text-white group-hover:text-sky-300 transition-colors mt-0.5">
                      {item.name}
                    </h3>
                  </div>

                  <p className="text-xs text-slate-300 leading-relaxed">
                    {item.description}
                  </p>

                  <div className="p-3 bg-[#0b132b] rounded-xl border border-slate-800/80 space-y-1">
                    <div className="text-[10px] uppercase font-mono text-slate-400 font-bold">Harga Sewa Modul:</div>
                    <div className="text-xl font-black text-emerald-400 flex items-baseline gap-1">
                      Rp {item.monthlyPrice.toLocaleString("id-ID")}
                      <span className="text-xs text-slate-400 font-mono font-normal">/ {item.priceUnit}</span>
                    </div>
                  </div>

                  {/* Feature Checklist */}
                  <div className="space-y-1.5 pt-1">
                    <div className="text-[11px] font-mono text-slate-400 font-bold uppercase">Fitur Utama Termasuk:</div>
                    <ul className="space-y-1 text-xs text-slate-300 font-mono">
                      {item.features.map((feat, fIdx) => (
                        <li key={fIdx} className="flex items-start gap-1.5">
                          <Check className="w-3.5 h-3.5 text-emerald-400 shrink-0 mt-0.5" />
                          <span>{feat}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>

                <div className="pt-4 border-t border-slate-800 flex items-center justify-between gap-2">
                  <a
                    href={item.demoUrl}
                    className="text-xs font-mono font-bold text-sky-400 hover:text-sky-300 flex items-center gap-1"
                  >
                    <span>Uji Coba Demo</span>
                    <ExternalLink className="w-3.5 h-3.5" />
                  </a>

                  <button
                    onClick={() => setEditingModule(item)}
                    className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-mono font-bold rounded-lg border border-slate-700 transition-colors flex items-center gap-1.5 cursor-pointer"
                  >
                    <Edit3 className="w-3.5 h-3.5 text-sky-400" />
                    <span>Edit Tarif & Deskripsi</span>
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* TAB 2: SINGLE SIGN-ON (SSO PYTHON DJANGO) */}
      {activeSubTab === "sso" && (
        <div className="space-y-6 animate-fade-in">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2 bg-[#081026] border border-[#1e293b] p-6 rounded-2xl space-y-5">
              <div className="flex items-center gap-3 border-b border-slate-800 pb-4">
                <div className="w-10 h-10 rounded-xl bg-sky-500/20 text-sky-300 border border-sky-400/40 flex items-center justify-center">
                  <Key className="w-5 h-5" />
                </div>
                <div>
                  <h2 className="text-lg font-black text-white">
                    Pengaturan Provider Single Sign-On (https://auth.median-cloud.web.id)
                  </h2>
                  <p className="text-xs text-slate-400 font-mono">
                    Python Django 5.x OAuth2 Server Handshake & Supabase PostgreSQL DB
                  </p>
                </div>
              </div>

              <div className="space-y-4 font-mono text-xs">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="bg-[#0b132b] p-3.5 rounded-xl border border-slate-800 space-y-1">
                    <span className="text-slate-400 text-[10px] uppercase font-bold">OAuth Provider URL (Django):</span>
                    <div className="text-sky-300 font-bold text-sm truncate">https://auth.median-cloud.web.id/o/authorize/</div>
                  </div>

                  <div className="bg-[#0b132b] p-3.5 rounded-xl border border-slate-800 space-y-1">
                    <span className="text-slate-400 text-[10px] uppercase font-bold">OAuth Client ID Registered:</span>
                    <div className="text-emerald-300 font-bold text-sm truncate">ems-gan-django-client</div>
                  </div>

                  <div className="bg-[#0b132b] p-3.5 rounded-xl border border-slate-800 space-y-1">
                    <span className="text-slate-400 text-[10px] uppercase font-bold">Redirect URI Callback:</span>
                    <div className="text-slate-200 font-bold text-xs truncate">/auth/callback</div>
                  </div>

                  <div className="bg-[#0b132b] p-3.5 rounded-xl border border-slate-800 space-y-1">
                    <span className="text-slate-400 text-[10px] uppercase font-bold">Scopes Diizinkan:</span>
                    <div className="text-amber-300 font-bold text-xs">openid, profile, email, nip, division, position</div>
                  </div>
                </div>

                <div className="bg-[#030712] p-4 rounded-xl border border-slate-800 space-y-2">
                  <div className="flex items-center justify-between text-xs text-slate-300">
                    <span className="font-bold uppercase text-sky-400">Pengujian Alur Autentikasi SSO User Django:</span>
                    <span className="text-emerald-400 font-bold">✓ Ready</span>
                  </div>
                  <p className="text-slate-400 leading-relaxed">
                    Setiap karyawan atau klien yang login di <strong>https://ems.median-cloud.web.id</strong> akan diarahkan secara otomatis ke server SSO Python Django <strong>https://auth.median-cloud.web.id</strong> untuk otentikasi terpusat terhubung ke Supabase DB.
                  </p>
                </div>
              </div>

              <div className="pt-2 flex items-center justify-between">
                <span className="text-xs text-slate-400 font-mono">
                  Status Koneksi SSO & DB: <strong className="text-emerald-400">ONLINE (DJANGO + SUPABASE)</strong>
                </span>

                <a
                  href="/api/auth/url"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="px-5 py-2.5 bg-sky-500 hover:bg-sky-400 text-slate-950 font-black text-xs uppercase tracking-wider rounded-xl transition-all flex items-center gap-2 shadow-lg shadow-sky-500/20"
                >
                  <ExternalLink className="w-4 h-4 stroke-[3]" />
                  <span>Test Autentikasi Django SSO</span>
                </a>
              </div>
            </div>

            {/* SSO User Session Card */}
            <div className="bg-[#081026] border border-[#1e293b] p-6 rounded-2xl space-y-4">
              <h3 className="text-sm font-bold text-sky-300 uppercase font-mono tracking-wider flex items-center gap-2">
                <ShieldCheck className="w-4 h-4 text-emerald-400" />
                Sesi User SSO Terverifikasi Saat Ini:
              </h3>

              {currentUser ? (
                <div className="bg-[#0b132b] p-4 rounded-xl border border-slate-800 space-y-3 font-mono text-xs">
                  <div className="flex items-center gap-3 border-b border-slate-800 pb-3">
                    <div className="w-10 h-10 rounded-full bg-sky-500/20 text-sky-300 font-black flex items-center justify-center border border-sky-400/40">
                      {currentUser.name.charAt(0)}
                    </div>
                    <div>
                      <div className="font-bold text-white text-sm">{currentUser.name}</div>
                      <div className="text-sky-300 text-[11px]">{currentUser.position}</div>
                    </div>
                  </div>

                  <div className="space-y-1.5 text-slate-300">
                    <div>NIP: <strong className="text-white">{currentUser.nip}</strong></div>
                    <div>Email: <strong className="text-white">{currentUser.email || "bambang.hartono@median-cloud.web.id"}</strong></div>
                    <div>Divisi: <strong className="text-white">{currentUser.department}</strong></div>
                    <div>Provider: <strong className="text-emerald-400">https://auth.median-cloud.web.id</strong></div>
                  </div>
                </div>
              ) : (
                <div className="text-xs text-slate-400 font-mono">Tidak ada user SSO terverifikasi saat ini.</div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* TAB 3: PROFIL PERUSAHAAN & WEB MARKETING */}
      {activeSubTab === "company_profile" && (
        <div className="space-y-6 animate-fade-in">
          <div className="bg-[#081026] border border-[#1e293b] p-6 sm:p-8 rounded-2xl space-y-6">
            <div className="flex items-center justify-between border-b border-slate-800 pb-4">
              <div>
                <h2 className="text-xl font-black text-white">
                  PT Media Ekosistem Digital Aplikasi Nasional (MEDIAN CLOUD)
                </h2>
                <p className="text-xs text-slate-400 font-mono mt-0.5">
                  Profil Perusahaan & Landing Page Marketing yang Tayang di https://median-cloud.web.id
                </p>
              </div>

              <span className="px-3 py-1 bg-sky-500/20 text-sky-300 border border-sky-400/40 text-xs font-mono font-bold rounded-lg uppercase">
                PORTAL MARKETING LIVE
              </span>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 font-mono text-xs">
              <div className="space-y-4">
                <div className="bg-[#0b132b] p-4 rounded-xl border border-slate-800 space-y-1">
                  <span className="text-slate-400 text-[10px] uppercase font-bold">Tagline Marketing:</span>
                  <p className="text-sm font-bold text-sky-300">
                    "Ekosistem Digital Terpadu untuk Solusi Enterprise & UMKM Indonesia"
                  </p>
                </div>

                <div className="bg-[#0b132b] p-4 rounded-xl border border-slate-800 space-y-1">
                  <span className="text-slate-400 text-[10px] uppercase font-bold">Alamat Kantor Pusat:</span>
                  <p className="text-slate-200">
                    MEDIAN Cloud Tower, Lt. 18-20, Jl. Jend. Sudirman Kav. 52-53, Jakarta Selatan 12190
                  </p>
                </div>

                <div className="bg-[#0b132b] p-4 rounded-xl border border-slate-800 space-y-1">
                  <span className="text-slate-400 text-[10px] uppercase font-bold">Kontak Resmi Perusahaan:</span>
                  <div className="text-slate-200 space-y-0.5">
                    <div>Email: <strong className="text-emerald-300">corporate@median-cloud.web.id</strong></div>
                    <div>Telepon: <strong className="text-white">+62 21 5088 9000</strong></div>
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div className="bg-[#0b132b] p-4 rounded-xl border border-slate-800 space-y-2">
                  <span className="text-slate-400 text-[10px] uppercase font-bold">Susunan Dewan Direksi:</span>
                  <ul className="space-y-1.5 text-slate-200">
                    <li className="flex justify-between"><span>Bambang Hartono</span><strong className="text-sky-300">Direktur Utama (CEO)</strong></li>
                    <li className="flex justify-between"><span>Dwi Wahyuni</span><strong className="text-sky-300">Direktur Keuangan & SDM (CFO)</strong></li>
                    <li className="flex justify-between"><span>Ahmad Subagyo</span><strong className="text-sky-300">Direktur Teknologi (CTO)</strong></li>
                  </ul>
                </div>

                <div className="bg-[#0b132b] p-4 rounded-xl border border-slate-800 space-y-1">
                  <span className="text-slate-400 text-[10px] uppercase font-bold">Visi & Misi Perusahaan:</span>
                  <p className="text-slate-300 leading-relaxed">
                    Menyediakan platform manajemen digital enterprise yang andal, aman, dan dapat disesuaikan untuk mempercepat transformasi digital nasional.
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* TAB 4: INQUIRY SEWA DARI PORTAL */}
      {activeSubTab === "leads" && (
        <div className="space-y-6 animate-fade-in">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-black text-white">
                Daftar Inquiry & Permintaan Sewa Modul dari Portal
              </h2>
              <p className="text-xs text-slate-400 font-mono">
                Permintaan sewa modul yang dikirim calon klien melalui form di https://median-cloud.web.id
              </p>
            </div>

            <button
              onClick={() => setNewLeadModalOpen(true)}
              className="px-4 py-2.5 bg-sky-500 hover:bg-sky-400 text-slate-950 font-black text-xs uppercase rounded-xl transition-all flex items-center gap-2 cursor-pointer shadow-lg shadow-sky-500/20"
            >
              <Plus className="w-4 h-4" />
              <span>Simulasi Form Portal</span>
            </button>
          </div>

          <div className="space-y-3">
            {leads.map((lead) => (
              <div 
                key={lead.id}
                className="bg-[#081026] border border-[#1e293b] p-5 rounded-2xl space-y-3 font-mono text-xs"
              >
                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                  <div className="flex items-center gap-2">
                    <span className="px-2 py-0.5 bg-sky-500/20 text-sky-300 border border-sky-400/40 text-[10px] font-bold rounded">
                      INQUIRY # {lead.id}
                    </span>
                    <strong className="text-white text-sm font-sans font-bold">{lead.clientName}</strong>
                  </div>

                  <span className="text-[10px] text-slate-400">
                    Dikirim: {new Date(lead.submittedAt).toLocaleString("id-ID")}
                  </span>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-slate-300">
                  <div>PIC: <strong className="text-white">{lead.contactPerson}</strong></div>
                  <div>Email: <strong className="text-sky-300">{lead.email}</strong></div>
                  <div>Telepon: <strong className="text-emerald-300">{lead.phone}</strong></div>
                </div>

                <div className="p-3 bg-[#0b132b] rounded-xl border border-slate-800 text-slate-300">
                  Catatan Klien: "{lead.notes}"
                </div>

                <div className="flex items-center justify-between pt-1">
                  <div className="flex items-center gap-1.5">
                    <span className="text-slate-400 text-[11px]">Modul Diminta:</span>
                    <div className="flex gap-1 flex-wrap">
                      {lead.requestedModules.map((m: string, i: number) => (
                        <span key={i} className="px-2 py-0.5 bg-slate-800 text-amber-300 border border-slate-700 text-[10px] rounded">
                          {m}
                        </span>
                      ))}
                    </div>
                  </div>

                  <span className="px-2.5 py-1 bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 text-[10px] font-bold uppercase rounded">
                    Status: {lead.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* MODAL EDIT CATALOG ITEM */}
      {editingModule && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="bg-[#081026] border border-sky-500/40 rounded-2xl max-w-xl w-full p-6 space-y-4 shadow-2xl font-mono">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <h3 className="text-base font-black text-white">
                Edit Katalog Modul Sewa ({editingModule.code})
              </h3>
              <button onClick={() => setEditingModule(null)} className="text-slate-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-3 text-xs">
              <div>
                <label className="text-slate-400 block mb-1">Nama Modul:</label>
                <input
                  type="text"
                  value={editingModule.name}
                  onChange={e => setEditingModule({ ...editingModule, name: e.target.value })}
                  className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-white"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-slate-400 block mb-1">Tarif Sewa (Rp):</label>
                  <input
                    type="number"
                    value={editingModule.monthlyPrice}
                    onChange={e => setEditingModule({ ...editingModule, monthlyPrice: Number(e.target.value) })}
                    className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-emerald-400 font-bold"
                  />
                </div>

                <div>
                  <label className="text-slate-400 block mb-1">Satuan Tarif:</label>
                  <input
                    type="text"
                    value={editingModule.priceUnit}
                    onChange={e => setEditingModule({ ...editingModule, priceUnit: e.target.value })}
                    className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-white"
                  />
                </div>
              </div>

              <div>
                <label className="text-slate-400 block mb-1">Deskripsi Singkat:</label>
                <textarea
                  rows={3}
                  value={editingModule.description}
                  onChange={e => setEditingModule({ ...editingModule, description: e.target.value })}
                  className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-white font-sans text-xs"
                />
              </div>
            </div>

            <div className="pt-2 flex items-center justify-end gap-2 border-t border-slate-800">
              <button
                onClick={() => setEditingModule(null)}
                className="px-4 py-2 bg-slate-800 text-slate-300 text-xs rounded-xl"
              >
                Batal
              </button>
              <button
                onClick={handleUpdateModuleInCatalog}
                className="px-5 py-2 bg-sky-500 text-slate-950 font-black text-xs uppercase rounded-xl shadow-lg shadow-sky-500/20"
              >
                Simpan Ke Katalog
              </button>
            </div>
          </div>
        </div>
      )}

      {/* MODAL SIMULASI FORM PORTAL LEADS */}
      {newLeadModalOpen && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <form onSubmit={handleCreateLeadInquiry} className="bg-[#081026] border border-sky-500/40 rounded-2xl max-w-lg w-full p-6 space-y-4 shadow-2xl font-mono">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <h3 className="text-base font-black text-white">
                Simulasi Form Inquiry dari Portal https://median-cloud.web.id
              </h3>
              <button type="button" onClick={() => setNewLeadModalOpen(false)} className="text-slate-400 hover:text-white">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-3 text-xs">
              <div>
                <label className="text-slate-400 block mb-1">Nama Perusahaan / Klien:</label>
                <input
                  type="text"
                  required
                  value={newLeadForm.clientName}
                  onChange={e => setNewLeadForm({ ...newLeadForm, clientName: e.target.value })}
                  placeholder="Contoh: PT Semen Perkasa Tbk"
                  className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-white"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-slate-400 block mb-1">Nama Kontak PIC:</label>
                  <input
                    type="text"
                    required
                    value={newLeadForm.contactPerson}
                    onChange={e => setNewLeadForm({ ...newLeadForm, contactPerson: e.target.value })}
                    placeholder="Bpk. Budi Santoso"
                    className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-white"
                  />
                </div>

                <div>
                  <label className="text-slate-400 block mb-1">Email Respon:</label>
                  <input
                    type="email"
                    required
                    value={newLeadForm.email}
                    onChange={e => setNewLeadForm({ ...newLeadForm, email: e.target.value })}
                    placeholder="budi@perkasa.co.id"
                    className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-white"
                  />
                </div>
              </div>

              <div>
                <label className="text-slate-400 block mb-1">Catatan / Kebutuhan:</label>
                <textarea
                  rows={3}
                  value={newLeadForm.notes}
                  onChange={e => setNewLeadForm({ ...newLeadForm, notes: e.target.value })}
                  placeholder="Deskripsikan kebutuhan modul sewa..."
                  className="w-full bg-[#0b132b] border border-slate-800 rounded-xl px-3 py-2 text-white font-sans text-xs"
                />
              </div>
            </div>

            <div className="pt-2 flex items-center justify-end gap-2 border-t border-slate-800">
              <button
                type="button"
                onClick={() => setNewLeadModalOpen(false)}
                className="px-4 py-2 bg-slate-800 text-slate-300 text-xs rounded-xl"
              >
                Batal
              </button>
              <button
                type="submit"
                className="px-5 py-2 bg-sky-500 text-slate-950 font-black text-xs uppercase rounded-xl shadow-lg shadow-sky-500/20"
              >
                Kirim Inquiry
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
};
