import { ReactNode } from 'react';
import { router, usePage, Link } from '@inertiajs/react';
import { useQuery } from '@tanstack/react-query';
import { SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar';
import AdminSidebar from '@/components/admin/AdminSidebar';
import AdminCommandPalette from '@/components/admin/AdminCommandPalette';
import AdminQuickActions, { useRecentPages } from '@/components/admin/AdminQuickActions';
import NotificationBell from '@/components/admin/NotificationBell';
import { AdminThemeProvider, useAdminTheme } from '@/contexts/AdminThemeContext';
import { RolePreviewProvider, useRolePreview, AppRole } from '@/contexts/RolePreviewContext';
import { useAuth } from '@/hooks/useAuth';
import { Sun, Moon, Search, ChevronRight, LayoutDashboard, Eye, EyeOff, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel,
  DropdownMenuSeparator, DropdownMenuTrigger, DropdownMenuSub, DropdownMenuSubTrigger,
  DropdownMenuSubContent,
} from '@/components/ui/dropdown-menu';

const breadcrumbMap: Record<string, string> = {
  '': 'Dashboard',
  orders: 'Bookings',
  calendar: 'Calendar',
  trainers: 'Trainers',
  companies: 'Companies',
  availability: 'Availability',
  courses: 'Courses',
  'course-assignments': 'Assignments',
  venues: 'Locations',
  'e-learning': 'E-Learning',
  accounts: 'User Accounts',
  'user-roles': 'User Roles',
  'discount-codes': 'Discounts',
  sops: 'SOPs',
  'locktel-cms': 'Locktel CMS',
  'audit-log': 'Audit Log',
  'email-logs': 'Email Logs',
  prerequisites: 'Prerequisites',
  waitlist: 'Waitlist',
  certificates: 'Certificates',
  revenue: 'Revenue',
  'ar-assist': 'AR Assist',
  services: 'Services',
  'location-overrides': 'Location Overrides',
  'date-changes': 'Date Changes',
};

const Breadcrumbs = () => {
  const { url } = usePage();
  const path = url.split('?')[0];
  const segments = path.replace('/admin', '').split('/').filter(Boolean);

  if (segments.length === 0) return null;

  return (
    <nav className="flex items-center gap-1 text-xs text-muted-foreground">
      <Link href="/admin" className="hover:text-foreground transition-colors flex items-center gap-1">
        <LayoutDashboard className="h-3 w-3" />
        Dashboard
      </Link>
      {segments.map((seg, i) => {
        const segPath = '/admin/' + segments.slice(0, i + 1).join('/');
        const label = breadcrumbMap[seg] || seg.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
        const isLast = i === segments.length - 1;
        return (
          <span key={segPath} className="flex items-center gap-1">
            <ChevronRight className="h-3 w-3" />
            {isLast ? (
              <span className="text-foreground font-medium">{label}</span>
            ) : (
              <Link href={segPath} className="hover:text-foreground transition-colors">
                {label}
              </Link>
            )}
          </span>
        );
      })}
    </nav>
  );
};

const ROLE_LABELS: Record<string, string> = {
  company_manager: 'Company Manager',
  company_trainer: 'Company Trainer',
  delegate: 'Delegate',
};

const PORTAL_ROUTES: Record<string, string> = {
  company_manager: '/admin',
  company_trainer: '/admin',
  delegate: '/admin',
};

const RolePreviewBanner = () => {
  const { preview, stopPreview } = useRolePreview();

  if (!preview.active || !preview.role) return null;

  const portalRoute = PORTAL_ROUTES[preview.role];

  return (
    <div className="bg-amber-500 text-black px-4 py-1.5 flex items-center justify-between text-sm font-medium">
      <div className="flex items-center gap-2">
        <Eye className="h-4 w-4" />
        <span>
          Previewing as <strong>{ROLE_LABELS[preview.role] || preview.role}</strong>
          {preview.companyName && <> — {preview.companyName}</>}
          {preview.previewEmail && <> — {preview.previewEmail}</>}
        </span>
        {portalRoute && preview.role !== 'company_trainer' && (
          <Button
            variant="outline"
            size="sm"
            className="h-6 text-xs bg-transparent border-black/30 hover:bg-black/10 text-black ml-2"
            onClick={() => router.visit(portalRoute)}
          >
            Open Portal View →
          </Button>
        )}
      </div>
      <Button
        variant="ghost"
        size="sm"
        className="h-6 text-xs gap-1 text-black hover:bg-black/10"
        onClick={stopPreview}
      >
        <X className="h-3 w-3" /> Exit Preview
      </Button>
    </div>
  );
};

type PreviewCompany = { id: string; name: string; company_type: string };
type PreviewDelegate = { email: string; first_name: string; last_name: string; company_id: string | null };

const PreviewDropdown = () => {
  const { isReallySysLevel } = useAuth();
  const { preview, startPreview, stopPreview } = useRolePreview();

  const { data: companies } = useQuery({
    queryKey: ['preview-companies'],
    queryFn: async (): Promise<PreviewCompany[]> => {
      const res = await fetch('/api/admin/preview/companies');
      if (!res.ok) return [];
      return res.json();
    },
    enabled: isReallySysLevel(),
  });

  const { data: delegates } = useQuery({
    queryKey: ['preview-delegates'],
    queryFn: async (): Promise<PreviewDelegate[]> => {
      const res = await fetch('/api/admin/preview/delegates');
      if (!res.ok) return [];
      return res.json();
    },
    enabled: isReallySysLevel(),
  });

  const purchasingCompanies = companies?.filter(
    (c) => c.company_type === 'customer_company' || c.company_type === 'hybrid',
  ) || [];
  const trainingCompanies = companies?.filter(
    (c) => c.company_type === 'training_company' || c.company_type === 'hybrid',
  ) || [];

  if (!isReallySysLevel()) return null;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button
          variant={preview.active ? 'default' : 'ghost'}
          size="icon"
          className={`h-8 w-8 ${preview.active ? 'bg-amber-500 hover:bg-amber-600 text-black' : 'text-muted-foreground hover:text-foreground'}`}
          title="Preview as another role"
        >
          {preview.active ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-56">
        <DropdownMenuLabel className="text-xs">Preview As</DropdownMenuLabel>
        <DropdownMenuSeparator />

        <DropdownMenuSub>
          <DropdownMenuSubTrigger className="text-sm">🏢 Company Manager</DropdownMenuSubTrigger>
          <DropdownMenuSubContent className="w-48 max-h-64 overflow-y-auto">
            {purchasingCompanies.map((c) => (
              <DropdownMenuItem
                key={c.id}
                className="text-sm"
                onClick={() => startPreview('company_manager' as AppRole, c.id, c.name)}
              >
                {c.name}
              </DropdownMenuItem>
            ))}
            {!purchasingCompanies.length && (
              <DropdownMenuItem disabled className="text-xs text-muted-foreground">
                No purchasing companies
              </DropdownMenuItem>
            )}
          </DropdownMenuSubContent>
        </DropdownMenuSub>

        <DropdownMenuSub>
          <DropdownMenuSubTrigger className="text-sm">👷 Company Trainer</DropdownMenuSubTrigger>
          <DropdownMenuSubContent className="w-48 max-h-64 overflow-y-auto">
            {trainingCompanies.map((c) => (
              <DropdownMenuItem
                key={c.id}
                className="text-sm"
                onClick={() => startPreview('company_trainer' as AppRole, c.id, c.name)}
              >
                {c.name}
              </DropdownMenuItem>
            ))}
            {!trainingCompanies.length && (
              <DropdownMenuItem disabled className="text-xs text-muted-foreground">
                No training companies
              </DropdownMenuItem>
            )}
          </DropdownMenuSubContent>
        </DropdownMenuSub>

        <DropdownMenuSub>
          <DropdownMenuSubTrigger className="text-sm">🎓 Delegate</DropdownMenuSubTrigger>
          <DropdownMenuSubContent className="w-56 max-h-64 overflow-y-auto">
            {delegates?.map((d) => (
              <DropdownMenuItem
                key={d.email}
                className="text-sm"
                onClick={() => startPreview('delegate' as AppRole, d.company_id, null, d.email)}
              >
                <div className="flex flex-col">
                  <span>{d.first_name} {d.last_name}</span>
                  <span className="text-[10px] text-muted-foreground">{d.email}</span>
                </div>
              </DropdownMenuItem>
            ))}
            {!delegates?.length && (
              <DropdownMenuItem disabled className="text-xs text-muted-foreground">
                No delegates found
              </DropdownMenuItem>
            )}
          </DropdownMenuSubContent>
        </DropdownMenuSub>

        {preview.active && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem className="text-sm text-destructive" onClick={stopPreview}>
              ✕ Exit Preview
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
};

const AdminContent = ({ children }: { children: ReactNode }) => {
  const { adminTheme, toggleAdminTheme } = useAdminTheme();
  useRecentPages();

  const openSearch = () => {
    document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', metaKey: true }));
  };

  return (
    <div>
      <AdminCommandPalette />
      <SidebarProvider>
        <div className="min-h-screen flex w-full bg-background">
          <AdminSidebar />
          <main className="flex-1 overflow-auto">
            <RolePreviewBanner />
            <header className="h-12 flex items-center justify-between border-b border-border px-4 bg-background sticky top-0 z-10">
              <div className="flex items-center gap-3">
                <SidebarTrigger />
                <Breadcrumbs />
              </div>
              <div className="flex items-center gap-1">
                <AdminQuickActions />
                <PreviewDropdown />
                <NotificationBell />
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8 text-muted-foreground hover:text-foreground"
                  onClick={openSearch}
                >
                  <Search className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8 text-muted-foreground hover:text-foreground"
                  onClick={toggleAdminTheme}
                  title={adminTheme === 'dark' ? 'Light mode' : 'Dark mode'}
                >
                  {adminTheme === 'dark' ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
                </Button>
              </div>
            </header>
            <div className="p-6">{children}</div>
          </main>
        </div>
      </SidebarProvider>
    </div>
  );
};

interface AdminLayoutProps {
  children: ReactNode;
}

export default function AdminLayout({ children }: AdminLayoutProps) {
  return (
    <AdminThemeProvider>
      <RolePreviewProvider>
        <AdminContent>{children}</AdminContent>
      </RolePreviewProvider>
    </AdminThemeProvider>
  );
}
