import { useEffect, useRef, useState } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2 } from 'lucide-react';
import { useAPI } from '@/providers/APIProvider';

const ServerManager = ({ onServerChange = () => {} }) => {
  const { servers, loading, error, loadServers } = useAPI();
  const initialized = useRef(false);
  const [selectedServer, setSelectedServer] = useState(null);

  // Initial load of servers
  useEffect(() => {
    const initializeServers = async () => {
      if (!initialized.current) {
        initialized.current = true;
        await loadServers();
        console.log(servers);
      }
    };

    initializeServers();
  }, [loadServers]);

  // Handle server selection when servers are loaded
  useEffect(() => {
    if (servers?.length > 0 && !loading && !selectedServer) {
      const defaultServer = servers[0];
      setSelectedServer(defaultServer);
      onServerChange(defaultServer.id);
    }
  }, [servers, loading, onServerChange, selectedServer]);

  const handleServerChange = (serverId) => {
    const server = servers.find(s => s.id === serverId);
    if (server) {
      setSelectedServer(server);
      onServerChange(serverId);
    }
  };

  if (loading) {
    return (
        <div className="flex items-center gap-2 text-muted-foreground">
          <Loader2 className="h-4 w-4 animate-spin" />
          <span>서버 목록 불러오는 중...</span>
        </div>
    );
  }

  if (error) {
    return (
        <Alert variant="destructive" className="w-full max-w-md">
          <AlertDescription>{error}</AlertDescription>
        </Alert>
    );
  }

  if (!servers?.length) {
    return (
        <Alert className="w-full max-w-md">
          <AlertDescription>사용 가능한 서버가 없습니다.</AlertDescription>
        </Alert>
    );
  }

  return (
      <Select
          value={selectedServer?.id}
          onValueChange={handleServerChange}
      >
        <SelectTrigger className="w-40">
          <SelectValue placeholder="서버 선택">
            {selectedServer?.name}
          </SelectValue>
        </SelectTrigger>
        <SelectContent>
          {servers.map((server) => (
              <SelectItem
                  key={server.id}
                  value={server.id}
              >
                {server.name}
              </SelectItem>
          ))}
        </SelectContent>
      </Select>
  );
};

export default ServerManager;
