// src/components/layout/header.tsx
"use client";

import { useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import { useAdminStore } from "@/store/adminStore";
import Link from "next/link";
import { useSkinStore } from "@/store/skinStore";
import { useAdminMobileNav } from "@/store/adminMobileNavStore";
import { Menu } from "lucide-react";

// ─── Theme Toggle ─────────────────────────────────────────────────────────────

function ThemeToggle() {
  const { currentMode, toggleMode } = useSkinStore();
  const isDarkMode = currentMode === "dark";

  return (
    <button
      onClick={toggleMode}
      aria-label="Toggle dark mode"
      className="flex items-center justify-center w-10 h-10 sm:w-9 sm:h-9 rounded-xl transition-all duration-200"
      style={{
        background: "var(--color-surface-alt)",
        border: "1px solid var(--color-border)",
        color: "var(--color-text-secondary)",
      }}
      title={isDarkMode ? "Light mode" : "Dark mode"}
      onMouseEnter={(e) => (e.currentTarget.style.borderColor = "var(--color-cta)")}
      onMouseLeave={(e) => (e.currentTarget.style.borderColor = "var(--color-border)")}
    >
      {isDarkMode ? (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <circle cx="12" cy="12" r="5" />
          <line x1="12" y1="1" x2="12" y2="3" />
          <line x1="12" y1="21" x2="12" y2="23" />
          <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
          <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
          <line x1="1" y1="12" x2="3" y2="12" />
          <line x1="21" y1="12" x2="23" y2="12" />
          <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
          <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
        </svg>
      ) : (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
        </svg>
      )}
    </button>
  );
}

// ─── User Menu ────────────────────────────────────────────────────────────────

function UserMenu() {
  const router = useRouter();
  const { user, clearUser } = useAdminStore();
  const [open, setOpen] = useState(false);

  async function handleLogout() {
    try {
      await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
    } catch (err) {
      console.error("Logout error:", err);
    } finally {
      // Clear user store
      clearUser();

      router.push("/admin/login");
    }
  }

  const firstName = user?.firstName || "";
  const lastName = user?.lastName || "";
  const email = user?.email || "";
  
  const initials = firstName && lastName
    ? `${firstName[0]}${lastName[0]}`.toUpperCase()
    : firstName
    ? firstName[0].toUpperCase()
    : "U";

  const displayName = firstName && lastName 
    ? `${firstName} ${lastName}`
    : firstName || email?.split("@")[0] || "User";

  // Don't show menu if no user
  if (!user) {
    return null;
  }

  return (
    <div className="relative">
      <button
        onClick={() => setOpen(!open)}
        aria-label="Account menu"
        className="flex items-center gap-2.5 px-2 sm:px-3 py-2 rounded-xl transition-all duration-200"
        style={{
          background: "var(--color-surface-alt)",
          border: "1px solid var(--color-border)",
        }}
        onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--color-cta)"}
        onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--color-border)"}
      >
        <div
          className="w-7 h-7 rounded-lg flex items-center justify-center text-xs font-bold text-white shrink-0"
          style={{ background: "var(--color-cta)" }}
        >
          {initials}
        </div>

        <div className="hidden sm:flex flex-col items-start">
          <span className="text-xs font-semibold leading-tight" style={{ color: "var(--color-text)" }}>
            {displayName}
          </span>
          <span className="text-xs leading-tight" style={{ color: "var(--color-text-muted)" }}>
            {email}
          </span>
        </div>

        <svg 
          width="14" 
          height="14" 
          viewBox="0 0 24 24" 
          fill="none" 
          stroke="currentColor" 
          strokeWidth="2"
          className="hidden sm:block transition-transform duration-200"
          style={{ 
            color: "var(--color-text-muted)",
            transform: open ? "rotate(180deg)" : "rotate(0deg)"
          }}
        >
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>

      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />

          <div
            className="absolute right-0 top-full mt-2 w-52 max-w-[calc(100vw-1.5rem)] rounded-2xl z-50 overflow-hidden"
            style={{
              background: "var(--color-surface)",
              border: "1px solid var(--color-border)",
              boxShadow: "var(--shadow-card-lg)",
            }}
          >
            <div className="p-2 flex flex-col gap-0.5">
              <button
                onClick={() => {
                  setOpen(false);
                  router.push("/admin/dashboard/settings");
                }}
                className="flex items-center gap-2.5 w-full px-3 py-2.5 rounded-xl text-sm text-left transition-colors"
                style={{ color: "var(--color-text-secondary)" }}
                onMouseEnter={(e) => e.currentTarget.style.background = "var(--color-surface-alt)"}
                onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <circle cx="12" cy="12" r="3"/>
                  <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
                </svg>
                Settings
              </button>

              <div style={{ height: "1px", background: "var(--color-border)", margin: "4px 0" }} />

              <button
                onClick={() => {
                  setOpen(false);
                  handleLogout();
                }}
                className="flex items-center gap-2.5 w-full px-3 py-2.5 rounded-xl text-sm text-left transition-colors"
                style={{ color: "var(--color-danger)" }}
                onMouseEnter={(e) => { 
                  e.currentTarget.style.background = "rgba(239,68,68,0.1)"; 
                }}
                onMouseLeave={(e) => { 
                  e.currentTarget.style.background = "transparent"; 
                }}
              >
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
                  <polyline points="16 17 21 12 16 7"/>
                  <line x1="21" y1="12" x2="9" y2="12"/>
                </svg>
                Logout
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

// ─── Breadcrumb (Left Side) ───────────────────────────────────────────────────

function Breadcrumb() {
  const pathname = usePathname();
  
  // Base path - jahan se breadcrumb start ho ga
  const BASE_PATH = '/admin/dashboard';
  
  const getBreadcrumbName = (segment: string): string => {
    // Remove query parameters if any
    const cleanSegment = segment.split('?')[0];
    
    // Check if it's a UUID
    const isUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(cleanSegment);
    if (isUUID) {
      return 'Details';
    }
    
    // Check if it's a number (ID)
    if (/^\d+$/.test(cleanSegment)) {
      return `#${cleanSegment}`;
    }
    
    // Special cases
    const specialCases: Record<string, string> = {
      'admin': 'Admin',
      'dashboard': 'Dashboard',
      'employees': 'Employees',
      'new': 'Add New',
      'edit': 'Edit',
      'view': 'View',
      'settings': 'Settings',
      'profile': 'Profile',
      'reports': 'Reports',
      'departments': 'Departments',
      'designations': 'Designations',
      'locations': 'Locations',
      'roles': 'Roles',
      'permissions': 'Permissions',
      'audit': 'Audit Logs',
      'documents': 'Documents',
      'leave': 'Leave Management',
      'payroll': 'Payroll',
      'recruitment': 'Recruitment',
      'performance': 'Performance',
      'training': 'Training',
      'assets': 'Assets',
      'tasks': 'Tasks',
      'projects': 'Projects',
      'clients': 'Clients',
      'vendors': 'Vendors',
      'contracts': 'Contracts',
      'invoices': 'Invoices',
      'overrides': 'Overrides',
      'change-password': 'Change Password',
      'bulk': 'Bulk Actions',
      'import': 'Import',
      'export': 'Export',
      'trash': 'Trash',
    };
    
    if (specialCases[cleanSegment]) {
      return specialCases[cleanSegment];
    }
    
    // Convert kebab-case to Title Case
    return cleanSegment
      .split('-')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  };

  // Get pathname without base path
  const getRelativePath = (path: string): string => {
    if (path === BASE_PATH) return '';
    if (path.startsWith(BASE_PATH)) {
      return path.substring(BASE_PATH.length);
    }
    return path;
  };

  // Get all segments after base path
  const relativePath = getRelativePath(pathname);
  const segments = relativePath.split('/').filter(Boolean);
  
  // If on dashboard or empty path
  if (pathname === BASE_PATH || pathname === '/admin/dashboard' || segments.length === 0) {
    return (
      <div className="flex items-center gap-2">
        <h1 className="text-lg sm:text-xl font-semibold truncate" style={{ color: 'var(--color-text)' }}>
          Dashboard
        </h1>
      </div>
    );
  }

  // Build breadcrumb items
  const breadcrumbItems = segments.map((segment, index) => {
    const fullPath = BASE_PATH + '/' + segments.slice(0, index + 1).join('/');
    const isLast = index === segments.length - 1;
    const label = getBreadcrumbName(segment);
    
    return {
      label,
      path: fullPath,
      isLast,
    };
  });

  return (
    <div className="flex items-center gap-2 min-w-0">
      {/* Dashboard Link - Always points to /admin/dashboard */}
      <Link
        href={BASE_PATH}
        className="hidden sm:inline text-sm hover:opacity-70 transition-opacity shrink-0"
        style={{ color: 'var(--color-text-muted)' }}
      >
        Dashboard
      </Link>
      
      {/* Breadcrumb Separator */}
      <span className="hidden sm:inline-flex">
        <ChevronRight />
      </span>
      
      {/* Breadcrumb Items */}
      {breadcrumbItems.map((item) => (
        <div key={item.path} className={`items-center gap-2 min-w-0 ${item.isLast ? "flex" : "hidden sm:flex"}`}>
          {item.isLast ? (
            <span 
              className="text-base sm:text-sm font-semibold sm:font-medium truncate"
              style={{ color: 'var(--color-text-secondary)' }}
            >
              {item.label}
            </span>
          ) : (
            <>
              <Link
                href={item.path}
                className="text-sm hover:opacity-70 transition-opacity"
                style={{ color: 'var(--color-text-muted)' }}
              >
                {item.label}
              </Link>
              <ChevronRight />
            </>
          )}
        </div>
      ))}
    </div>
  );
}

// Separator component
function ChevronRight() {
  return (
    <svg 
      width="14" 
      height="14" 
      viewBox="0 0 24 24" 
      fill="none" 
      stroke="currentColor" 
      strokeWidth="2"
      style={{ color: 'var(--color-text-muted)' }}
      className="shrink-0"
    >
      <polyline points="9 18 15 12 9 6"/>
    </svg>
  );
}

// ─── Main Header ──────────────────────────────────────────────────────────────

export default function Header() {
  const toggleMobileNav = useAdminMobileNav((s) => s.toggle);

  return (
    <header
      className="flex items-center justify-between gap-2 h-14 sm:h-16 px-3 sm:px-6 shrink-0"
      style={{
        background: "var(--color-surface)",
        borderBottom: "1px solid var(--color-border)",
      }}
    >
      {/* Left Side - menu button (below lg) + Breadcrumb */}
      <div className="flex items-center gap-2 min-w-0 flex-1">
        <button
          onClick={toggleMobileNav}
          aria-label="Open menu"
          className="lg:hidden flex items-center justify-center w-10 h-10 rounded-xl shrink-0"
          style={{
            background: "var(--color-surface-alt)",
            border: "1px solid var(--color-border)",
            color: "var(--color-text-secondary)",
          }}
        >
          <Menu size={20} />
        </button>
        <div className="min-w-0">
          <Breadcrumb />
        </div>
      </div>

      {/* Right Side - Actions (Theme Toggle + User Menu) */}
      <div className="flex items-center gap-2 sm:gap-2.5 shrink-0">
        <ThemeToggle />
        <UserMenu />
      </div>
    </header>
  );
}
