import React, { useState } from 'react';
import { ProfilPerusahaan, PeriodeAkuntansi, User } from '../../types/accounting';
import {
  LayoutDashboard,
  ListTree,
  BookMarked,
  Scale,
  Table2,
  FileBarChart2,
  Database,
  Users,
  ShieldCheck,
  BookOpen,
  Building,
  Menu,
  X,
  Lock,
  ChevronDown,
  Calendar,
  Sparkles,
  TrendingUp,
  Search,
  ChevronRight,
  ExternalLink,
  ArrowRightLeft,
  ListOrdered,
  Columns,
  Layers,
  PieChart,
  Calculator,
  Activity,
  CreditCard,
  QrCode,
  FileCheck,
  Globe,
  RefreshCw,
} from 'lucide-react';

interface MenuCategory {
  categoryTitle: string;
  items: {
    id: string;
    label: string;
    shortLabel?: string;
    icon: React.ComponentType<{ className?: string }>;
    badge?: string;
    badgeColor?: string;
    isAi?: boolean;
    onClick?: () => void;
  }[];
}

interface AdminLteLayoutProps {
  children: React.ReactNode;
  activeTab: string;
  onSelectTab: (tab: string) => void;
  profile: ProfilPerusahaan;
  activePeriode: PeriodeAkuntansi;
  periodes: PeriodeAkuntansi[];
  onSelectPeriode: (periode: PeriodeAkuntansi) => void;
  activeUser: User;
  onOpenProfilModal: () => void;
  onOpenTutupBukuModal: () => void;
  onOpenAiDiagnosticModal?: () => void;
  onOpenSignatoriesModal?: () => void;
  onOpenKelolaPeriodeModal?: () => void;
  accountCount: number;
  journalCount: number;
  isBalanced?: boolean;
}

