'use client';

import React, { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import Link from 'next/link';
import { apiRequest } from '@/lib/api';
import Icons8Icon from '@/components/icons/Icons8Icon';
import {
  LayoutDashboard,
  RefreshCw,
  ShoppingBag,
  Settings,
  MessageSquare,
  LogOut,
  User,
  Activity,
  LayoutList,
  Menu,
  X,
  Users,
  Sun,
  Moon,
  AlertCircle,
} from 'lucide-react';

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { user, logout, loading } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [hasWhatsApp, setHasWhatsApp] = useState(false);
  const [theme, setTheme] = useState<'dark' | 'light'>('dark');

  useEffect(() => {
    const savedTheme = localStorage.getItem('theme') as 'dark' | 'light' | null;
    if (savedTheme) {
      setTheme(savedTheme);
      if (savedTheme === 'light') {
        document.documentElement.classList.add('light');
      } else {
        document.documentElement.classList.remove('light');
      }
    }
  }, []);

  const toggleTheme = () => {
    if (theme === 'dark') {
      setTheme('light');
      document.documentElement.classList.add('light');
      localStorage.setItem('theme', 'light');
    } else {
      setTheme('dark');
      document.documentElement.classList.remove('light');
      localStorage.setItem('theme', 'dark');
    }
  };

  const isExpiredOrUnsubscribed = user && (user.subscriptionStatus === 'UNSUBSCRIBED' || user.onboardingStep !== 'ONBOARDING_COMPLETED');
  const isAllowedPath = pathname === '/dashboard/billing' || pathname === '/dashboard/profile' || pathname === '/dashboard/billing/confirm';

  useEffect(() => {
    if (!loading && !user) {
      router.push('/login');
      return;
    }

    if (!loading && user && isExpiredOrUnsubscribed && !isAllowedPath) {
      router.push('/dashboard/billing');
    }
  }, [user, loading, router, pathname, isExpiredOrUnsubscribed, isAllowedPath]);

  useEffect(() => {
    // Close sidebar on route change
    setSidebarOpen(false);
  }, [pathname]);

  useEffect(() => {
    async function checkWhatsApp() {
      try {
        const integrations = await apiRequest('api/integrations').catch(() => []);
        if (Array.isArray(integrations)) {
          const wa = integrations.find((i: any) => i.integrationType === 'whatsapp' && i.status === 'ACTIVE');
          setHasWhatsApp(!!wa);
        }
      } catch {
        // Silent catch for unsubscribed accounts
      }
    }
    if (user && !isExpiredOrUnsubscribed) {
      checkWhatsApp();
    }
  }, [user, isExpiredOrUnsubscribed]);

  if (loading || !user || (isExpiredOrUnsubscribed && !isAllowedPath)) {
    return (
      <div className="flex h-screen w-screen items-center justify-center bg-background">
        <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-emerald-500 border-t-transparent"></div>
      </div>
    );
  }

  const menuItems: { name: string; href: string; iconName: 'overview' | '1sync' | 'shopping-cart' | 'customers' | 'prototype' | 'settings' | 'user' | 'delivery' }[] = [
    { name: 'Overview', href: '/dashboard', iconName: 'overview' },
    { name: 'Products & Sync', href: '/dashboard/products', iconName: '1sync' },
    { name: 'Orders & Sales', href: '/dashboard/orders', iconName: 'shopping-cart' },
    { name: 'Deliveries', href: '/dashboard/deliveries', iconName: 'delivery' },
    { name: 'Customers', href: '/dashboard/customers', iconName: 'customers' },
    { name: 'Message Templates', href: '/dashboard/templates', iconName: 'prototype' },
    { name: 'Integrations', href: '/dashboard/integrations', iconName: 'settings' },
    { name: 'Store Profile', href: '/dashboard/profile', iconName: 'user' },
  ];

  return (
    <div className="h-screen w-screen overflow-hidden md:p-6 lg:p-8 flex items-center justify-center bg-[var(--outer-bg)] text-slate-800 dark:text-gray-100 font-sans">
      <div className="w-full h-full md:max-w-7xl bg-background md:rounded-none md:shadow-2xl md:border md:border-slate-200/60 dark:md:border-white/5 flex overflow-hidden relative">
        {/* Sidebar Backdrop Overlay on Mobile */}
        {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 md:hidden transition-all duration-300"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar (Sliding Drawer on Mobile, Static on Desktop) */}
      <aside
        className={`fixed inset-y-0 left-0 w-64 glass-panel border-y-0 border-l-0 flex flex-col h-full z-50 transform ${
          sidebarOpen ? 'translate-x-0' : '-translate-x-full'
        } md:translate-x-0 md:static transition-transform duration-300 ease-in-out`}
      >
        {/* Brand Logo & Theme Toggle Header */}
        <div className="p-5 border-b border-white/5 flex items-center justify-between gap-2">
          <h1 className="font-black text-xs tracking-widest text-emerald-600 dark:text-emerald-400 Outfit uppercase leading-snug">
            WhatsApp Commerce Hub
          </h1>
          <div className="flex items-center gap-1.5 shrink-0">
            <button
              onClick={toggleTheme}
              title={theme === 'light' ? 'Switch to Dark Mode' : 'Switch to Light Mode'}
              className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-white/5 transition-colors cursor-pointer border-0 bg-transparent outline-none"
              aria-label="Toggle theme"
            >
              {theme === 'light' ? (
                <Moon className="h-4 w-4 text-gray-400 hover:text-white" />
              ) : (
                <Sun className="h-4 w-4 text-gray-400 hover:text-white" />
              )}
            </button>
            <button
              onClick={() => setSidebarOpen(false)}
              className="p-1.5 rounded-lg text-gray-400 hover:text-white md:hidden hover:bg-white/5 transition-colors cursor-pointer"
              aria-label="Close sidebar"
            >
              <X className="h-5 w-5" />
            </button>
          </div>
        </div>

        {/* Menu Navigation */}
        <nav className="flex-1 px-4 py-6 space-y-1 overflow-y-auto">
          {menuItems.map((item) => {
            const isActive = pathname === item.href;
            return (
              <Link
                key={item.name}
                href={item.href}
                className={`flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all ${
                  isActive
                    ? 'active-sidebar-link text-white pl-3.5'
                    : 'text-gray-400 hover:bg-white/5 hover:text-white'
                }`}
              >
                <Icons8Icon 
                  name={item.iconName} 
                  className={`h-[23px] w-[23px] ${isActive ? 'text-emerald-500 dark:text-emerald-400' : 'text-gray-400'}`} 
                />
                {item.name}
              </Link>
            );
          })}
        </nav>

        {/* Profile Card & Logout */}
        <div className="p-4 border-t border-white/5 space-y-3 bg-black/10">
          <div className="flex items-center gap-3 px-1 py-1">
            <div className="h-8 w-8 rounded-full bg-emerald-50 dark:bg-emerald-500/10 border border-emerald-100 dark:border-emerald-500/20 flex items-center justify-center shrink-0">
              <User className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
            </div>
            <div className="overflow-hidden">
              <p className="text-xs font-semibold text-white truncate">{user.name}</p>
              <p className="text-[10px] text-gray-500 truncate">{user.email}</p>
            </div>
          </div>
          <button
            onClick={logout}
            className="w-full flex items-center gap-3 px-4 py-2 rounded-lg text-xs font-medium text-red-400 hover:bg-red-500/10 hover:text-red-300 transition-all cursor-pointer"
          >
            <LogOut className="h-4 w-4" />
            Logout Account
          </button>
        </div>
      </aside>

      {/* Main Body */}
      <main className="flex-1 flex flex-col h-full overflow-hidden relative">
        {/* Top Header */}
        <header className="h-16 border-b border-white/5 flex items-center justify-between px-4 md:px-8 z-10 bg-background/60 backdrop-blur-md md:hidden">
          <div className="flex items-center justify-between w-full">
            <div className="flex items-center gap-3">
              <button
                onClick={() => setSidebarOpen(true)}
                className="p-2 rounded-lg bg-white/5 border border-white/10 text-gray-400 hover:text-white hover:bg-white/10 transition-colors cursor-pointer"
                aria-label="Open sidebar"
              >
                <Menu className="h-5 w-5" />
              </button>
              <span className="font-black text-xs tracking-wide text-emerald-600 dark:text-emerald-400 Outfit uppercase select-none">
                WhatsApp Commerce
              </span>
            </div>
            <button
              onClick={toggleTheme}
              title={theme === 'light' ? 'Switch to Dark Mode' : 'Switch to Light Mode'}
              className="p-1.5 rounded-lg text-gray-400 hover:text-white hover:bg-white/5 transition-colors cursor-pointer border-0 bg-transparent outline-none"
              aria-label="Toggle theme"
            >
              {theme === 'light' ? (
                <Moon className="h-4 w-4 text-gray-400 hover:text-white" />
              ) : (
                <Sun className="h-4 w-4 text-gray-400 hover:text-white" />
              )}
            </button>
          </div>
        </header>

        {/* Content Area */}
        <div key={pathname} className="flex-1 overflow-y-auto p-4 md:p-8 relative z-0 animate-page-slide-in scrollbar-thin">
          {children}
        </div>
      </main>
      </div>
    </div>
  );
}
