'use client';

import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter, usePathname } from 'next/navigation';
import '@/app/admin/admin.css';

interface AdminLayoutProps {
  children: React.ReactNode;
  title: string;
}

const menuItems = [
  { icon: '📊', label: 'Dashboard', href: '/admin' },
  { icon: '📄', label: 'Artikel', href: '/admin/articles' },
  { icon: '💆', label: 'Treatments', href: '/admin/treatments' },
  { icon: '🚀', label: 'Promo', href: '/admin/promo' },
  { icon: '👨‍⚕️', label: 'Dokter', href: '/admin/doctors' },
  { icon: '⭐', label: 'Testimonial', href: '/admin/testimonials' },
  { icon: '📍', label: 'Locations', href: '/admin/locations' },
  { icon: '🖼️', label: 'Banner Slider', href: '/admin/banner' },
  { icon: '👥', label: 'Users', href: '/admin/users' },
];

export default function AdminLayout({ children, title }: AdminLayoutProps) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [userData, setUserData] = useState<{ fullName?: string; photo?: string; username?: string; role?: string } | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const router = useRouter();

  // Click outside to close dropdown
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setDropdownOpen(false);
      }
    };
    if (dropdownOpen) document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [dropdownOpen]);
  const pathname = usePathname();

  useEffect(() => {
    try {
      const stored = localStorage.getItem('admin_user');
      if (stored) setUserData(JSON.parse(stored));
    } catch (e) {}
  }, []);

  const handleLogout = () => {
    localStorage.removeItem('admin_logged_in');
    localStorage.removeItem('admin_token');
    localStorage.removeItem('admin_user');
    router.push('/admin/login');
  };

  const userInitial = (userData?.fullName || userData?.username || 'A').charAt(0).toUpperCase();

  return (
    <div className="min-h-screen bg-gray-50 admin-body">
      {/* Sidebar */}
      <aside className={`sidebar sidebar-transition ${sidebarOpen ? 'sidebar-open' : 'sidebar-closed'}`}>
        <div className="sidebar-header">
          <Link href="/admin">
            <Image src="/images/Logo-Carla.png" alt="Carla" width={140} height={40} className="sidebar-logo" />
          </Link>
          <button onClick={() => setSidebarOpen(false)} className="lg:hidden text-gray-400 hover:text-gray-600">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>
        <nav className="sidebar-nav">
          <p className="sidebar-label">Menu</p>
          {menuItems.map((item) => {
            const isActive = pathname === item.href || (item.href !== '/admin' && pathname.startsWith(item.href));
            return (
              <Link key={item.label} href={item.href}
                className={`sidebar-link ${isActive ? 'sidebar-link-active' : 'sidebar-link-inactive'}`}>
                <span className="text-lg">{item.icon}</span>
                <span>{item.label}</span>
              </Link>
            );
          })}
        </nav>
      </aside>

      {/* Overlay */}
      {sidebarOpen && <div className="admin-overlay" onClick={() => setSidebarOpen(false)} />}

      {/* Main */}
      <div className="admin-content">
        {/* Header */}
        <header className="admin-header">
          <div className="admin-header-inner">
            <div className="flex items-center gap-3">
              <button onClick={() => setSidebarOpen(true)} className="admin-hamburger">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16"/></svg>
              </button>
              <h1 className="admin-header-title">{title}</h1>
            </div>

            {/* Right: Profile Dropdown - Click to toggle */}
            <div className="relative" ref={dropdownRef}>
              <button
                className="flex items-center gap-2 text-gray-700 hover:text-gray-900 transition"
                onClick={() => setDropdownOpen(!dropdownOpen)}
              >
                <span className="h-9 w-9 rounded-full overflow-hidden border-2 border-gray-200">
                  {userData?.photo ? (
                    <img src={userData.photo} className="w-full h-full object-cover" />
                  ) : (
                    <span className="flex items-center justify-center w-full h-full bg-gold/20 text-gold font-semibold text-sm">{userInitial}</span>
                  )}
                </span>
                <span className="hidden sm:block text-sm font-medium">{userData?.fullName || userData?.username || 'Admin'}</span>
                <svg className={`w-4 h-4 text-gray-400 transition-transform duration-200 ${dropdownOpen ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7"/></svg>
              </button>

              {dropdownOpen && (
                <div
                  className="absolute right-0 top-full mt-2 w-56 bg-white rounded-xl border border-gray-200 shadow-lg py-2 z-50"
                  onMouseLeave={() => setDropdownOpen(false)}
                >
                  <div className="px-4 py-3 border-b border-gray-100">
                    <p className="text-sm font-semibold text-gray-800">{userData?.fullName || userData?.username}</p>
                    <p className="text-xs text-gray-400 capitalize">{userData?.role || 'Admin'}</p>
                  </div>
                  <Link href="/admin/profile" onClick={() => setDropdownOpen(false)}
                    className="flex items-center gap-3 px-4 py-2.5 text-sm text-gray-600 hover:bg-gray-50 transition">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                    Profil Saya
                  </Link>
                  <hr className="border-gray-100 my-1" />
                  <button onClick={() => { setDropdownOpen(false); handleLogout(); }}
                    className="flex items-center gap-3 px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 w-full transition">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
                    Logout
                  </button>
                </div>
              )}
            </div>
          </div>
        </header>

        {/* Content */}
        <main className="admin-main">
          {children}
        </main>
      </div>
    </div>
  );
}
