'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import { 
  BarChart3, 
  ChevronDown, 
  CreditCard, 
  Handshake, 
  LogOut, 
  Megaphone, 
  Paintbrush, 
  Settings, 
  Shield 
} from 'lucide-react';
import { useAuth } from '@/lib/auth/AuthContext';
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
import { DriverViewModel as DriverViewModelClass } from '@/lib/view-models/DriverViewModel';
import { useFindDriverById } from '@/hooks/driver/useFindDriverById';
import { routes } from '@/lib/routing/RouteConfig';
import { Box } from '@/ui/Box';
import { Text } from '@/ui/Text';
import { Icon } from '@/ui/Icon';
import { Link } from '@/ui/Link';
import { Image } from '@/ui/Image';

// Hook to detect demo user mode based on session
function useDemoUserMode(): { isDemo: boolean; demoRole: string | null } {
  const { session } = useAuth();
  const [demoMode, setDemoMode] = useState({ isDemo: false, demoRole: null as string | null });
  
  // Check if this is a demo user
  useEffect(() => {
    if (!session?.user) {
      setDemoMode({ isDemo: false, demoRole: null });
      return;
    }

    const email = session.user.email?.toLowerCase() || '';
    const displayName = session.user.displayName?.toLowerCase() || '';
    const primaryDriverId = session.user.primaryDriverId || '';
    const role = 'role' in session.user ? (session.user as { role?: string }).role : undefined;

    // Check if this is a demo user
    if (email.includes('demo') ||
        displayName.includes('demo') ||
        primaryDriverId.startsWith('demo-')) {
      
      // Use role from session if available, otherwise derive from email
      let roleToUse = role;
      if (!roleToUse) {
        if (email.includes('sponsor')) roleToUse = 'sponsor';
        else if (email.includes('league-owner') || displayName.includes('owner')) roleToUse = 'league-owner';
        else if (email.includes('league-steward') || displayName.includes('steward')) roleToUse = 'league-steward';
        else if (email.includes('league-admin') || displayName.includes('admin')) roleToUse = 'league-admin';
        else if (email.includes('system-owner') || displayName.includes('system owner')) roleToUse = 'system-owner';
        else if (email.includes('super-admin') || displayName.includes('super admin')) roleToUse = 'super-admin';
        else roleToUse = 'driver';
      }
      
      setDemoMode({ isDemo: true, demoRole: roleToUse });
    } else {
      setDemoMode({ isDemo: false, demoRole: null });
    }
  }, [session]);
  
  return demoMode;
}

// Helper to check if user has admin access (Owner or Super Admin)
function useHasAdminAccess(): boolean {
  const { session } = useAuth();
  const { isDemo, demoRole } = useDemoUserMode();
  
  // Demo users with system-owner or super-admin roles
  if (isDemo && (demoRole === 'system-owner' || demoRole === 'super-admin')) {
    return true;
  }
  
  // Real users - would need role information from session
  // For now, we'll check if the user has any admin-related capabilities
  // This can be enhanced when the API includes role information
  if (!session?.user) return false;
  
  // Check for admin-related email patterns as a temporary measure
  const email = session.user.email?.toLowerCase() || '';
  const displayName = session.user.displayName?.toLowerCase() || '';
  
  return email.includes('system-owner') ||
         email.includes('super-admin') ||
         displayName.includes('system owner') ||
         displayName.includes('super admin');
}

