'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { motion } from 'framer-motion';
import {
  Building2, Wallet, Users, Package, FileText,
  LayoutDashboard, ChevronRight, ChevronDown,
  CreditCard, Receipt, PiggyBank, UserPlus,
  Clock, CalendarDays, Boxes, Truck, ShoppingCart,
  FileCheck, ScrollText, Brain, ArrowLeft,
  Monitor, UtensilsCrossed, ListOrdered, Printer,
  Settings, BarChart3, PenTool, TrendingUp, UserCircle,
  Target, Handshake, FileSpreadsheet
} from 'lucide-react';

interface NavItem {
  label: string;
  href?: string;
  icon: React.ReactNode;
  children?: NavItem[];
}

const navItems: NavItem[] = [
  {
    label: 'Overview',
    href: '/ghost-control/operations',
    icon: <LayoutDashboard className="w-4 h-4" />,
  },
  {
    label: 'Finance',
    icon: <Wallet className="w-4 h-4" />,
    children: [
      { label: 'Dashboard', href: '/ghost-control/operations/finance', icon: <Building2 className="w-4 h-4" /> },
      { label: 'Accounts', href: '/ghost-control/operations/finance/accounts', icon: <CreditCard className="w-4 h-4" /> },
      { label: 'Transactions', href: '/ghost-control/operations/finance/transactions', icon: <Receipt className="w-4 h-4" /> },
      { label: 'Budgets', href: '/ghost-control/operations/finance/budgets', icon: <PiggyBank className="w-4 h-4" /> },
    ],
  },
  {
    label: 'HR & People',
    icon: <Users className="w-4 h-4" />,
    children: [
      { label: 'Dashboard', href: '/ghost-control/operations/hr', icon: <Building2 className="w-4 h-4" /> },
      { label: 'Employees', href: '/ghost-control/operations/hr/employees', icon: <UserPlus className="w-4 h-4" /> },
      { label: 'Time Tracking', href: '/ghost-control/operations/hr/time', icon: <Clock className="w-4 h-4" /> },
      { label: 'Leave Requests', href: '/ghost-control/operations/hr/leave', icon: <CalendarDays className="w-4 h-4" /> },
    ],
  },
  {
    label: 'Inventory',
    icon: <Package className="w-4 h-4" />,
    children: [
      { label: 'Dashboard', href: '/ghost-control/operations/inventory', icon: <Building2 className="w-4 h-4" /> },
      { label: 'Products', href: '/ghost-control/operations/inventory/products', icon: <Boxes className="w-4 h-4" /> },
      { label: 'Suppliers', href: '/ghost-control/operations/inventory/suppliers', icon: <Truck className="w-4 h-4" /> },
      { label: 'Orders', href: '/ghost-control/operations/inventory/orders', icon: <ShoppingCart className="w-4 h-4" /> },
    ],
  },
  {
    label: 'CRM & Sales',
    icon: <TrendingUp className="w-4 h-4" />,
    children: [
      { label: 'Dashboard', href: '/ghost-control/operations/crm', icon: <Building2 className="w-4 h-4" /> },
      { label: 'Customers', href: '/ghost-control/operations/crm/customers', icon: <UserCircle className="w-4 h-4" /> },
      { label: 'Contacts', href: '/ghost-control/operations/crm/contacts', icon: <Users className="w-4 h-4" /> },
      { label: 'Leads', href: '/ghost-control/operations/crm/leads', icon: <Target className="w-4 h-4" /> },
      { label: 'Opportunities', href: '/ghost-control/operations/crm/opportunities', icon: <Handshake className="w-4 h-4" /> },
      { label: 'Sales Orders', href: '/ghost-control/operations/crm/orders', icon: <FileSpreadsheet className="w-4 h-4" /> },
    ],
  },
  {
    label: 'Documents',
    icon: <FileText className="w-4 h-4" />,
    children: [
      { label: 'Dashboard', href: '/ghost-control/operations/documents', icon: <Building2 className="w-4 h-4" /> },
      { label: 'All Documents', href: '/ghost-control/operations/documents/all', icon: <FileCheck className="w-4 h-4" /> },
      { label: 'Contracts', href: '/ghost-control/operations/documents/contracts', icon: <ScrollText className="w-4 h-4" /> },
    ],
  },
  {
    label: 'Reports',
    icon: <BarChart3 className="w-4 h-4" />,
    children: [
      { label: 'All Reports', href: '/ghost-control/reports', icon: <Building2 className="w-4 h-4" /> },
      { label: 'Report Builder', href: '/ghost-control/reports/builder', icon: <PenTool className="w-4 h-4" /> },
    ],
  },
];

