import { Link, useLocation, useParams } from 'react-router-dom';
import { useAuthStore } from '../../lib/auth';
import { useMyMemberships, useOrganizations } from '../../hooks/useClients';
import { useJobs, useBriefs, useMyQCQueueCount } from '../../hooks/useJob';

interface SidebarItem {
  label: string;
  href: string;
  icon: string;
  roles?: string[];
  badge?: number;
}

interface SidebarProps {
  onMobileClose?: () => void;
}

export function Sidebar({ onMobileClose }: SidebarProps) {
  const { user } = useAuthStore();
  const location = useLocation();
  const params = useParams<{ orgSlug?: string }>();
  const { data: memberships = [] } = useMyMemberships();

  const isQCRole = ['linguist', 'reviewer', 'production', 'admin'].includes(user?.role || '');
  const isPMOrAdmin = ['project_manager', 'admin'].includes(user?.role || '');
  const isAdminOrProduction = ['production', 'admin'].includes(user?.role || '');
  const isPlatformAdmin = user?.role === 'admin';

  const myQCCount = useMyQCQueueCount(isQCRole);
  const { data: finalData } = useJobs(
    { status: 'pending_final_review', size: 1 },
    { enabled: isPMOrAdmin }
  );
  const { data: failuresData } = useJobs(
    { status: 'processing_failed,tts_failed,render_failed', size: 1 },
    { enabled: isAdminOrProduction }
  );

  const { data: allBriefs = [] } = useBriefs();
  const { data: allOrgs = [] } = useOrganizations({ enabled: isPlatformAdmin });

  const qcBadge = isQCRole ? myQCCount : 0;
  const finalBadge = isPMOrAdmin ? (finalData?.total || 0) : 0;
  const failuresBadge = isAdminOrProduction ? (failuresData?.total || 0) : 0;
  const briefsBadge = allBriefs.filter(b => b.status === 'submitted').length;

  // Determine current org ID from route params, first membership, or first org (admin fallback).
  // The route param :orgSlug actually carries the organization _id (hex string),
  // not the human-readable slug — the backend queries memberships by organization_id.
  const currentOrgId =
    params.orgSlug ||
    (memberships.length > 0 ? memberships[0].organization_id : null) ||
    (isPlatformAdmin && allOrgs.length > 0 ? allOrgs[0].id : null);

  const sidebarItems: SidebarItem[] = [
    {
      label: 'Dashboard',
      href: '/',
      icon: '🏠',
    },
    {
      label: 'All Jobs',
      href: '/jobs',
      icon: '📋',
    },
    {
      label: 'Upload Video',
      href: '/jobs/new',
      icon: '📤',
      roles: ['client', 'production', 'admin', 'project_manager'],
    },
    {
      label: 'My QC Queue',
      href: '/qc/queue',
      icon: '📝',
      roles: ['linguist', 'reviewer', 'production', 'admin'],
      badge: qcBadge || undefined,
    },
    {
      label: 'Reviewer Queue',
      href: '/qc/reviewer-queue',
      icon: '🔎',
      roles: ['reviewer', 'admin'],
    },
    {
      label: 'QC Review',
      href: '/admin/qc',
      icon: '🔍',
      roles: ['reviewer', 'linguist', 'production', 'admin'],
    },
    {
      label: 'Final Review',
      href: '/admin/final',
      icon: '✅',
      roles: ['reviewer', 'linguist', 'production', 'admin', 'project_manager'],
      badge: finalBadge || undefined,
    },
    {
      label: 'User Management',
      href: '/admin/users',
      icon: '👥',
      roles: ['admin'],
    },
    {
      label: 'Clients',
      href: '/admin/clients',
      icon: '🏢',
      roles: ['admin', 'project_manager'],
    },
    {
      label: 'Briefs',
      href: '/briefs',
      icon: '📄',
      roles: ['client', 'production', 'admin', 'project_manager'],
      badge: briefsBadge || undefined,
    },
    {
      label: 'Failures',
      href: '/admin/failures',
      icon: '🔥',
      roles: ['production', 'admin'],
      badge: failuresBadge || undefined,
    },
    {
      label: 'Audit Log',
      href: '/admin/audit-log',
      icon: '📋',
      roles: ['production', 'admin', 'project_manager'],
    },
  ];

  const filteredItems = sidebarItems.filter(item => 
    !item.roles || item.roles.includes(user?.role || '')
  );

  const isActive = (href: string) => {
    if (href === '/') {
      return location.pathname === '/';
    }
    return location.pathname.startsWith(href);
  };

  return (
    <div className="h-full w-64 bg-white shadow-lg border-r border-gray-200 flex flex-col">
      {/* Logo/Brand */}
      <div className="flex items-center px-5 py-4 border-b border-gray-200">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-lg flex items-center justify-center flex-shrink-0">
            <span className="text-white text-sm font-bold">VA</span>
          </div>
          <div className="min-w-0">
            <h1 className="text-sm font-bold text-gray-900 truncate">Video Access</h1>
            <p className="text-xs text-gray-400">Accessibility Platform</p>
          </div>
        </div>
      </div>

      {/* Org Switcher — shown when user has memberships or is platform admin with orgs */}
      {(memberships.length > 0 || (isPlatformAdmin && allOrgs.length > 0)) && (
        <div className="px-4 py-3 border-b border-gray-100 bg-gray-50">
          {memberships.length > 0 ? (
            memberships.length === 1 ? (
              <div className="text-xs text-gray-500">
                <span className="font-medium text-gray-700">{memberships[0].organization_name}</span>
                <span className="ml-1 capitalize text-gray-400">· {memberships[0].role_in_org}</span>
              </div>
            ) : (
              <select
                value={currentOrgId || ''}
                onChange={(e) => {
                  const orgId = e.target.value;
                  window.location.href = `/video-accessibility/org/${orgId}/settings/members`;
                }}
                className="w-full text-xs border-0 bg-transparent text-gray-700 font-medium focus:outline-none cursor-pointer"
              >
                {memberships.map(m => (
                  <option key={m.organization_id} value={m.organization_id}>
                    {m.organization_name}
                  </option>
                ))}
              </select>
            )
          ) : (
            /* Platform admin with no personal memberships — show org switcher from full org list */
            allOrgs.length === 1 ? (
              <div className="text-xs text-gray-500">
                <span className="font-medium text-gray-700">{allOrgs[0].name}</span>
                <span className="ml-1 text-gray-400">· admin</span>
              </div>
            ) : (
              <select
                value={currentOrgId || ''}
                onChange={(e) => {
                  const orgId = e.target.value;
                  window.location.href = `/video-accessibility/org/${orgId}/settings/members`;
                }}
                className="w-full text-xs border-0 bg-transparent text-gray-700 font-medium focus:outline-none cursor-pointer"
              >
                {allOrgs.map(org => (
                  <option key={org.id} value={org.id}>
                    {org.name}
                  </option>
                ))}
              </select>
            )
          )}
        </div>
      )}

      {/* Navigation */}
      <nav className="flex-1 px-3 py-4 space-y-0.5 overflow-y-auto">
        {filteredItems.map((item) => (
          <Link
            key={item.href}
            to={item.href}
            onClick={onMobileClose}
            className={`flex items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150 ${
              isActive(item.href)
                ? 'bg-indigo-50 text-indigo-700'
                : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
            }`}
          >
            <span className="text-base mr-2.5">{item.icon}</span>
            <span className="flex-1">{item.label}</span>
            {item.badge && (
              <span className={`px-1.5 py-0.5 text-xs rounded-full font-medium ${
                isActive(item.href) ? 'bg-indigo-100 text-indigo-700' : 'bg-gray-100 text-gray-500'
              }`}>
                {item.badge}
              </span>
            )}
          </Link>
        ))}

        {/* Org Settings link */}
        {currentOrgId && (
          <Link
            to={`/org/${currentOrgId}/settings/members`}
            onClick={onMobileClose}
            className={`flex items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150 ${
              location.pathname.includes('/settings')
                ? 'bg-indigo-50 text-indigo-700'
                : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
            }`}
          >
            <span className="text-base mr-2.5">⚙️</span>
            <span>Settings</span>
          </Link>
        )}
      </nav>

      {/* Help link — bottom of nav, above user info */}
      <div className="px-3 pb-2 border-t border-gray-100 pt-2">
        <Link
          to="/help"
          onClick={onMobileClose}
          className={`flex items-center px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150 ${
            location.pathname === '/help'
              ? 'bg-indigo-50 text-indigo-700'
              : 'text-gray-500 hover:text-gray-900 hover:bg-gray-50'
          }`}
        >
          <span className="text-base mr-2.5">📖</span>
          <span>Help</span>
        </Link>
      </div>

      {/* User Info */}
      <div className="px-4 py-3 border-t border-gray-200">
        <div className="flex items-center space-x-2.5">
          <div className="w-7 h-7 bg-gradient-to-br from-indigo-400 to-purple-500 rounded-full flex items-center justify-center flex-shrink-0">
            <span className="text-white text-xs font-medium">
              {(user?.full_name || user?.email || '?').charAt(0).toUpperCase()}
            </span>
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-xs font-medium text-gray-900 truncate">
              {user?.full_name || user?.email}
            </p>
            <p className="text-xs text-gray-400 capitalize">{user?.role}</p>
          </div>
        </div>
      </div>
    </div>
  );
}