'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useAuthStore } from '@/lib/auth/store';
import { 
  HomeIcon,
  CreditCardIcon,
  ServerIcon,
  ChatBubbleLeftRightIcon,
  UserIcon,
  Bars3Icon,
  XMarkIcon,
  BellIcon,
  ArrowRightOnRectangleIcon
} from '@heroicons/react/24/outline';

interface DashboardLayoutProps {
  children: React.ReactNode;
}

interface NavigationChild {
  name: string;
  href: string;
  icon?: React.ComponentType<React.SVGProps<SVGSVGElement>>;
}

interface NavigationItem {
  name: string;
  href?: string;
  icon: React.ComponentType<React.SVGProps<SVGSVGElement>>;
  children?: NavigationChild[];
}

const navigation = [
  { name: 'Dashboard', href: '/dashboard', icon: HomeIcon },
  { 
    name: 'Billing', 
    icon: CreditCardIcon,
    children: [
      { name: 'Invoices', href: '/billing/invoices' },
      { name: 'Payment Methods', href: '/billing/payments' },
    ]
  },
  { name: 'Subscriptions', href: '/subscriptions', icon: ServerIcon },
  { 
    name: 'Support', 
    icon: ChatBubbleLeftRightIcon,
    children: [
      { name: 'Cases', href: '/support/cases' },
      { name: 'New Case', href: '/support/new' },
      { name: 'Knowledge Base', href: '/support/kb' },
    ]
  },
  { 
    name: 'Account', 
    icon: UserIcon,
    children: [
      { name: 'Profile', href: '/account/profile' },
      { name: 'Security', href: '/account/security' },
      { name: 'Notifications', href: '/account/notifications' },
    ]
  },
];

export function DashboardLayout({ children }: DashboardLayoutProps) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [expandedItems, setExpandedItems] = useState<string[]>([]);
  const [mounted, setMounted] = useState(false);
  const { user, isAuthenticated, logout, checkAuth } = useAuthStore();
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    setMounted(true);
    // Check auth on mount
    checkAuth();
  }, [checkAuth]);

  useEffect(() => {
    if (mounted && !isAuthenticated) {
      router.push('/auth/login');
    }
  }, [mounted, isAuthenticated, router]);

  const toggleExpanded = (itemName: string) => {
    setExpandedItems(prev => 
      prev.includes(itemName) 
        ? prev.filter(name => name !== itemName)
        : [...prev, itemName]
    );
  };

  const handleLogout = async () => {
    await logout();
    router.push('/');
  };

  // Show loading state until mounted and auth is checked
  if (!mounted) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-screen flex overflow-hidden bg-gray-100">
      {/* Mobile sidebar overlay */}
      {sidebarOpen && (
        <div className="fixed inset-0 flex z-40 md:hidden">
          <div className="fixed inset-0 bg-gray-600 bg-opacity-75" onClick={() => setSidebarOpen(false)} />
          <div className="relative flex-1 flex flex-col max-w-xs w-full bg-white">
            <div className="absolute top-0 right-0 -mr-12 pt-2">
              <button
                type="button"
                className="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"
                onClick={() => setSidebarOpen(false)}
              >
                <XMarkIcon className="h-6 w-6 text-white" />
              </button>
            </div>
            <MobileSidebar 
              navigation={navigation} 
              pathname={pathname} 
              expandedItems={expandedItems}
              toggleExpanded={toggleExpanded}
            />
          </div>
        </div>
      )}

      {/* Desktop sidebar */}
      <div className="hidden md:flex md:flex-shrink-0">
        <div className="flex flex-col w-64">
          <DesktopSidebar 
            navigation={navigation} 
            pathname={pathname} 
            expandedItems={expandedItems}
            toggleExpanded={toggleExpanded}
          />
        </div>
      </div>

      {/* Main content */}
      <div className="flex flex-col w-0 flex-1 overflow-hidden">
        {/* Top navigation */}
        <div className="relative z-10 flex-shrink-0 flex h-16 bg-white shadow">
          <button
            type="button"
            className="px-4 border-r border-gray-200 text-gray-500 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-blue-500 md:hidden"
            onClick={() => setSidebarOpen(true)}
          >
            <Bars3Icon className="h-6 w-6" />
          </button>
          <div className="flex-1 px-4 flex justify-between">
            <div className="flex-1 flex">
              <div className="w-full flex md:ml-0">
                <div className="relative w-full text-gray-400 focus-within:text-gray-600">
                  <div className="flex items-center h-16">
                    <h1 className="text-lg font-semibold text-gray-900">
                      Assist Solutions Portal
                    </h1>
                  </div>
                </div>
              </div>
            </div>
            <div className="ml-4 flex items-center md:ml-6">
              {/* Notifications */}
              <button
                type="button"
                className="bg-white p-1 rounded-full text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                <BellIcon className="h-6 w-6" />
              </button>

              {/* Profile dropdown */}
              <div className="ml-3 relative">
                <div className="flex items-center space-x-3">
                  <div className="text-right">
                    <p className="text-sm font-medium text-gray-900">
                      {user?.firstName && user?.lastName 
                        ? `${user.firstName} ${user.lastName}` 
                        : user?.firstName 
                        ? user.firstName
                        : user?.email?.split('@')[0] || 'User'
                      }
                    </p>
                    <p className="text-xs text-gray-500">{user?.email || ''}</p>
                  </div>
                  <button
                    onClick={handleLogout}
                    className="bg-white p-1 rounded-full text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                    title="Sign out"
                  >
                    <ArrowRightOnRectangleIcon className="h-6 w-6" />
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Page content */}
        <main className="flex-1 relative overflow-y-auto focus:outline-none">
          {children}
        </main>
      </div>
    </div>
  );
}

