import React, { useState } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { motion } from 'framer-motion';
import {
  FileText,
  Plus,
  Warehouse,
  Factory,
  DollarSign,
  Droplets,
  LogOut,
  Home,
  ChevronRight,
  Building2,
  Menu,
  X
} from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { useResponsive } from '../../hooks/useResponsive';
import { STORAGE_KEYS } from '../../config/app';

interface NavItem {
  id: string;
  icon: React.ElementType;
  label: string;
  path: string;
}

const navItems: NavItem[] = [
  { id: 'home', icon: Home, label: '首页', path: '/purchaser' },
  { id: 'plans', icon: FileText, label: '计划总览', path: '/purchaser/plans' },
  { id: 'new', icon: Plus, label: '新建纺织计划', path: '/purchaser/plans/new' },
  { id: 'washing', icon: Droplets, label: '新建水洗计划', path: '/purchaser/washing-plans/new' },
  { id: 'warehouse', icon: Warehouse, label: '产品信息', path: '/purchaser/warehouse' },
  { id: 'finished', icon: Building2, label: '水洗仓库', path: '/purchaser/finished-warehouse' },
  { id: 'factories', icon: Factory, label: '工厂管理', path: '/purchaser/factories' },
  { id: 'accounts-payable', icon: DollarSign, label: '应付账款', path: '/purchaser/accounts-payable' }
];

export function PurchaserLayout() {
  const navigate = useNavigate();
  const location = useLocation();
  const { auth, logout } = useAuth();
  const { isMobile } = useResponsive();

  // 从 localStorage 读取侧边栏状态，默认展开
  const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
    const saved = localStorage.getItem(STORAGE_KEYS.purchaserSidebarCollapsed);
    return saved ? JSON.parse(saved) : false;
  });
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  // 保存侧边栏状态到 localStorage
  const toggleSidebar = () => {
    const newState = !sidebarCollapsed;
    setSidebarCollapsed(newState);
    localStorage.setItem(STORAGE_KEYS.purchaserSidebarCollapsed, JSON.stringify(newState));
  };

  const isActive = (path: string) => {
    const currentPath = location.pathname;

    // 首页精确匹配
    if (path === '/purchaser') {
      return currentPath === '/purchaser';
    }

    // 精确匹配当前路径
    if (currentPath === path) return true;

    // 对于 /purchaser/plans 路径，不应该匹配 /purchaser/plans/new
    // 只有当当前路径就是 /purchaser/plans 或者以 /purchaser/plans/ 开头但后面没有其他路径段时才匹配
    if (path === '/purchaser/plans') {
      return currentPath === '/purchaser/plans';
    }

    // 对于其他路径，匹配子路径
    if (currentPath.startsWith(path + '/')) return true;

    return false;
  };

  const handleLogout = async () => {
    await logout();
    navigate('/login');
  };

  return (
    <div className="min-h-screen bg-slate-50">
      {/* 桌面端侧边栏 - 固定不动，无入场动画 */}
      {!isMobile && (
        <aside
          className={`fixed left-0 top-0 h-screen bg-gradient-to-b from-slate-900 via-slate-800 to-slate-900 text-white z-50 flex flex-col ${
            sidebarCollapsed ? 'w-20' : 'w-64'
          }`}
        >
          {/* Logo区域 */}
          <div className="h-16 flex items-center px-4 border-b border-slate-700/50">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-amber-400 to-orange-500 flex items-center justify-center shadow-lg">
                <Building2 className="w-6 h-6 text-white" />
              </div>
              {!sidebarCollapsed && (
                <div>
                  <h1 className="font-bold text-lg leading-tight">采购商工作台</h1>
                  <p className="text-xs text-slate-400">{auth.company?.name || '未登录'}</p>
                </div>
              )}
            </div>
          </div>

          {/* 导航菜单 */}
          <nav className="flex-1 py-4 px-3 overflow-y-auto">
            <div className="space-y-1">
              {navItems.map((item) => {
                const active = isActive(item.path);
                const Icon = item.icon;

                return (
                  <button
                    key={item.id}
                    onClick={() => navigate(item.path)}
                    className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors duration-200 group ${
                      active
                        ? 'bg-gradient-to-r from-amber-500/20 to-orange-500/20 text-amber-400 border border-amber-500/30'
                        : 'text-slate-300 hover:bg-slate-700/50 hover:text-white'
                    }`}
                  >
                    <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                      active ? 'bg-amber-500/20' : 'bg-slate-700/50 group-hover:bg-slate-600'
                    }`}>
                      <Icon className="w-5 h-5" />
                    </div>
                    {!sidebarCollapsed && (
                      <div className="flex-1 text-left">
                        <div className="font-medium text-sm">{item.label}</div>
                      </div>
                    )}
                    {!sidebarCollapsed && active && (
                      <ChevronRight className="w-4 h-4 text-amber-400" />
                    )}
                  </button>
                );
              })}
            </div>
          </nav>

          {/* 底部操作区 */}
          <div className="p-3 border-t border-slate-700/50 space-y-2">
            <button
              onClick={toggleSidebar}
              className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-slate-400 hover:bg-slate-700/50 hover:text-white transition-colors"
            >
              <div className={`w-8 h-8 rounded-lg bg-slate-700/50 flex items-center justify-center ${
                sidebarCollapsed ? 'rotate-180' : ''
              }`}>
                <ChevronRight className="w-4 h-4" />
              </div>
              {!sidebarCollapsed && <span className="text-sm">收起菜单</span>}
            </button>

            <motion.button
              onClick={handleLogout}
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              className="w-full flex items-center gap-3 px-3 py-3 rounded-xl text-red-400 hover:bg-red-500/10 transition-colors"
            >
              <div className="w-10 h-10 rounded-lg bg-red-500/10 flex items-center justify-center">
                <LogOut className="w-5 h-5" />
              </div>
              {!sidebarCollapsed && <span className="font-medium text-sm">退出登录</span>}
            </motion.button>
          </div>
        </aside>
      )}

      {/* 主内容区 - 移动端无侧边栏，桌面端有侧边栏 */}
      <main className={`${
        !isMobile && (sidebarCollapsed ? 'ml-20' : 'ml-64')
      }`}>
        <Outlet />
      </main>
    </div>
  );
}
