"use client";

import * as React from 'react';
import { useEffect, useState, useRef } from 'react';
import type { Database } from '@/types/supabase';
import { getSupabaseClient } from '../../utils/supabase';
import { AuthChangeEvent, Session } from '@supabase/supabase-js';
import { Loader2, X, Check } from 'lucide-react';
import { cn } from '@/lib/utils';

type Team = Database['limq']['Tables']['teams']['Row'];

// TeamSelector component with multi-select support
export function TeamSelector({ 
  value, 
  onChange, 
  className,
  multiple = false,
}: { 
  value?: string | string[];
  onChange?: (teamId: string | string[]) => void;
  className?: string;
  multiple?: boolean;
}) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [teams, setTeams] = useState<Team[]>([]);
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const selectorRef = useRef<HTMLDivElement>(null);

  // Initialize selected teams based on value prop
  useEffect(() => {
    if (value) {
      if (Array.isArray(value)) {
        setSelectedIds(value);
      } else {
        setSelectedIds(value ? [value] : []);
      }
    } else {
      setSelectedIds([]);
    }
  }, [value]);

  // Add click outside listener to close dropdown
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (selectorRef.current && !selectorRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

    // Only add the event listener if the dropdown is open
    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [isOpen]);

  useEffect(() => {
    let isMounted = true;

    const fetchTeams = async (userId: string) => {
      if (!isMounted) return;
      setLoading(true);
      setError(null);
      
      try {
        const supabase = getSupabaseClient();
        
        const { data: memberships, error: membershipError } = await supabase
          .from('team_membership')
          .select('team_id')
          .eq('user_id', userId);

        if (membershipError) throw membershipError;

        if (!memberships || memberships.length === 0) {
          if (isMounted) setTeams([]);
          return;
        }

        const teamIds = memberships.map(m => m.team_id);
        const { data: teamsData, error: teamsError } = await supabase
          .from('teams')
          .select('*')
          .in('id', teamIds)
          .is('deleted_at', null);

        if (teamsError) throw teamsError;

        if (isMounted && teamsData) {
          setTeams(teamsData);
        }
      } catch (err) {
        if (isMounted) {
          setError(err instanceof Error ? err.message : 'Failed to load teams');
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    const supabase = getSupabaseClient();
    
    const { data: { subscription } } = supabase.auth.onAuthStateChange((event: AuthChangeEvent, session: Session | null) => {
      if (event === 'SIGNED_IN' && session?.user?.id) {
        fetchTeams(session.user.id);
      } else if (event === 'SIGNED_OUT') {
        setTeams([]);
        setError(null);
      }
    });

    supabase.auth.getSession().then(({ data: { session } }) => {
      if (session?.user?.id) {
        fetchTeams(session.user.id);
      }
    });

    return () => {
      isMounted = false;
      subscription.unsubscribe();
    };
  }, []);

  const handleToggle = () => {
    if (!loading && !error && teams.length > 0) {
      setIsOpen(!isOpen);
    }
  };

  const handleTeamSelect = (teamId: string) => {
    let newSelected: string[];
    
    if (multiple) {
      // For multi-select: toggle team in/out of selection
      if (selectedIds.includes(teamId)) {
        newSelected = selectedIds.filter(id => id !== teamId);
      } else {
        newSelected = [...selectedIds, teamId];
      }
    } else {
      // For single-select: replace selection with the new team
      newSelected = [teamId];
      setIsOpen(false);
    }
    
    setSelectedIds(newSelected);
    
    if (onChange) {
      onChange(multiple ? newSelected : newSelected[0] || '');
    }
  };

  const removeTeam = (e: React.MouseEvent, teamId: string) => {
    e.stopPropagation();
    const newSelected = selectedIds.filter(id => id !== teamId);
    setSelectedIds(newSelected);
    if (onChange) {
      onChange(multiple ? newSelected : newSelected[0] || '');
    }
  };

  if (loading) {
    return (
      <div className={cn(
        "flex w-full items-center justify-between rounded-md border px-3 py-2",
        className
      )}>
        <Loader2 className="h-4 w-4 animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className={cn(
        "flex w-full items-center rounded-md border border-destructive bg-destructive/10 px-3 py-2 text-destructive",
        className
      )}>
        {error}
      </div>
    );
  }

  if (teams.length === 0) {
    return (
      <div className={cn(
        "flex w-full items-center rounded-md border px-3 py-2 text-muted-foreground",
        className
      )}>
        No teams available
      </div>
    );
  }

  const selectedTeams = teams.filter(team => selectedIds.includes(team.id));

  return (
    <div className="relative" ref={selectorRef}>
      <div 
        className={cn(
          "flex w-full min-h-10 items-center flex-wrap rounded-md border p-1 cursor-pointer",
          isOpen && "ring-2 ring-offset-2 ring-blue-500",
          className
        )}
        onClick={handleToggle}
      >
        {selectedTeams.length > 0 ? (
          <div className="flex flex-wrap gap-1">
            {selectedTeams.map(team => (
              <div 
                key={team.id} 
                className="flex items-center gap-1 bg-blue-100 text-blue-800 rounded-md px-2 py-1 text-sm"
              >
                {team.name}
                {multiple && (
                  <X 
                    size={14} 
                    className="cursor-pointer hover:text-blue-900" 
                    onClick={(e) => removeTeam(e, team.id)} 
                  />
                )}
              </div>
            ))}
          </div>
        ) : (
          <div className="px-2 py-1 text-gray-500">Select a team</div>
        )}
      </div>
      
      {isOpen && (
        <div className="absolute w-full mt-1 max-h-60 overflow-auto rounded-md border bg-white shadow-lg z-10">
          {teams.map(team => (
            <div 
              key={team.id}
              className={cn(
                "px-3 py-2 cursor-pointer hover:bg-gray-100 flex items-center justify-between",
                selectedIds.includes(team.id) && "bg-blue-50"
              )}
              onClick={() => handleTeamSelect(team.id)}
            >
              <span>{team.name}</span>
              {selectedIds.includes(team.id) && (
                <Check className="h-4 w-4 text-blue-600" />
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
} 