const posNavItem: NavItem = {
  label: 'Point of Sale',
  icon: <Monitor className="w-4 h-4" />,
  children: [
    { label: 'Terminal', href: '/ghost-control/operations/pos/terminal', icon: <UtensilsCrossed className="w-4 h-4" /> },
    { label: 'Menu & Items', href: '/ghost-control/operations/pos/admin', icon: <ListOrdered className="w-4 h-4" /> },
    { label: 'Orders', href: '/ghost-control/operations/pos/orders', icon: <Receipt className="w-4 h-4" /> },
    { label: 'Stations', href: '/ghost-control/operations/pos/stations', icon: <Printer className="w-4 h-4" /> },
  ],
};

export function ERPSidebar() {
  const pathname = usePathname();
  const [expandedItems, setExpandedItems] = useState<string[]>(['Finance', 'HR & People', 'Inventory', 'CRM & Sales', 'Documents', 'Reports']);
  const [posEnabled, setPosEnabled] = useState(false);

  useEffect(() => {
    fetch('/api/modules')
      .then(r => r.json())
      .then(data => {
        const posModule = data.modules?.find((m: any) => m.moduleId === 'pos');
        if (posModule?.isEnabled) setPosEnabled(true);
      })
      .catch(() => {});
  }, []);

  const toggleExpand = (label: string) => {
    setExpandedItems((prev) =>
      prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]
    );
  };

  return (
    <aside className="fixed left-0 top-16 w-64 h-[calc(100vh-4rem)] bg-brand-bg-elevated border-r border-brand-deep/20 overflow-y-auto">
      <div className="p-4">
        <Link
          href="/ghost-control"
          className="flex items-center gap-2 text-gray-400 hover:text-brand transition-colors mb-4"
        >
          <ArrowLeft className="w-4 h-4" />
          <span className="text-sm">Back to Control Center</span>
        </Link>
        
        <div className="flex items-center gap-2 mb-6">
          <Building2 className="w-6 h-6 text-brand" />
          <h2 className="text-lg font-bold text-white">ERP Operations</h2>
        </div>

        <nav className="space-y-1">
          {(() => {
            const items = [...navItems];
            if (posEnabled) {
              // Insert after CRM & Sales (index 4), before Documents
              const crmIdx = items.findIndex(i => i.label === 'CRM & Sales');
              items.splice(crmIdx + 1, 0, posNavItem);
            }
            return items;
          })().map((item) => (
            <div key={item.label}>
              {item.children ? (
                <>
                  <button
                    onClick={() => toggleExpand(item.label)}
                    className={`w-full flex items-center justify-between px-3 py-2 rounded-lg text-sm transition-colors ${
                      pathname.includes(item.label.toLowerCase().split(' ')[0])
                        ? 'bg-brand-deep/10 text-brand'
                        : 'text-gray-400 hover:bg-white/5 hover:text-white'
                    }`}
                  >
                    <div className="flex items-center gap-3">
                      {item.icon}
                      <span>{item.label}</span>
                    </div>
                    {expandedItems.includes(item.label) ? (
                      <ChevronDown className="w-4 h-4" />
                    ) : (
                      <ChevronRight className="w-4 h-4" />
                    )}
                  </button>
                  {expandedItems.includes(item.label) && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      exit={{ opacity: 0, height: 0 }}
                      className="ml-4 mt-1 space-y-1 border-l border-white/10 pl-3"
                    >
                      {item.children.map((child) => (
                        <Link
                          key={child.href}
                          href={child.href!}
                          className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${
                            pathname === child.href
                              ? 'bg-brand-deep/10 text-brand'
                              : 'text-gray-500 hover:bg-white/5 hover:text-gray-300'
                          }`}
                        >
                          {child.icon}
                          <span>{child.label}</span>
                        </Link>
                      ))}
                    </motion.div>
                  )}
                </>
              ) : (
                <Link
                  href={item.href!}
                  className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors ${
                    pathname === item.href
                      ? 'bg-brand-deep/10 text-brand'
                      : 'text-gray-400 hover:bg-white/5 hover:text-white'
                  }`}
                >
                  {item.icon}
                  <span>{item.label}</span>
                </Link>
              )}
            </div>
          ))}
        </nav>

        {/* Configuration Link */}
        <Link
          href="/ghost-control/configuration"
          className={`flex items-center gap-3 px-3 py-2.5 mt-6 rounded-lg text-sm font-medium transition-colors border ${
            pathname === '/ghost-control/configuration'
              ? 'bg-brand-deep/10 text-brand border-brand-deep/30'
              : 'text-gray-400 hover:bg-white/5 hover:text-white border-white/10 hover:border-brand-deep/20'
          }`}
        >
          <Settings className="w-4 h-4" />
          <span>Configuration</span>
        </Link>

        <div className="mt-6 p-4 bg-gradient-to-br from-brand-deep/10 to-brand-secondary/10 rounded-lg border border-brand-deep/20">
          <div className="flex items-center gap-2 mb-2">
            <Brain className="w-5 h-5 text-brand" />
            <span className="text-sm font-medium text-white">Ghost Learning</span>
          </div>
          <p className="text-xs text-gray-400">
            The Ghost is analyzing your operations patterns to suggest automations.
          </p>
        </div>
      </div>
    </aside>
  );
}
