import React, { useState } from "react";
import { NavLink } from "react-router-dom";
import {
  House,
  ChartLine,
  Buildings,
  Users,
  Receipt,
  CurrencyDollar,
  ShieldCheck,
  Gear,
  SignOut,
  CaretLeft,
  CaretRight,
  Briefcase,
  TrendUp,
  FileText,
  Wallet,
  ChartPieSlice,
  Clock,
} from "@phosphor-icons/react";
import Logo from "../Logo";
import axios from "axios";

export default function Sidebar({ user }) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const isSuperAdmin = user?.roles?.some((r) => r.name === "Super Admin");
  const isCompanyAdmin = user?.roles?.some((r) => r.name === "Company Admin");

  const handleLogout = async () => {
    try {
      await axios.post("/api/logout");
      window.location.href = "/login";
    } catch (error) {
      console.error("Logout error:", error);
    }
  };

  const navItems = [
    {
      name: "Dashboard",
      icon: House,
      path: "/dashboard",
      show: true,
    },
    {
      name: "Super Admin Dashboard",
      icon: ChartPieSlice,
      path: "/super-admin-dashboard",
      show: isSuperAdmin,
    },
    {
      name: "Super Admin Bank Accounts",
      icon: Wallet,
      path: "/super-admin-bank-accounts",
      show: isSuperAdmin,
    },
    {
      name: "Company Dashboard",
      icon: ChartLine,
      path: "/company-admin-dashboard",
      show: isCompanyAdmin,
    },
    {
      name: "Companies",
      icon: Buildings,
      path: "/companies",
      show: isSuperAdmin,
    },
    {
      name: "Employees",
      icon: Users,
      path: "/employees",
      show: isSuperAdmin || isCompanyAdmin,
    },
    {
      name: "Loan Requests",
      icon: CurrencyDollar,
      path: "/loans",
      show: isSuperAdmin || isCompanyAdmin,
    },
    {
      name: "Profit Allocation",
      icon: TrendUp,
      path: "/profit-sweeps",
      show: isSuperAdmin || isCompanyAdmin,
    },
    {
      name: "Expenses",
      icon: Receipt,
      path: "/expenses",
      show: isSuperAdmin || isCompanyAdmin,
    },
    {
      name: "Assets",
      icon: Bank,
      path: "/assets",
      show: isSuperAdmin || isCompanyAdmin,
    },
    {
      name: "Company Users",
      icon: Users,
      path: "/company-users",
      show: isSuperAdmin || isCompanyAdmin,
    },
    {
      name: "Invoices",
      icon: FileText,
      path: "/invoices",
      show: isSuperAdmin,
    },
    {
      name: "Treasury",
      icon: Wallet,
      path: "/treasury",
      show: isSuperAdmin,
    },
    {
      name: "Role Management",
      icon: ShieldCheck,
      path: "/roles",
      show: isSuperAdmin || user?.permissions?.includes("roles.view"),
    },
    {
      name: "Audit Logs",
      icon: Clock,
      path: "/audit-logs",
      show: isSuperAdmin || user?.permissions?.includes("audit.view"),
    },
    {
      name: "Settings",
      icon: Gear,
      path: "/settings",
      show: true,
    },
  ];

  return (
    <aside
      className={`
                fixed left-0 top-0 h-screen bg-gradient-to-b from-gray-900 to-gray-800
                text-white transition-all duration-300 ease-in-out z-50 shadow-2xl
                ${isCollapsed ? "w-20" : "w-64"}
            `}
    >
      {/* Header */}
      <div
        className={`h-16 flex items-center border-b border-primary-700 px-3 ${isCollapsed ? "justify-center" : "justify-between"}`}
      >
        <div className="flex items-center gap-2 overflow-hidden">
          <div
            className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0"
            style={{ background: "linear-gradient(135deg,#5D4037,#6D4C41)" }}
          >
            <span className="text-white font-black text-xs tracking-tight">
              SMG
            </span>
          </div>
          {!isCollapsed && (
            <div className="leading-tight">
              <p className="font-bold text-white text-sm leading-none">
                Sarkin Mota Group
              </p>
              <p className="text-gray-400 text-xs">Group Management</p>
            </div>
          )}
        </div>
        <button
          onClick={() => setIsCollapsed(!isCollapsed)}
          className={`p-1.5 rounded-lg hover:bg-gray-700 transition-colors flex-shrink-0 ${isCollapsed ? "hidden" : ""}`}
        >
          <CaretLeft size={18} weight="bold" />
        </button>
        {isCollapsed && (
          <button
            onClick={() => setIsCollapsed(false)}
            className="absolute -right-3 top-5 bg-gray-800 border border-gray-600 rounded-full p-1 hover:bg-gray-700 transition-colors z-10"
          >
            <CaretRight size={12} weight="bold" />
          </button>
        )}
      </div>

      {/* User Info */}
      {!isCollapsed && (
        <div className="px-4 py-4 border-b border-gray-700">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-gradient-to-br from-primary-500 to-purple-600 flex items-center justify-center font-bold text-white">
              {user?.name?.charAt(0).toUpperCase()}
            </div>
            <div className="flex-1 min-w-0">
              <p className="font-semibold truncate text-sm">{user?.name}</p>
              <p className="text-xs text-gray-400 truncate">
                {user?.company?.name || "Sarkin Mota Group"}
              </p>
            </div>
          </div>
          {user?.roles?.map((role, idx) => (
            <span
              key={idx}
              className="inline-block mt-2 px-2 py-1 bg-primary-600 bg-opacity-30 text-primary-300 text-xs rounded-md"
            >
              {role.name}
            </span>
          ))}
        </div>
      )}

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto py-4">
        <div className="space-y-1 px-2">
          {navItems
            .filter((item) => item.show)
            .map((item) => (
              <NavLink
                key={item.path}
                to={item.path}
                className={({ isActive }) =>
                  `flex items-center gap-3 px-3 py-3 rounded-lg transition-all duration-200 group
                                ${
                                  isActive
                                    ? "bg-gradient-to-r from-primary-600 to-primary-500 text-white shadow-lg"
                                    : "text-gray-300 hover:bg-gray-700 hover:text-white"
                                }
                                ${isCollapsed ? "justify-center" : ""}`
                }
                title={isCollapsed ? item.name : ""}
              >
                <item.icon
                  size={22}
                  weight="duotone"
                  className="flex-shrink-0"
                />
                {!isCollapsed && (
                  <span className="font-medium text-sm">{item.name}</span>
                )}
              </NavLink>
            ))}
        </div>
      </nav>

      {/* Logout */}
      <div className="border-t border-gray-700 p-2">
        <button
          onClick={handleLogout}
          className={`
                        w-full flex items-center gap-3 px-3 py-3 rounded-lg
                        text-gray-300 hover:bg-red-600 hover:text-white
                        transition-all duration-200
                        ${isCollapsed ? "justify-center" : ""}
                    `}
          title={isCollapsed ? "Logout" : ""}
        >
          <SignOut size={22} weight="bold" className="flex-shrink-0" />
          {!isCollapsed && <span className="font-medium text-sm">Logout</span>}
        </button>
      </div>
    </aside>
  );
}
