"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  AlertCircle,
  Building2,
  Check,
  ChevronRight,
  Crown,
  Lock,
  Pencil,
  Plus,
  Power,
  Settings2,
  Shield,
  Trash2,
  X,
} from "lucide-react";

interface ClientModule {
  id: number;
  moduleKey: string;
  moduleName: string;
  isEnabled: boolean;
}

interface ClientAccount {
  id: number;
  companyName: string;
  slug: string;
  contactEmail: string;
  contactPhone: string;
  planTier: string;
  status: string;
  createdAt: string;
  modules: ClientModule[];
}

interface AvailableModule {
  key: string;
  name: string;
  description: string;
}

const MODULE_ICONS: Record<string, string> = {
  hris: "👥",
  text_messaging: "💬",
  org_chart: "🌳",
  job_boards: "📢",
  careers_portal: "🌐",
  advanced_reporting: "📊",
  onboarding: "📋",
  scheduling: "🗓️",
};

export default function SuperAdminClientsPage() {
  const [clients, setClients] = useState<ClientAccount[]>([]);
  const [availableModules, setAvailableModules] = useState<AvailableModule[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentUserRole, setCurrentUserRole] = useState<string | null>(null);
  const [isSuperAdmin, setIsSuperAdmin] = useState(false);

  // Modals
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingClient, setEditingClient] = useState<ClientAccount | null>(null);
  const [managingModulesClient, setManagingModulesClient] = useState<ClientAccount | null>(null);

  // Form states
  const [newClient, setNewClient] = useState({ companyName: "", slug: "", contactEmail: "", contactPhone: "", planTier: "starter", enabledModules: ["careers_portal"] });
  const [editClient, setEditClient] = useState({ companyName: "", contactEmail: "", contactPhone: "", planTier: "starter", status: "active" });
  const [moduleStates, setModuleStates] = useState<Record<string, boolean>>({});

  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    async function init() {
      try {
        const meRes = await fetch("/api/me");
        const meData = await meRes.json();
        const role = meData?.user?.role || "recruiter";
        setCurrentUserRole(role);
        setIsSuperAdmin(role === "super_admin");

        if (role === "super_admin") {
          await loadClients();
        }
      } catch {
        setError("Failed to load user permissions.");
      } finally {
        setLoading(false);
      }
    }
    init();
  }, []);

  async function loadClients() {
    try {
      const res = await fetch("/api/clients");
      const data = await res.json();
      if (res.ok) {
        setClients(data.clients);
        setAvailableModules(data.availableModules);
      } else {
        setError(data.error || "Failed to load clients.");
      }
    } catch {
      setError("Network error loading clients.");
    }
  }

  function openCreateClient() {
    setNewClient({ companyName: "", slug: "", contactEmail: "", contactPhone: "", planTier: "starter", enabledModules: ["careers_portal"] });
    setShowCreateModal(true);
    setError("");
    setNotice("");
  }

  function openEditClient(client: ClientAccount) {
    setEditClient({
      companyName: client.companyName,
      contactEmail: client.contactEmail,
      contactPhone: client.contactPhone || "",
      planTier: client.planTier,
      status: client.status,
    });
    setEditingClient(client);
    setError("");
    setNotice("");
  }

  function openManageModules(client: ClientAccount) {
    const states: Record<string, boolean> = {};
    availableModules.forEach((mod) => {
      const existing = client.modules.find((m) => m.moduleKey === mod.key);
      states[mod.key] = existing?.isEnabled || false;
    });
    setModuleStates(states);
    setManagingModulesClient(client);
    setError("");
    setNotice("");
  }

  async function handleCreateClient(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const res = await fetch("/api/clients", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newClient),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(`Client "${data.companyName}" created successfully!`);
        setShowCreateModal(false);
        await loadClients();
      } else {
        setError(data.error || "Failed to create client.");
      }
    } catch {
      setError("Network error creating client.");
    } finally {
      setSaving(false);
    }
  }

  async function handleUpdateClient(e: React.FormEvent) {
    e.preventDefault();
    if (!editingClient) return;
    setSaving(true);
    setError("");
    try {
      const res = await fetch(`/api/clients/${editingClient.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(editClient),
      });
      const data = await res.json();
      if (res.ok) {
        setNotice(`Client "${data.companyName}" updated successfully!`);
        setEditingClient(null);
        await loadClients();
      } else {
        setError(data.error || "Failed to update client.");
      }
    } catch {
      setError("Network error updating client.");
    } finally {
      setSaving(false);
    }
  }

  async function handleDeleteClient(client: ClientAccount) {
    if (!confirm(`Are you sure you want to delete "${client.companyName}"? This cannot be undone.`)) return;
    try {
      const res = await fetch(`/api/clients/${client.id}`, { method: "DELETE" });
      if (res.ok) {
        setNotice(`Client "${client.companyName}" deleted.`);
        await loadClients();
      }
    } catch {
      setError("Failed to delete client.");
    }
  }

  async function toggleModule(moduleKey: string) {
    if (!managingModulesClient) return;
    const newState = !moduleStates[moduleKey];
    setModuleStates((prev) => ({ ...prev, [moduleKey]: newState }));

    try {
      const res = await fetch(`/api/clients/${managingModulesClient.id}/modules`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ moduleKey, isEnabled: newState }),
      });
      if (res.ok) {
        setNotice(`Module ${newState ? "enabled" : "disabled"} for ${managingModulesClient.companyName}.`);
        await loadClients();
      } else {
        setModuleStates((prev) => ({ ...prev, [moduleKey]: !newState }));
        setError("Failed to toggle module.");
      }
    } catch {
      setModuleStates((prev) => ({ ...prev, [moduleKey]: !newState }));
      setError("Network error toggling module.");
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-indigo-600" />
      </div>
    );
  }

  if (!isSuperAdmin) {
    return (
      <div className="p-6 max-w-3xl mx-auto">
        <div className="bg-white rounded-3xl border border-amber-200 p-8 shadow-sm text-center space-y-4">
          <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-amber-100 text-amber-700">
            <Lock className="w-7 h-7" />
          </div>
          <h2 className="text-2xl font-extrabold text-gray-900">Super Administrator Access Required</h2>
          <p className="text-sm text-gray-500 max-w-md mx-auto">
            Only H.R. Vista super administrators can manage client accounts and toggle paid module access. Your current role is <strong>{currentUserRole}</strong>.
          </p>
          <Link href="/settings" className="inline-flex items-center gap-1.5 px-4 py-2.5 bg-indigo-600 text-white rounded-xl text-sm font-bold">
            Return to Settings <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="bg-white rounded-3xl border border-gray-200 p-6 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div className="p-3 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl text-white">
            <Crown className="w-6 h-6" />
          </div>
          <div>
            <h1 className="text-2xl font-extrabold text-gray-900">Client Account Management</h1>
            <p className="text-sm text-gray-500">Provision client workspaces and toggle paid feature modules per account.</p>
          </div>
        </div>
        <button
          onClick={openCreateClient}
          className="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold text-sm flex items-center gap-2 shadow-sm"
        >
          <Plus className="w-4 h-4" /> Provision New Client
        </button>
      </div>

      {notice && (
        <div className="p-4 bg-emerald-50 border border-emerald-200 rounded-2xl text-sm font-bold text-emerald-800 flex items-center justify-between">
          <div className="flex items-center gap-2"><Check className="w-5 h-5 text-emerald-600" /><span>{notice}</span></div>
          <button onClick={() => setNotice("")} className="text-emerald-600 hover:text-emerald-800"><X className="w-4 h-4" /></button>
        </div>
      )}

      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-2xl text-sm font-semibold text-red-700 flex items-center justify-between">
          <div className="flex items-center gap-2"><AlertCircle className="w-5 h-5 text-red-600" /><span>{error}</span></div>
          <button onClick={() => setError("")} className="text-red-600 hover:text-red-800"><X className="w-4 h-4" /></button>
        </div>
      )}

      {/* Client Accounts Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        {clients.length === 0 ? (
          <div className="col-span-2 bg-white rounded-3xl border border-dashed border-gray-300 p-12 text-center text-gray-400 space-y-2">
            <Building2 className="w-10 h-10 mx-auto text-gray-300" />
            <p className="font-bold text-gray-700">No client accounts provisioned yet.</p>
            <p className="text-xs">Click "Provision New Client" to create your first client workspace.</p>
          </div>
        ) : (
          clients.map((client) => {
            const enabledCount = client.modules.filter((m) => m.isEnabled).length;
            return (
              <div key={client.id} className="bg-white rounded-2xl border border-gray-200 shadow-sm p-5 space-y-4 hover:shadow-md transition-shadow">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-11 h-11 rounded-xl bg-indigo-100 text-indigo-700 font-black flex items-center justify-center text-lg shrink-0">
                      {client.companyName[0]}
                    </div>
                    <div>
                      <h3 className="font-bold text-gray-900">{client.companyName}</h3>
                      <p className="text-xs text-gray-500 font-mono">{client.slug}</p>
                    </div>
                  </div>
                  <span className={`text-[10px] font-extrabold px-2.5 py-1 rounded-full uppercase ${
                    client.status === "active" ? "bg-emerald-100 text-emerald-800" : client.status === "suspended" ? "bg-amber-100 text-amber-800" : "bg-red-100 text-red-800"
                  }`}>{client.status}</span>
                </div>

                <div className="grid grid-cols-3 gap-3 text-xs">
                  <div className="p-2.5 bg-gray-50 rounded-lg border border-gray-100">
                    <p className="text-gray-400 font-bold uppercase">Plan</p>
                    <p className="font-bold text-gray-900 capitalize mt-0.5">{client.planTier}</p>
                  </div>
                  <div className="p-2.5 bg-gray-50 rounded-lg border border-gray-100">
                    <p className="text-gray-400 font-bold uppercase">Modules</p>
                    <p className="font-bold text-gray-900 mt-0.5">{enabledCount}/{client.modules.length}</p>
                  </div>
                  <div className="p-2.5 bg-gray-50 rounded-lg border border-gray-100">
                    <p className="text-gray-400 font-bold uppercase">Contact</p>
                    <p className="font-medium text-gray-900 truncate mt-0.5">{client.contactEmail.split("@")[0]}</p>
                  </div>
                </div>

                {/* Enabled Modules Preview */}
                <div className="flex flex-wrap gap-1 pt-2 border-t border-gray-100">
                  {client.modules.filter((m) => m.isEnabled).length === 0 ? (
                    <span className="text-[10px] text-gray-400 italic">No modules enabled</span>
                  ) : (
                    client.modules
                      .filter((m) => m.isEnabled)
                      .slice(0, 4)
                      .map((m) => (
                        <span key={m.id} className="text-[10px] font-bold px-2 py-0.5 bg-indigo-50 text-indigo-700 rounded-md border border-indigo-100">
                          {MODULE_ICONS[m.moduleKey] || "🔧"} {m.moduleName.split(" ")[0]}
                        </span>
                      ))
                  )}
                </div>

                <div className="flex items-center gap-2 pt-3 border-t border-gray-100">
                  <button
                    onClick={() => openManageModules(client)}
                    className="flex-1 flex items-center justify-center gap-1.5 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-bold transition-colors"
                  >
                    <Power className="w-3.5 h-3.5" /> Manage Modules
                  </button>
                  <button
                    onClick={() => openEditClient(client)}
                    className="p-2 text-gray-500 hover:text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
                    title="Edit client"
                  >
                    <Pencil className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => handleDeleteClient(client)}
                    className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                    title="Delete client"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* Create Client Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="px-6 py-5 bg-indigo-600 text-white flex items-center justify-between">
              <h2 className="font-bold text-lg flex items-center gap-2"><Building2 className="w-5 h-5" /> Provision New Client</h2>
              <button onClick={() => setShowCreateModal(false)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleCreateClient} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-bold text-gray-700 mb-1">Company Name *</label>
                <input value={newClient.companyName} onChange={(e) => setNewClient({ ...newClient, companyName: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none" placeholder="e.g. AMCE Corp" />
              </div>
              <div>
                <label className="block text-sm font-bold text-gray-700 mb-1">URL Slug</label>
                <input value={newClient.slug} onChange={(e) => setNewClient({ ...newClient, slug: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none" placeholder="auto-generated-from-name" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-1">Contact Email *</label>
                  <input type="email" value={newClient.contactEmail} onChange={(e) => setNewClient({ ...newClient, contactEmail: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none" placeholder="admin@company.com" />
                </div>
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-1">Contact Phone</label>
                  <input value={newClient.contactPhone} onChange={(e) => setNewClient({ ...newClient, contactPhone: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none" placeholder="+1 (555) 000-0000" />
                </div>
              </div>
              <div>
                <label className="block text-sm font-bold text-gray-700 mb-1">Plan Tier</label>
                <select value={newClient.planTier} onChange={(e) => setNewClient({ ...newClient, planTier: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none">
                  <option value="starter">Starter</option>
                  <option value="professional">Professional</option>
                  <option value="enterprise">Enterprise</option>
                </select>
              </div>
              <div className="p-4 bg-blue-50 border border-blue-100 rounded-xl space-y-2">
                <p className="text-sm font-bold text-gray-800">Enable Modules for this Client</p>
                <div className="grid grid-cols-2 gap-2">
                  {availableModules.map((mod) => (
                    <label key={mod.key} className="flex items-center gap-2 text-xs cursor-pointer p-2 rounded-lg hover:bg-white border border-transparent hover:border-blue-200">
                      <input type="checkbox" checked={newClient.enabledModules.includes(mod.key)} onChange={(e) => {
                        if (e.target.checked) setNewClient({ ...newClient, enabledModules: [...newClient.enabledModules, mod.key] });
                        else setNewClient({ ...newClient, enabledModules: newClient.enabledModules.filter((k) => k !== mod.key) });
                      }} className="rounded border-gray-300" />
                      <span className="font-semibold text-gray-700">{mod.name}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setShowCreateModal(false)} className="px-4 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-100 rounded-xl">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2.5 bg-indigo-600 text-white font-bold text-sm rounded-xl hover:bg-indigo-700 disabled:opacity-50">{saving ? "Creating..." : "Create Client"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Edit Client Modal */}
      {editingClient && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden">
            <div className="px-6 py-5 bg-indigo-600 text-white flex items-center justify-between">
              <h2 className="font-bold text-lg flex items-center gap-2"><Pencil className="w-5 h-5" /> Edit Client</h2>
              <button onClick={() => setEditingClient(null)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <form onSubmit={handleUpdateClient} className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-bold text-gray-700 mb-1">Company Name *</label>
                <input value={editClient.companyName} onChange={(e) => setEditClient({ ...editClient, companyName: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none" />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-1">Contact Email *</label>
                  <input type="email" value={editClient.contactEmail} onChange={(e) => setEditClient({ ...editClient, contactEmail: e.target.value })} required className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none" />
                </div>
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-1">Contact Phone</label>
                  <input value={editClient.contactPhone} onChange={(e) => setEditClient({ ...editClient, contactPhone: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-1">Plan Tier</label>
                  <select value={editClient.planTier} onChange={(e) => setEditClient({ ...editClient, planTier: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none">
                    <option value="starter">Starter</option>
                    <option value="professional">Professional</option>
                    <option value="enterprise">Enterprise</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-bold text-gray-700 mb-1">Status</label>
                  <select value={editClient.status} onChange={(e) => setEditClient({ ...editClient, status: e.target.value })} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 focus:outline-none">
                    <option value="active">Active</option>
                    <option value="suspended">Suspended</option>
                    <option value="cancelled">Cancelled</option>
                  </select>
                </div>
              </div>
              <div className="pt-4 border-t border-gray-100 flex justify-end gap-3">
                <button type="button" onClick={() => setEditingClient(null)} className="px-4 py-2.5 text-sm font-bold text-gray-700 hover:bg-gray-100 rounded-xl">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2.5 bg-indigo-600 text-white font-bold text-sm rounded-xl hover:bg-indigo-700 disabled:opacity-50">{saving ? "Saving..." : "Save Changes"}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Manage Modules Modal */}
      {managingModulesClient && (
        <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="px-6 py-5 bg-gradient-to-r from-indigo-600 to-purple-700 text-white flex items-center justify-between">
              <div>
                <h2 className="font-bold text-lg flex items-center gap-2"><Settings2 className="w-5 h-5" /> Module Management</h2>
                <p className="text-xs text-indigo-200 mt-0.5">Toggle paid features for {managingModulesClient.companyName}</p>
              </div>
              <button onClick={() => setManagingModulesClient(null)} className="p-2 text-indigo-100 hover:text-white"><X className="w-5 h-5" /></button>
            </div>

            <div className="p-6 space-y-3">
              {availableModules.map((mod) => {
                const isEnabled = moduleStates[mod.key] || false;
                return (
                  <div key={mod.key} className={`p-4 rounded-xl border-2 transition-all flex items-center justify-between gap-4 ${isEnabled ? "border-indigo-500 bg-indigo-50/50" : "border-gray-200 bg-white"}`}>
                    <div className="flex items-center gap-3 min-w-0">
                      <span className="text-2xl shrink-0">{MODULE_ICONS[mod.key] || "🔧"}</span>
                      <div className="min-w-0">
                        <p className="font-bold text-gray-900 text-sm">{mod.name}</p>
                        <p className="text-xs text-gray-500 leading-snug">{mod.description}</p>
                      </div>
                    </div>
                    <button
                      onClick={() => toggleModule(mod.key)}
                      className={`relative inline-flex h-7 w-12 shrink-0 cursor-pointer rounded-full transition-colors ${isEnabled ? "bg-indigo-600" : "bg-gray-300"}`}
                    >
                      <span className={`inline-block h-5 w-5 transform rounded-full bg-white shadow-sm transition-transform mt-1 ${isEnabled ? "translate-x-6" : "translate-x-1"}`} />
                    </button>
                  </div>
                );
              })}
            </div>

            <div className="px-6 py-4 bg-gray-50 border-t border-gray-100 flex justify-between items-center">
              <p className="text-xs text-gray-500">
                {Object.values(moduleStates).filter(Boolean).length} of {availableModules.length} modules enabled
              </p>
              <button onClick={() => setManagingModulesClient(null)} className="px-5 py-2.5 bg-indigo-600 text-white font-bold text-sm rounded-xl hover:bg-indigo-700">
                Done
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
