import React, { useState } from "react";
import SarkinMotaAI from "./SarkinMotaAI";
import { Outlet, Link, useLocation, useNavigate } from "react-router-dom";
import {
  House,
  Buildings,
  Users,
  Briefcase,
  SignOut,
  ChartLine,
  ChartPieSlice,
  CurrencyDollar,
  TrendUp,
  Receipt,
  FileText,
  Wallet,
  ShieldCheck,
  Gear,
  CaretLeft,
  CaretRight,
  X,
  UserCircle,
  Handshake,
  Cube,
  CalendarBlank,
  Sparkle,
} from "@phosphor-icons/react";
import useAuthStore from "../store/authStore";
import toast from "react-hot-toast";
import Logo from "./Logo";

export default function Layout() {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [aiOpen, setAiOpen] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();
  const { user, logout, isSuperAdmin } = useAuthStore();

  const handleLogout = async () => {
    await logout();
    toast.success("Logged out successfully");
    navigate("/login");
  };

  const navigation = [
    { name: "Dashboard", href: "/dashboard", icon: House, show: true },
    {
      name: "Super Admin Dashboard",
      href: "/super-admin-dashboard",
      icon: ChartPieSlice,
      show: isSuperAdmin(),
    },
    {
      name: "Super Admin Bank Accounts",
      href: "/super-admin-bank-accounts",
      icon: Wallet,
      show: isSuperAdmin(),
    },
    {
      name: "Company Analytics",
      href: "/company-dashboard",
      icon: ChartLine,
      show: user?.company_id,
    },
    {
      name: "Companies",
      href: "/companies",
      icon: Buildings,
      show: isSuperAdmin(),
    },
    { name: "Employees", href: "/employees", icon: Users, show: true },
    { name: "Departments", href: "/departments", icon: Briefcase, show: true },
    { name: "Loan Requests", href: "/loans", icon: CurrencyDollar, show: true },
    {
      name: "Profit Allocation",
      href: "/profit-sweeps",
      icon: TrendUp,
      show: true,
    },
    { name: "Assets", href: "/assets", icon: Cube, show: true },
    { name: "Invoices", href: "/invoices", icon: FileText, show: true },
    {
      name: "Bank Accounts",
      href: "/bank-accounts",
      icon: Wallet,
      show: user?.company_id,
    },
    {
      name: "Treasury",
      href: "/treasury",
      icon: CurrencyDollar,
      show: isSuperAdmin(),
    },
    {
      name: "Investors & Partners",
      href: "/investors",
      icon: Handshake,
      show: isSuperAdmin(),
    },
    {
      name: "Role Management",
      href: "/roles",
      icon: ShieldCheck,
      show: isSuperAdmin(),
    },
    { name: "Settings", href: "/settings", icon: Gear, show: true },
  ].filter((item) => item.show);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Mobile Sidebar */}
      <div
        className={`fixed inset-0 z-40 lg:hidden ${sidebarOpen ? "" : "pointer-events-none"}`}
      >
        <div
          className={`fixed inset-0 bg-gray-900 transition-opacity ${sidebarOpen ? "opacity-75" : "opacity-0"}`}
          onClick={() => setSidebarOpen(false)}
        />

        <div
          className={`fixed inset-y-0 left-0 flex flex-col w-72 transform transition-transform ${sidebarOpen ? "translate-x-0" : "-translate-x-full"}`}
          style={{
            background:
              "linear-gradient(180deg, #3E2723 0%, #5D4037 50%, #6D4C41 100%)",
          }}
        >
          <div className="flex items-center justify-between h-[72px] px-4 border-b border-white/10">
            <div className="flex items-center gap-3">
              <div
                className="w-9 h-9 rounded-xl flex items-center justify-center"
                style={{
                  background: "linear-gradient(135deg, #6D4C41, #8D6E63)",
                }}
              >
                <Logo className="h-5 w-5" />
              </div>
              <div>
                <p className="font-extrabold text-white text-base leading-tight">
                  SARKIN MOTA
                </p>
                <p
                  className="text-[10px] font-semibold tracking-widest uppercase"
                  style={{ color: "#C6A862" }}
                >
                  GROUP
                </p>
              </div>
            </div>
            <button
              onClick={() => setSidebarOpen(false)}
              className="p-1.5 rounded-lg text-white/50 hover:text-white hover:bg-white/10"
            >
              <X size={20} weight="bold" />
            </button>
          </div>

          <div className="px-4 py-3 border-b border-white/10">
            <div className="flex items-center gap-3">
              <div
                className="w-9 h-9 rounded-full flex items-center justify-center font-bold text-white text-sm"
                style={{
                  background: "linear-gradient(135deg, #5D4037, #A1887F)",
                }}
              >
                {user?.name?.charAt(0).toUpperCase()}
              </div>
              <div>
                <p className="font-semibold text-white text-sm">{user?.name}</p>
                <p className="text-xs" style={{ color: "#C6A862" }}>
                  {user?.company?.name || "Super Admin"}
                </p>
              </div>
            </div>
          </div>

          <nav className="flex-1 px-2 py-3 space-y-0.5 overflow-y-auto">
            {navigation.map((item) => {
              const Icon = item.icon;
              const isActive =
                location.pathname === item.href ||
                location.pathname.startsWith(item.href + "/");
              return (
                <Link
                  key={item.name}
                  to={item.href}
                  onClick={() => setSidebarOpen(false)}
                  className={`flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all text-sm font-medium ${
                    isActive
                      ? "text-white"
                      : "text-white/55 hover:text-white hover:bg-white/10"
                  }`}
                  style={
                    isActive
                      ? {
                          background:
                            "linear-gradient(135deg, #5D4037, #8D6E63)",
                          boxShadow: "0 4px 16px rgba(62,39,35,0.35)",
                        }
                      : {}
                  }
                >
                  <Icon size={20} weight={isActive ? "fill" : "duotone"} />
                  <span>{item.name}</span>
                </Link>
              );
            })}
          </nav>

          <div className="border-t border-white/10 p-2">
            <button
              onClick={handleLogout}
              className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/70 hover:bg-white/10 hover:text-white transition-all text-sm font-medium"
            >
              <SignOut size={20} weight="bold" />
              <span>Logout</span>
            </button>
          </div>
        </div>
      </div>

      {/* Desktop Sidebar - Collapsible */}
      <aside
        className={`hidden lg:fixed lg:inset-y-0 lg:flex lg:flex-col transition-all duration-300 ease-in-out z-50 ${isCollapsed ? "lg:w-[72px]" : "lg:w-72"}`}
        style={{
          background:
            "linear-gradient(180deg, #3E2723 0%, #5D4037 50%, #6D4C41 100%)",
          boxShadow: "4px 0 24px rgba(62,39,35,0.18)",
        }}
      >
        {/* Brand Header — always visible */}
        <div
          className={`flex items-center border-b border-white/10 ${isCollapsed ? "justify-center py-4 px-2 flex-col gap-2" : "justify-between px-4 h-[72px]"}`}
        >
          <div
            className={`flex items-center gap-3 overflow-hidden ${isCollapsed ? "flex-col" : ""}`}
          >
            <div
              className="flex-shrink-0 w-9 h-9 rounded-xl flex items-center justify-center"
              style={{
                background: "linear-gradient(135deg, #6D4C41, #8D6E63)",
              }}
            >
              <Logo className="h-5 w-5" />
            </div>
            {!isCollapsed && (
              <div>
                <p className="font-extrabold text-white text-base leading-tight tracking-tight">
                  SARKIN MOTA
                </p>
                <p
                  className="text-[10px] font-semibold tracking-widest uppercase"
                  style={{ color: "#C6A862" }}
                >
                  GROUP
                </p>
              </div>
            )}
          </div>
          <button
            onClick={() => setIsCollapsed(!isCollapsed)}
            className="flex-shrink-0 p-1.5 rounded-lg text-white/50 hover:text-white hover:bg-white/10 transition-all"
          >
            {isCollapsed ? (
              <CaretRight size={16} weight="bold" />
            ) : (
              <CaretLeft size={16} weight="bold" />
            )}
          </button>
        </div>

        {/* User Info */}
        {!isCollapsed ? (
          <div className="px-4 py-3 border-b border-white/10">
            <div className="flex items-center gap-3">
              <div
                className="w-9 h-9 rounded-full flex-shrink-0 flex items-center justify-center font-bold text-white text-sm"
                style={{
                  background: "linear-gradient(135deg, #5D4037, #A1887F)",
                }}
              >
                {user?.name?.charAt(0).toUpperCase()}
              </div>
              <div className="flex-1 min-w-0">
                <p className="font-semibold text-white text-sm truncate">
                  {user?.name}
                </p>
                <p className="text-xs truncate" style={{ color: "#C6A862" }}>
                  {user?.company?.name || "Super Admin"}
                </p>
              </div>
            </div>
          </div>
        ) : (
          <div className="flex justify-center py-3 border-b border-white/10">
            <div
              className="w-8 h-8 rounded-full flex items-center justify-center font-bold text-white text-xs"
              style={{
                background: "linear-gradient(135deg, #5D4037, #A1887F)",
              }}
            >
              {user?.name?.charAt(0).toUpperCase()}
            </div>
          </div>
        )}

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto py-3">
          <div className={`space-y-0.5 ${isCollapsed ? "px-1" : "px-2"}`}>
            {navigation.map((item) => {
              const Icon = item.icon;
              const isActive =
                location.pathname === item.href ||
                location.pathname.startsWith(item.href + "/");
              return (
                <Link
                  key={item.name}
                  to={item.href}
                  title={isCollapsed ? item.name : undefined}
                  className={`flex items-center gap-3 px-3 py-2.5 rounded-xl transition-all duration-150 group relative
                    ${
                      isActive
                        ? "text-white shadow-lg"
                        : "text-white/55 hover:text-white hover:bg-white/10"
                    }
                    ${isCollapsed ? "justify-center" : ""}`}
                  style={
                    isActive
                      ? {
                          background:
                            "linear-gradient(135deg, #5D4037, #8D6E63)",
                          boxShadow: "0 4px 16px rgba(62,39,35,0.35)",
                        }
                      : {}
                  }
                >
                  <Icon
                    size={20}
                    weight={isActive ? "fill" : "duotone"}
                    className="flex-shrink-0"
                  />
                  {!isCollapsed && (
                    <span className="font-medium text-sm">{item.name}</span>
                  )}
                  {!isCollapsed && isActive && (
                    <span className="ml-auto w-1.5 h-1.5 rounded-full bg-white opacity-80" />
                  )}
                </Link>
              );
            })}
          </div>
        </nav>

        {/* Logout */}
        <div className="border-t border-white/10 p-2">
          <button
            onClick={handleLogout}
            title={isCollapsed ? "Logout" : undefined}
            className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-white/70 hover:bg-white/10 hover:text-white transition-all ${isCollapsed ? "justify-center" : ""}`}
          >
            <SignOut size={20} weight="bold" className="flex-shrink-0" />
            {!isCollapsed && (
              <span className="font-medium text-sm">Logout</span>
            )}
          </button>
        </div>
      </aside>

      {/* Main Content */}
      <div
        className={`transition-all duration-300 min-h-screen ${isCollapsed ? "lg:pl-[72px]" : "lg:pl-72"}`}
        style={{ background: "#FDFAF6" }}
      >
        {/* Top Bar */}
        <div
          className="sticky top-0 z-40 flex h-14 items-center justify-between px-6 glass border-b border-white/60"
          style={{ boxShadow: "0 1px 12px rgba(62,39,35,0.06)" }}
        >
          <button
            type="button"
            className="p-2 rounded-lg text-gray-500 lg:hidden hover:bg-primary-50"
            onClick={() => setSidebarOpen(true)}
          >
            <House size={22} weight="duotone" />
          </button>
          <div className="flex-1" />
          <div className="flex items-center gap-3">
            <button
              onClick={() => setAiOpen(true)}
              className="flex items-center gap-2 px-3 py-1.5 rounded-xl text-white text-xs font-bold shadow-md hover:shadow-lg hover:scale-105 transition-all"
              style={{
                background: "linear-gradient(135deg, #5D4037, #C6A862)",
              }}
            >
              <Sparkle size={14} weight="fill" />
              <span className="hidden sm:inline">Ask Sarkin Mota AI</span>
            </button>
            <div className="text-right hidden sm:block">
              <p className="text-sm font-bold text-gray-900 leading-tight">
                {user?.name}
              </p>
              <p className="text-xs text-gray-400">
                {user?.company?.name || "Super Admin"}
              </p>
            </div>
            <Link
              to="/profile"
              className="w-8 h-8 rounded-full flex items-center justify-center font-bold text-white text-sm hover:scale-105 transition-transform"
              style={{
                background: "linear-gradient(135deg, #5D4037, #A1887F)",
              }}
            >
              {user?.name?.charAt(0).toUpperCase()}
            </Link>
          </div>
        </div>

        <main className="p-6 fade-in">
          <Outlet />
        </main>
      </div>

      <SarkinMotaAI open={aiOpen} onClose={() => setAiOpen(false)} />
    </div>
  );
}