function DesktopSidebar({ 
  navigation, 
  pathname, 
  expandedItems, 
  toggleExpanded 
}: {
  navigation: NavigationItem[];
  pathname: string;
  expandedItems: string[];
  toggleExpanded: (name: string) => void;
}) {
  return (
    <div className="flex flex-col h-0 flex-1 border-r border-gray-200 bg-white">
      <div className="flex-1 flex flex-col pt-5 pb-4 overflow-y-auto">
        <div className="flex items-center flex-shrink-0 px-4">
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-lg flex items-center justify-center">
              <span className="text-white font-bold text-sm">AS</span>
            </div>
            <span className="text-lg font-semibold text-gray-900">Portal</span>
          </div>
        </div>
        <nav className="mt-5 flex-1 px-2 space-y-1">
          {navigation.map((item) => (
            <NavigationItem
              key={item.name}
              item={item}
              pathname={pathname}
              isExpanded={expandedItems.includes(item.name)}
              toggleExpanded={toggleExpanded}
            />
          ))}
        </nav>
      </div>
    </div>
  );
}

function MobileSidebar({ 
  navigation, 
  pathname, 
  expandedItems, 
  toggleExpanded 
}: {
  navigation: NavigationItem[];
  pathname: string;
  expandedItems: string[];
  toggleExpanded: (name: string) => void;
}) {
  return (
    <div className="flex flex-col h-0 flex-1 border-r border-gray-200 bg-white">
      <div className="flex-1 flex flex-col pt-5 pb-4 overflow-y-auto">
        <div className="flex items-center flex-shrink-0 px-4">
          <div className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-lg flex items-center justify-center">
              <span className="text-white font-bold text-sm">AS</span>
            </div>
            <span className="text-lg font-semibold text-gray-900">Portal</span>
          </div>
        </div>
        <nav className="mt-5 flex-1 px-2 space-y-1">
          {navigation.map((item) => (
            <NavigationItem
              key={item.name}
              item={item}
              pathname={pathname}
              isExpanded={expandedItems.includes(item.name)}
              toggleExpanded={toggleExpanded}
            />
          ))}
        </nav>
      </div>
    </div>
  );
}

function NavigationItem({ 
  item, 
  pathname, 
  isExpanded, 
  toggleExpanded 
}: {
  item: NavigationItem;
  pathname: string;
  isExpanded: boolean;
  toggleExpanded: (name: string) => void;
}) {
  const hasChildren = item.children && item.children.length > 0;
  const isActive = hasChildren 
    ? item.children?.some((child: NavigationChild) => pathname.startsWith(child.href)) || false
    : item.href ? pathname === item.href : false;

  if (hasChildren) {
    return (
      <div>
        <button
          onClick={() => toggleExpanded(item.name)}
          className={`
            ${isActive ? 'bg-blue-50 text-blue-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}
            group w-full flex items-center pl-2 pr-1 py-2 text-left text-sm font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500
          `}
        >
          <item.icon className={`${isActive ? 'text-blue-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-6 w-6`} />
          <span className="flex-1">{item.name}</span>
          <svg
            className={`${isExpanded ? 'rotate-90' : ''} ml-3 h-5 w-5 transform transition-transform`}
            viewBox="0 0 20 20"
            fill="currentColor"
          >
            <path fillRule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clipRule="evenodd" />
          </svg>
        </button>
        {isExpanded && (
          <div className="mt-1 space-y-1">
            {item.children?.map((child: NavigationChild) => (
              <Link
                key={child.name}
                href={child.href}
                className={`
                  ${pathname === child.href ? 'bg-blue-50 text-blue-700 border-r-2 border-blue-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}
                  group w-full flex items-center pl-11 pr-2 py-2 text-sm rounded-md
                `}
              >
                {child.name}
              </Link>
            ))}
          </div>
        )}
      </div>
    );
  }

  return (
    <Link
      href={item.href || '#'}
      className={`
        ${isActive ? 'bg-blue-50 text-blue-700 border-r-2 border-blue-700' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'}
        group flex items-center px-2 py-2 text-sm font-medium rounded-md
      `}
    >
      <item.icon className={`${isActive ? 'text-blue-500' : 'text-gray-400 group-hover:text-gray-500'} mr-3 flex-shrink-0 h-6 w-6`} />
      {item.name}
    </Link>
  );
}