export const AdminLteLayout: React.FC<AdminLteLayoutProps> = ({
  children,
  activeTab,
  onSelectTab,
  profile,
  activePeriode,
  periodes,
  onSelectPeriode,
  activeUser,
  onOpenProfilModal,
  onOpenTutupBukuModal,
  onOpenAiDiagnosticModal,
  onOpenSignatoriesModal,
  onOpenKelolaPeriodeModal,
  accountCount,
  journalCount,
  isBalanced = true,
}) => {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [userDropdownOpen, setUserDropdownOpen] = useState(false);
  const [menuSearch, setMenuSearch] = useState('');

  // Structured Menu Groups
  const menuCategories: MenuCategory[] = [
    {
      categoryTitle: 'IKHTISAR & ANALITIK',
      items: [
        {
          id: 'dashboard',
          label: 'Dashboard Eksekutif',
          icon: LayoutDashboard,
          badge: 'Live',
          badgeColor: 'bg-blue-600',
        },
      ],
    },
    {
      categoryTitle: 'PEMBUKUAN TRANSAKSI',
      items: [
        {
          id: 'coa',
          label: '1. Daftar Akun (COA)',
          shortLabel: 'Daftar Akun',
          icon: ListTree,
          badge: `${accountCount}`,
          badgeColor: 'bg-emerald-600',
        },
        {
          id: 'jurnal',
          label: '2. Jurnal Umum & Penyesuaian',
          shortLabel: 'Jurnal Umum',
          icon: BookMarked,
          badge: 'JU & AJP',
          badgeColor: 'bg-indigo-600',
        },
        {
          id: 'vendors',
          label: 'Buku Pembantu & Virtual Account',
          shortLabel: 'Vendor & VA (VL)',
          icon: CreditCard,
          badge: 'Virtual Ledger',
          badgeColor: 'bg-emerald-600',
        },
        {
          id: 'kelola-periode',
          label: 'Kelola Periode & Sinkronisasi',
          shortLabel: 'Kelola Periode',
          icon: Calendar,
          badge: `${periodes.length} Periode`,
          badgeColor: 'bg-blue-600',
          onClick: onOpenKelolaPeriodeModal,
        },
      ],
    },
    {
      categoryTitle: 'KERTAS KERJA & AUDIT',
      items: [
        {
          id: 'neracasaldo',
          label: '3. Neraca Saldo (Trial Balance)',
          shortLabel: 'Neraca Saldo',
          icon: Scale,
          badge: '3-Tahap',
          badgeColor: 'bg-purple-600',
        },
        {
          id: 'neracalajur',
          label: '4. Neraca Lajur (Worksheet)',
          shortLabel: 'Neraca Lajur',
          icon: Table2,
          badge: '10 Kolom',
          badgeColor: 'bg-cyan-600',
        },
        {
          id: 'ai-diagnostic',
          label: 'Audit & AI Diagnosa Saldo',
          shortLabel: 'AI Diagnosa',
          icon: Sparkles,
          badge: isBalanced ? 'AI Ready' : 'Perlu Cek',
          badgeColor: isBalanced ? 'bg-indigo-600' : 'bg-red-600 animate-pulse',
          isAi: true,
          onClick: onOpenAiDiagnosticModal,
        },
      ],
    },
    {
      categoryTitle: 'LAPORAN KEUANGAN RESMI',
      items: [
        {
          id: 'laporan-labarugi',
          label: '5. Laba Rugi & Perpajakan',
          shortLabel: 'Laba Rugi',
          icon: TrendingUp,
          badge: 'Bagian A & B',
          badgeColor: 'bg-emerald-600',
        },
        {
          id: 'laporan-ekuitas',
          label: '6. Capital Statement',
          shortLabel: 'Perubahan Modal',
          icon: ArrowRightLeft,
          badge: 'Bagian C',
          badgeColor: 'bg-amber-600',
        },
        {
          id: 'laporan-balancesheet',
          label: '7. Balance Sheet (Stafel)',
          shortLabel: 'Balance Sheet',
          icon: ListOrdered,
          badge: 'Bagian D',
          badgeColor: 'bg-indigo-600',
        },
        {
          id: 'laporan-skontro',
          label: '8. Neraca (Format Skontro)',
          shortLabel: 'Neraca Skontro',
          icon: Columns,
          badge: '2-Kolom',
          badgeColor: 'bg-blue-600',
        },
        {
          id: 'penyusutan',
          label: 'Rincian Penyusutan Aset Tetap',
          shortLabel: 'Rincian Penyusutan',
          icon: Calculator,
          badge: 'PSAK 16',
          badgeColor: 'bg-teal-600',
        },
        {
          id: 'laporan-pemetaan',
          label: 'Pemetaan Akun (Edukasi)',
          shortLabel: 'Pemetaan Akun',
          icon: Layers,
          badge: 'Matriks',
          badgeColor: 'bg-purple-600',
        },
        {
          id: 'laporan-aruskas',
          label: '9. Laporan Arus Kas',
          shortLabel: 'Arus Kas',
          icon: PieChart,
          badge: 'Kas',
          badgeColor: 'bg-teal-600',
        },
        {
          id: 'laporan-summary',
          label: 'Executive GOP & Summary',
          shortLabel: 'Ringkasan GOP',
          icon: Sparkles,
          badge: 'Eksekutif',
          badgeColor: 'bg-rose-600',
        },
        {
          id: 'analisis-rasio',
          label: '10. Analisis Rasio Keuangan',
          shortLabel: 'Rasio Keuangan',
          icon: Activity,
          badge: 'Likuiditas & Solvabilitas',
          badgeColor: 'bg-emerald-600',
        },
      ],
    },
    {
      categoryTitle: 'TEKNOLOGI & DATABASE',
      items: [
        {
          id: 'database',
          label: 'Database MySQL/PG & CI4',
          shortLabel: 'Database & CI4',
          icon: Database,
          badge: 'CI4 Ready',
          badgeColor: 'bg-amber-600',
        },
      ],
    },
    {
      categoryTitle: 'TATA KELOLA & PANDUAN',
      items: [
        {
          id: 'users',
          label: 'User & Permissions Matrix',
          shortLabel: 'Manajemen User',
          icon: Users,
        },
        {
          id: 'signatories-modal',
          label: 'Penandatangan Dokumen & QR Code',
          shortLabel: 'Tanda Tangan & QR',
          icon: FileCheck,
          badge: 'Dinamis',
          badgeColor: 'bg-blue-600',
          onClick: onOpenSignatoriesModal,
        },
        {
          id: 'audit',
          label: 'Audit Trail & Activity Log',
          shortLabel: 'Audit Trail',
          icon: ShieldCheck,
        },
        {
          id: 'panduan',
          label: 'Buku Panduan SOP Akuntansi',
          shortLabel: 'Panduan SOP',
          icon: BookOpen,
          badge: 'SOP',
          badgeColor: 'bg-emerald-700',
        },
      ],
    },
  ];

  // Current active label for breadcrumb
  let activeItemLabel = 'Dashboard Eksekutif';
  let activeItemCategory = 'IKHTISAR & ANALITIK';
  for (const cat of menuCategories) {
    for (const it of cat.items) {
      if (it.id === activeTab || (activeTab === 'laporan' && it.id === 'laporan-labarugi')) {
        activeItemLabel = it.label;
        activeItemCategory = cat.categoryTitle;
        break;
      }
    }
  }

  return (
    <div className="min-h-screen bg-slate-100 font-sans text-slate-800 flex flex-col">
      {/* Top Navbar */}
      <header className="sticky top-0 z-40 flex h-14 w-full items-center justify-between border-b border-slate-200 bg-white px-4 shadow-2xs print:hidden">
        {/* Left side */}
        <div className="flex items-center gap-3">
          <button
            onClick={() => setSidebarOpen(!sidebarOpen)}
            className="rounded p-1.5 text-slate-600 hover:bg-slate-100 hover:text-slate-900 transition-colors"
            title="Toggle Sidebar Menu"
          >
            <Menu className="h-5 w-5" />
          </button>

          {/* Brand and Breadcrumb */}
          <div className="flex items-center gap-2">
            <span className="font-bold text-sm text-slate-900 uppercase tracking-wider hidden sm:inline">
              {profile.namaPerusahaan}
            </span>
            <div className="hidden lg:flex items-center gap-1.5 text-xs text-slate-400 pl-2 border-l border-slate-200">
              <span>{activeItemCategory}</span>
              <ChevronRight className="h-3 w-3" />
              <span className="font-semibold text-slate-700">{activeItemLabel}</span>
            </div>
          </div>
        </div>

        {/* Right side tools */}
        <div className="flex items-center gap-2 sm:gap-3">
          {/* AI Audit Quick Trigger */}
          {onOpenAiDiagnosticModal && (
            <button
              onClick={onOpenAiDiagnosticModal}
              className={`hidden md:inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 text-xs font-bold text-white shadow-2xs transition-all ${
                !isBalanced
                  ? 'bg-red-600 hover:bg-red-700 animate-pulse'
                  : 'bg-linear-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700'
              }`}
              title="Audit AI Keseimbangan Pembukuan"
            >
              <Sparkles className="h-3.5 w-3.5" />
              {!isBalanced ? 'Perlu Audit AI!' : 'AI Diagnosa'}
            </button>
          )}

          {/* Active Period Selector */}
          <div className="flex items-center gap-1.5 rounded-lg border border-blue-200 bg-blue-50/70 px-2.5 py-1 text-xs">
            <Calendar className="h-3.5 w-3.5 text-blue-700" />
            <span className="text-slate-600 hidden xl:inline">Periode:</span>
            <select
              value={activePeriode.id}
              onChange={(e) => {
                const target = periodes.find((p) => p.id === e.target.value);
                if (target) onSelectPeriode(target);
              }}
              className="bg-transparent font-bold text-blue-900 focus:outline-hidden cursor-pointer text-xs"
            >
              {periodes.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.namaPeriode} {p.isClosed ? '(Tutup)' : '(Aktif)'}
                </option>
              ))}
            </select>
          </div>

          {/* Quick Kelola Periode Button */}
          {onOpenKelolaPeriodeModal && (
            <button
              onClick={onOpenKelolaPeriodeModal}
              className="hidden lg:inline-flex items-center gap-1 rounded border border-blue-300 bg-white px-2 py-1 text-xs font-semibold text-blue-700 hover:bg-blue-50 shadow-2xs transition-colors cursor-pointer"
              title="Kelola & Sinkronkan Semua Periode Akuntansi"
            >
              <RefreshCw className="h-3 w-3 text-blue-600" />
              <span className="hidden xl:inline">Kelola Periode</span>
            </button>
          )}

          {/* Quick Tutup Buku Button */}
          <button
            onClick={onOpenTutupBukuModal}
            className="hidden sm:inline-flex items-center gap-1 rounded bg-amber-600 px-2.5 py-1 text-xs font-semibold text-white hover:bg-amber-700 shadow-2xs"
            title="Tutup Buku Periode & Roll-over Saldo Otomatis"
          >
            <Lock className="h-3 w-3" />
            Tutup Buku
          </button>

          {/* Quick Signatories & QR Trigger */}
          {onOpenSignatoriesModal && (
            <button
              onClick={onOpenSignatoriesModal}
              className="hidden lg:inline-flex items-center gap-1.5 rounded-lg border border-slate-300 bg-slate-50 px-2.5 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-100 hover:text-slate-900 shadow-2xs transition-colors cursor-pointer"
              title="Atur Pejabat Penandatangan Dokumen Dinamis & QR Code Resmi"
            >
              <QrCode className="h-3.5 w-3.5 text-blue-600" />
              <span>Tanda Tangan & QR</span>
            </button>
          )}

          {/* Profil Perusahaan modal trigger */}
          <button
            onClick={onOpenProfilModal}
            className="inline-flex items-center gap-1 rounded border border-slate-300 bg-white px-2.5 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-50"
            title="Ubah Profil PT & Logo (Kamera/Lokal/Cloud)"
          >
            <Building className="h-3.5 w-3.5 text-slate-500" />
            <span className="hidden md:inline">Profil PT</span>
          </button>

          {/* Web Perusahaan link */}
          {profile.website && (
            <a
              href={profile.website}
              target="_blank"
              rel="noopener noreferrer"
              className="hidden lg:inline-flex items-center gap-1.5 rounded border border-blue-200 bg-blue-50 px-2.5 py-1 text-xs font-semibold text-blue-700 hover:bg-blue-100 hover:text-blue-900 transition-colors"
              title={`Kunjungi Website Resmi Perusahaan: ${profile.website}`}
            >
              <Globe className="h-3.5 w-3.5 text-blue-600" />
              <span>Web PT</span>
              <ExternalLink className="h-3 w-3 text-blue-500" />
            </a>
          )}

          {/* User profile dropdown button */}
          <div className="relative">
            <button
              onClick={() => setUserDropdownOpen(!userDropdownOpen)}
              className="flex items-center gap-2 rounded-full p-1 hover:bg-slate-100"
            >
              <img
                src={
                  activeUser.avatarUrl ||
                  'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100'
                }
                alt={activeUser.name}
                className="h-8 w-8 rounded-full object-cover border border-slate-300"
              />
              <div className="hidden lg:block text-left">
                <div className="text-xs font-bold text-slate-800 leading-tight">
                  {activeUser.name}
                </div>
                <div className="text-[10px] uppercase font-semibold text-blue-700">
                  {activeUser.role}
                </div>
              </div>
              <ChevronDown className="h-3 w-3 text-slate-400" />
            </button>

            {userDropdownOpen && (
              <div className="absolute right-0 mt-2 w-56 rounded-lg border border-slate-200 bg-white py-2 shadow-xl z-50 text-xs">
                <div className="px-4 py-2 border-b border-slate-100">
                  <p className="font-bold text-slate-900">{activeUser.name}</p>
                  <p className="text-[11px] text-slate-500 font-mono">{activeUser.email}</p>
                  <span className="mt-1 inline-block rounded bg-blue-100 px-2 py-0.5 text-[10px] font-bold text-blue-800 uppercase">
                    Role: {activeUser.role}
                  </span>
                </div>
                <button
                  onClick={() => {
                    onSelectTab('users');
                    setUserDropdownOpen(false);
                  }}
                  className="flex w-full items-center gap-2 px-4 py-2 hover:bg-slate-50 text-slate-700"
                >
                  <Users className="h-4 w-4" /> Kelola Pengguna & Hak Akses
                </button>
                <button
                  onClick={() => {
                    onOpenProfilModal();
                    setUserDropdownOpen(false);
                  }}
                  className="flex w-full items-center gap-2 px-4 py-2 hover:bg-slate-50 text-slate-700"
                >
                  <Building className="h-4 w-4" /> Pengaturan Logo Perusahaan
                </button>
                {profile.website && (
                  <a
                    href={profile.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    onClick={() => setUserDropdownOpen(false)}
                    className="flex w-full items-center justify-between px-4 py-2 hover:bg-blue-50 text-blue-700 font-medium"
                  >
                    <span className="flex items-center gap-2">
                      <Globe className="h-4 w-4 text-blue-600" /> Web Resmi PT
                    </span>
                    <ExternalLink className="h-3 w-3 text-blue-400" />
                  </a>
                )}
                <div className="border-t border-slate-100 pt-1">
                  <button
                    onClick={() => {
                      setUserDropdownOpen(false);
                      onSelectTab('panduan');
                    }}
                    className="flex w-full items-center gap-2 px-4 py-2 hover:bg-slate-50 text-slate-700"
                  >
                    <BookOpen className="h-4 w-4" /> Buka Panduan Pemakaian
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* Main Container */}
      <div className="flex flex-1 overflow-hidden">
        {/* AdminLTE Dark Sidebar */}
        <aside
          className={`${
            sidebarOpen ? 'w-64' : 'w-0 -translate-x-full lg:w-16 lg:translate-x-0'
          } shrink-0 bg-slate-900 text-slate-300 transition-all duration-300 ease-in-out z-30 flex flex-col print:hidden shadow-lg border-r border-slate-800`}
        >
          {/* Brand Header */}
          <div className="flex h-14 items-center gap-3 border-b border-slate-800 px-4 bg-slate-950">
            {profile.logoUrl ? (
              <img
                src={profile.logoUrl}
                alt="Logo"
                className="h-8 w-8 rounded-md object-cover bg-white p-0.5 shadow-xs"
              />
            ) : (
              <Building className="h-8 w-8 text-blue-400" />
            )}
            {sidebarOpen && (
              <div className="truncate">
                <div className="font-bold text-xs text-white uppercase tracking-wider truncate">
                  {profile.namaPerusahaan}
                </div>
                <div className="text-[10px] text-slate-400">AdminLTE Enterprise SIA</div>
              </div>
            )}
          </div>

          {/* User Profile Mini Card */}
          {sidebarOpen && (
            <div className="border-b border-slate-800 p-3 bg-slate-950/40">
              <div className="flex items-center gap-3">
                <img
                  src={
                    activeUser.avatarUrl ||
                    'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=100'
                  }
                  alt={activeUser.name}
                  className="h-9 w-9 rounded-full object-cover border border-slate-700"
                />
                <div className="truncate">
                  <div className="font-semibold text-xs text-white truncate">{activeUser.name}</div>
                  <div className="flex items-center gap-1.5 text-[10px] text-emerald-400 font-medium">
                    <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 inline-block animate-pulse"></span>
                    Online &bull; {activeUser.role}
                  </div>
                </div>
              </div>

              {/* Sidebar Menu Search */}
              <div className="relative mt-2.5">
                <Search className="absolute left-2.5 top-2 h-3 w-3 text-slate-500" />
                <input
                  type="text"
                  placeholder="Cari menu sistem..."
                  value={menuSearch}
                  onChange={(e) => setMenuSearch(e.target.value)}
                  className="w-full rounded bg-slate-800/80 border border-slate-700/80 pl-7 pr-2.5 py-1 text-[11px] text-slate-200 placeholder-slate-500 focus:border-blue-500 focus:outline-hidden"
                />
              </div>
            </div>
          )}

          {/* Grouped Accordion Navigation */}
          <nav className="flex-1 overflow-y-auto px-2 py-3 space-y-4">
            {menuCategories.map((group, groupIdx) => {
              const filteredItems = group.items.filter((item) =>
                item.label.toLowerCase().includes(menuSearch.toLowerCase())
              );

              if (filteredItems.length === 0) return null;

              return (
                <div key={groupIdx} className="space-y-1">
                  {sidebarOpen && (
                    <div className="px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider text-slate-400">
                      {group.categoryTitle}
                    </div>
                  )}

                  <div className="space-y-0.5">
                    {filteredItems.map((item) => {
                      const Icon = item.icon;
                      const isActive =
                        activeTab === item.id ||
                        (activeTab === 'laporan' && item.id === 'laporan-labarugi');

                      return (
                        <button
                          key={item.id}
                          onClick={() => {
                            if (item.onClick) {
                              item.onClick();
                            } else {
                              onSelectTab(item.id);
                            }
                          }}
                          title={item.label}
                          className={`group flex w-full items-center justify-between rounded-md px-2.5 py-1.5 text-xs font-medium transition-all ${
                            isActive
                              ? 'bg-blue-600 text-white font-semibold shadow-xs'
                              : item.isAi
                              ? 'text-indigo-300 hover:bg-indigo-950/50 hover:text-indigo-200'
                              : 'text-slate-300 hover:bg-slate-800/80 hover:text-white'
                          }`}
                        >
                          <div className="flex items-center gap-2.5 truncate">
                            <Icon
                              className={`h-4 w-4 shrink-0 transition-colors ${
                                isActive
                                  ? 'text-white'
                                  : item.isAi
                                  ? 'text-indigo-400 group-hover:text-indigo-300'
                                  : 'text-slate-400 group-hover:text-slate-200'
                              }`}
                            />
                            {sidebarOpen && (
                              <span className="truncate">
                                {sidebarOpen ? item.label : item.shortLabel || item.label}
                              </span>
                            )}
                          </div>

                          {sidebarOpen && item.badge && (
                            <span
                              className={`rounded px-1.5 py-0.5 text-[10px] font-bold text-white shrink-0 ${
                                item.badgeColor || 'bg-slate-700'
                              }`}
                            >
                              {item.badge}
                            </span>
                          )}
                        </button>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </nav>

          {/* Sidebar Footer */}
          {sidebarOpen && (
            <div className="border-t border-slate-800 p-3 text-[11px] text-slate-500 bg-slate-950/60 text-center">
              <div className="font-semibold text-slate-400">PT Tio Mandiri Jaya &copy; 2026</div>
              <div className="text-[10px] text-slate-600">CI4 &amp; PostgreSQL/MySQL Edition</div>
            </div>
          )}
        </aside>

        {/* Content Area */}
        <main className="flex-1 overflow-y-auto p-4 sm:p-6 print:p-0 print:overflow-visible">
          {children}
        </main>
      </div>

      {/* AdminLTE Bottom Footer */}
      <footer className="border-t border-slate-200 bg-white py-3 px-6 text-xs text-slate-500 flex flex-col sm:flex-row items-center justify-between gap-2 print:hidden">
        <div>
          <strong>Hak Cipta &copy; 2026 {profile.namaPerusahaan}.</strong> Seluruh hak dilindungi undang-undang.
        </div>
        <div className="flex items-center gap-3">
          <span>Standar Akuntansi: SAK EMKM / PSAK Indonesia</span>
          <span className="font-mono text-slate-400">CI4 v4.4+ Ready</span>
        </div>
      </footer>
    </div>
  );
};