export function UserPill() {
  const { session } = useAuth();
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const { isDemo, demoRole } = useDemoUserMode();

  const primaryDriverId = useEffectiveDriverId();

  // Use React-Query hook for driver data (only for non-demo users)
  const { data: driverDto } = useFindDriverById(primaryDriverId || '', {
    enabled: !!primaryDriverId && !isDemo,
  });

  // Transform DTO to ViewModel
  const driver = useMemo(() => {
    if (!driverDto) return null;
    return new DriverViewModelClass({ ...driverDto, avatarUrl: driverDto.avatarUrl ?? null });
  }, [driverDto]);

  // Close menu when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (isMenuOpen) {
        const target = e.target as HTMLElement;
        if (!target.closest('[data-user-pill]')) {
          setIsMenuOpen(false);
        }
      }
    };
    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, [isMenuOpen]);

  // Logout handler for demo users
  const handleLogout = async () => {
    try {
      // Call the logout API
      await fetch('/api/auth/logout', { method: 'POST' });
      // Redirect to home
      window.location.href = '/';
    } catch (error) {
      console.error('Logout failed:', error);
      window.location.href = '/';
    }
  };

  // Call hooks unconditionally before any returns
  const hasAdminAccess = useHasAdminAccess();
  
  // Handle unauthenticated users
  if (!session) {
    return (
      <Box display="flex" alignItems="center" gap={2}>
        <Link
          href={routes.auth.login}
          variant="secondary"
          rounded="full"
          px={4}
          py={1.5}
          size="xs"
          hoverTextColor="text-white"
          hoverBorderColor="border-gray-500"
        >
          Sign In
        </Link>
        <Link
          href={routes.auth.signup}
          variant="primary"
          rounded="full"
          px={4}
          py={1.5}
          size="xs"
          shadow="0 0 12px rgba(25,140,255,0.5)"
          hoverBg="rgba(25,140,255,0.9)"
        >
          Get Started
        </Link>
      </Box>
    );
  }

  // For all authenticated users (demo or regular), show the user pill
  // Determine what to show in the pill
  const displayName = driver?.name || session.user.displayName || session.user.email || 'User';
  const avatarUrl = session.user.avatarUrl;
  const roleLabel = isDemo ? ({
    'driver': 'Driver',
    'sponsor': 'Sponsor',
    'league-owner': 'League Owner',
    'league-steward': 'League Steward',
    'league-admin': 'League Admin',
    'system-owner': 'System Owner',
    'super-admin': 'Super Admin',
  } as Record<string, string>)[demoRole || 'driver'] : null;

  const roleColor = isDemo ? ({
    'driver': 'text-primary-blue',
    'sponsor': 'text-performance-green',
    'league-owner': 'text-purple-400',
    'league-steward': 'text-warning-amber',
    'league-admin': 'text-red-400',
    'system-owner': 'text-indigo-400',
    'super-admin': 'text-pink-400',
  } as Record<string, string>)[demoRole || 'driver'] : null;

  return (
    <Box position="relative" display="inline-flex" alignItems="center" data-user-pill>
      <Box
        as="button"
        type="button"
        onClick={() => setIsMenuOpen((open) => !open)}
        display="flex"
        alignItems="center"
        gap={3}
        rounded="full"
        border
        px={3}
        py={1.5}
        transition
        cursor="pointer"
        bg="linear-gradient(to r, var(--iron-gray), var(--deep-graphite))"
        borderColor={isMenuOpen ? 'border-primary-blue/50' : 'border-charcoal-outline'}
        transform={isMenuOpen ? 'scale(1.02)' : 'scale(1)'}
      >
        {/* Avatar */}
        <Box position="relative">
          {avatarUrl ? (
            <Box w="8" h="8" rounded="full" overflow="hidden" bg="bg-charcoal-outline" display="flex" alignItems="center" justifyContent="center" border borderColor="border-charcoal-outline/80">
              <Image
                src={avatarUrl}
                alt={displayName}
                objectFit="cover"
                fill
              />
            </Box>
          ) : (
            <Box w="8" h="8" rounded="full" bg="bg-primary-blue/20" border borderColor="border-primary-blue/30" display="flex" alignItems="center" justifyContent="center">
              <Text size="xs" weight="bold" color="text-primary-blue">
                {displayName[0]?.toUpperCase() || 'U'}
              </Text>
            </Box>
          )}
          <Box position="absolute" bottom="-0.5" right="-0.5" w="3" h="3" rounded="full" bg="bg-primary-blue" border borderColor="border-deep-graphite" borderWidth="2px" />
        </Box>

        {/* Info */}
        <Box display={{ base: 'none', sm: 'flex' }} flexDirection="col" alignItems="start">
          <Text size="xs" weight="semibold" color="text-white" truncate maxWidth="100px" block>
            {displayName}
          </Text>
          {roleLabel && (
            <Text size="xs" color={roleColor || 'text-gray-400'} weight="medium" fontSize="10px">
              {roleLabel}
            </Text>
          )}
        </Box>

        {/* Chevron */}
        <Icon icon={ChevronDown} size={3.5} color="rgb(107, 114, 128)" groupHoverTextColor="text-gray-300" />
      </Box>

      <AnimatePresence>
        {isMenuOpen && (
          <Box
            as={motion.div}
            initial={{ opacity: 0, y: -10, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -10, scale: 0.95 }}
            transition={{ duration: 0.15 }}
            position="absolute"
            right={0}
            top="100%"
            mt={2}
            zIndex={50}
          >
            <Box w="56" rounded="xl" bg="bg-deep-graphite" border borderColor="border-charcoal-outline" shadow="xl" overflow="hidden">
              {/* Header */}
              <Box p={4} borderBottom borderColor="border-charcoal-outline" bg={`linear-gradient(to r, ${isDemo ? 'rgba(59, 130, 246, 0.1)' : 'rgba(38, 38, 38, 0.2)'}, transparent)`}>
                <Box display="flex" alignItems="center" gap={3}>
                  {avatarUrl ? (
                    <Box w="10" h="10" rounded="lg" overflow="hidden" bg="bg-charcoal-outline" display="flex" alignItems="center" justifyContent="center" border borderColor="border-charcoal-outline/80">
                      <Image
                        src={avatarUrl}
                        alt={displayName}
                        objectFit="cover"
                        fill
                      />
                    </Box>
                  ) : (
                    <Box w="10" h="10" rounded="lg" bg="bg-primary-blue/20" border borderColor="border-primary-blue/30" display="flex" alignItems="center" justifyContent="center">
                      <Text size="xs" weight="bold" color="text-primary-blue">
                        {displayName[0]?.toUpperCase() || 'U'}
                      </Text>
                    </Box>
                  )}
                  <Box>
                    <Text size="sm" weight="semibold" color="text-white" block>{displayName}</Text>
                    {roleLabel && (
                      <Text size="xs" color={roleColor || 'text-gray-400'} block>{roleLabel}</Text>
                    )}
                    {isDemo && (
                      <Text size="xs" color="text-gray-500" block>Demo Account</Text>
                    )}
                  </Box>
                </Box>
                {isDemo && (
                  <Text size="xs" color="text-gray-500" block mt={2}>
                    Development account - not for production use
                  </Text>
                )}
              </Box>

              {/* Menu Items */}
              <Box py={1}>
                {/* Admin link for Owner/Super Admin users */}
                {hasAdminAccess && (
                  <Link
                    href="/admin"
                    block
                    px={4}
                    py={2.5}
                    onClick={() => setIsMenuOpen(false)}
                  >
                    <Icon icon={Shield} size={4} color="rgb(129, 140, 248)" mr={3} />
                    <Text size="sm" color="text-gray-200">Admin Area</Text>
                  </Link>
                )}
                
                {/* Sponsor portal link for demo sponsor users */}
                {isDemo && demoRole === 'sponsor' && (
                  <>
                    <Link
                      href="/sponsor"
                      block
                      px={4}
                      py={2.5}
                      onClick={() => setIsMenuOpen(false)}
                    >
                      <Icon icon={BarChart3} size={4} color="rgb(16, 185, 129)" mr={3} />
                      <Text size="sm" color="text-gray-200">Dashboard</Text>
                    </Link>
                    <Link
                      href={routes.sponsor.campaigns}
                      block
                      px={4}
                      py={2.5}
                      onClick={() => setIsMenuOpen(false)}
                    >
                      <Icon icon={Megaphone} size={4} color="rgb(59, 130, 246)" mr={3} />
                      <Text size="sm" color="text-gray-200">My Sponsorships</Text>
                    </Link>
                    <Link
                      href={routes.sponsor.billing}
                      block
                      px={4}
                      py={2.5}
                      onClick={() => setIsMenuOpen(false)}
                    >
                      <Icon icon={CreditCard} size={4} color="rgb(245, 158, 11)" mr={3} />
                      <Text size="sm" color="text-gray-200">Billing</Text>
                    </Link>
                    <Link
                      href={routes.sponsor.settings}
                      block
                      px={4}
                      py={2.5}
                      onClick={() => setIsMenuOpen(false)}
                    >
                      <Icon icon={Settings} size={4} color="rgb(156, 163, 175)" mr={3} />
                      <Text size="sm" color="text-gray-200">Settings</Text>
                    </Link>
                  </>
                )}

                {/* Regular user profile links */}
                <Link
                  href={routes.protected.profile}
                  block
                  px={4}
                  py={2.5}
                  onClick={() => setIsMenuOpen(false)}
                >
                  <Text size="sm" color="text-gray-200">Profile</Text>
                </Link>
                <Link
                  href={routes.protected.profileLeagues}
                  block
                  px={4}
                  py={2.5}
                  onClick={() => setIsMenuOpen(false)}
                >
                  <Text size="sm" color="text-gray-200">Manage leagues</Text>
                </Link>
                <Link
                  href={routes.protected.profileLiveries}
                  block
                  px={4}
                  py={2.5}
                  onClick={() => setIsMenuOpen(false)}
                >
                  <Icon icon={Paintbrush} size={4} mr={2} />
                  <Text size="sm" color="text-gray-200">Liveries</Text>
                </Link>
                <Link
                  href={routes.protected.profileSponsorshipRequests}
                  block
                  px={4}
                  py={2.5}
                  onClick={() => setIsMenuOpen(false)}
                >
                  <Icon icon={Handshake} size={4} color="rgb(16, 185, 129)" mr={2} />
                  <Text size="sm" color="text-gray-200">Sponsorship Requests</Text>
                </Link>
                <Link
                  href={routes.protected.profileSettings}
                  block
                  px={4}
                  py={2.5}
                  onClick={() => setIsMenuOpen(false)}
                >
                  <Icon icon={Settings} size={4} mr={2} />
                  <Text size="sm" color="text-gray-200">Settings</Text>
                </Link>

                {/* Demo-specific info */}
                {isDemo && (
                  <Box px={4} py={2} borderTop borderColor="border-charcoal-outline/50" mt={1}>
                    <Text size="xs" color="text-gray-500" italic>Demo users have limited profile access</Text>
                  </Box>
                )}
              </Box>

              {/* Footer */}
              <Box borderTop borderColor="border-charcoal-outline">
                {isDemo ? (
                  <Box
                    as="button"
                    type="button"
                    onClick={handleLogout}
                    display="flex"
                    alignItems="center"
                    justifyContent="between"
                    fullWidth
                    px={4}
                    py={3}
                    cursor="pointer"
                    transition
                    bg="transparent"
                    hoverBg="rgba(239, 68, 68, 0.05)"
                    hoverColor="text-racing-red"
                  >
                    <Text size="sm" color="text-gray-500">Logout</Text>
                    <Icon icon={LogOut} size={4} color="rgb(107, 114, 128)" />
                  </Box>
                ) : (
                  <Box as="form" action="/auth/logout" method="POST">
                    <Box
                      as="button"
                      type="submit"
                      display="flex"
                      alignItems="center"
                      justifyContent="between"
                      fullWidth
                      px={4}
                      py={3}
                      cursor="pointer"
                      transition
                      bg="transparent"
                      hoverBg="rgba(239, 68, 68, 0.1)"
                      hoverColor="text-red-400"
                    >
                      <Text size="sm" color="text-gray-500">Logout</Text>
                      <Icon icon={LogOut} size={4} color="rgb(107, 114, 128)" />
                    </Box>
                  </Box>
                )}
              </Box>
            </Box>
          </Box>
        )}
      </AnimatePresence>
    </Box>
  );
}
