'use client';

import { useState, useEffect, useRef } from 'react';
import { useSession } from 'next-auth/react';
import { MapPin, ChevronDown, Check } from 'lucide-react';
import { cn } from '@/lib/utils';

interface Site {
  id: string;
  name: string;
}

export function SiteSwitcher() {
  const { data: session } = useSession();
  const [sites, setSites] = useState<Site[]>([]);
  const [selectedSiteId, setSelectedSiteId] = useState<string | null>(null);
  const [isOpen, setIsOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const isSuperAdmin = session?.user?.role === 'SUPER_ADMIN';

  useEffect(() => {
    async function fetchSites() {
      try {
        const response = await fetch('/api/sites');
        if (response.ok) {
          const data = await response.json();
          setSites(data.data || []);
        }
      } catch (error) {
        console.error('Failed to fetch sites:', error);
      } finally {
        setIsLoading(false);
      }
    }

    fetchSites();
  }, []);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const selectedSite = sites.find((site) => site.id === selectedSiteId);
  const displayName = selectedSiteId ? selectedSite?.name : 'Todas las sedes';

  // For non-SUPER_ADMIN users, just show their assigned site
  if (!isSuperAdmin) {
    const userSiteName = sites.length > 0 ? sites[0]?.name : 'Cargando...';
    return (
      <div className="flex items-center gap-2 text-sm text-primary-700">
        <MapPin className="h-4 w-4 text-primary-500" />
        <span>{isLoading ? 'Cargando...' : userSiteName}</span>
      </div>
    );
  }

  // For SUPER_ADMIN, show dropdown to select site
  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={cn(
          'flex items-center gap-2 rounded-lg border border-primary-200 bg-white px-3 py-2 text-sm font-medium text-primary-700 transition-colors hover:bg-primary-50',
          isOpen && 'ring-2 ring-primary-500 ring-offset-1'
        )}
      >
        <MapPin className="h-4 w-4 text-primary-500" />
        <span>{isLoading ? 'Cargando...' : displayName}</span>
        <ChevronDown className={cn('h-4 w-4 transition-transform', isOpen && 'rotate-180')} />
      </button>

      {isOpen && (
        <div className="absolute left-0 top-full z-50 mt-1 w-56 rounded-lg border border-primary-200 bg-white py-1 shadow-lg">
          <button
            onClick={() => {
              setSelectedSiteId(null);
              setIsOpen(false);
            }}
            className={cn(
              'flex w-full items-center justify-between px-3 py-2 text-sm text-primary-700 hover:bg-primary-50',
              !selectedSiteId && 'bg-primary-50 font-medium'
            )}
          >
            <span>Todas las sedes</span>
            {!selectedSiteId && <Check className="h-4 w-4 text-primary" />}
          </button>
          <div className="my-1 border-t border-primary-100" />
          {sites.map((site) => (
            <button
              key={site.id}
              onClick={() => {
                setSelectedSiteId(site.id);
                setIsOpen(false);
              }}
              className={cn(
                'flex w-full items-center justify-between px-3 py-2 text-sm text-primary-700 hover:bg-primary-50',
                selectedSiteId === site.id && 'bg-primary-50 font-medium'
              )}
            >
              <span>{site.name}</span>
              {selectedSiteId === site.id && <Check className="h-4 w-4 text-primary" />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export default SiteSwitcher;
