import React, { useEffect, useState } from 'react';
import { ActionIcon, Group, Text, Loader } from '@mantine/core';
import { showErrorMessage } from '~/utils/utils.ts';
import { apiGetTeamList, get_team_info } from '~/utils/hms_api.ts';
import type { DoctorTeamInfo } from '~/utils/models.ts';
import InfoIcon from 'mdi-react/InfoIcon';
import { iconMStyle } from '~/styles.ts';
import { confirmViewTeamMembers } from '~/components/subs/confirms.tsx';
import { Departments } from '~/utils/hms_enums.ts';

const teamCache = new Map<number, DoctorTeamInfo>();

interface TeamInfoDisplayProps {
    teamId: number;
    showIcon?: boolean;
}

export function TeamInfoDisplay({ teamId, showIcon = true }: TeamInfoDisplayProps) {
    const [teamInfo, setTeamInfo] = useState<DoctorTeamInfo | null>(null);
    const [loading, setLoading] = useState(true);
    const [initialLoad, setInitialLoad] = useState(true);

    useEffect(() => {
        if (teamCache.has(teamId)) {
            setTeamInfo(teamCache.get(teamId) || null);
            setLoading(false);
            setInitialLoad(false);
            return;
        }

        fetchTeamInfo();
    }, [teamId]);

    const fetchTeamInfo = async () => {
        try {
            setLoading(true);
            const detailResponse = await get_team_info(teamId);
            
            if (detailResponse.success) {
                const team = detailResponse.data.team;
                teamCache.set(teamId, team);
                setTeamInfo(team);
            } else {
                const listResponse = await apiGetTeamList(-1);
                
                if (listResponse.success) {
                    const teams = listResponse.data.teams;
                    teams.forEach(team => {
                        teamCache.set(team.id, team);
                    });

                    const team = teams.find(t => t.id === teamId);
                    
                    if (team) {
                        setTeamInfo(team);
                    } else {
                        console.warn(`Team with ID ${teamId} not found`);
                    }
                } else {
                    showErrorMessage(listResponse.message, "Failed to load team information");
                }
            }
        } catch (error) {
            showErrorMessage("Error loading team information", "Error");
            console.error("Error fetching team information:", error);
        } finally {
            setLoading(false);
            setInitialLoad(false);
        }
    };

    const handleViewTeamDetails = () => {
        if (!teamInfo) {
            showErrorMessage("Team information not available", "Error");
            return;
        }
        
        confirmViewTeamMembers(teamInfo);
    };

    if (initialLoad) {
        return <Loader size="xs" />;
    }

    if (!teamInfo) {
        return (
            <Group gap="xs">
                <Text>ID: {teamId}</Text>
                {showIcon && (
                    <ActionIcon 
                        size="sm" 
                        onClick={fetchTeamInfo} 
                        loading={loading}
                        title="Refresh team information"
                    >
                        <InfoIcon style={iconMStyle} />
                    </ActionIcon>
                )}
            </Group>
        );
    }

    return (
        <Group gap="xs">
            <Text 
                style={{ cursor: 'pointer' }} 
                onClick={handleViewTeamDetails}
                title="Click to view team details"
            >
                {teamInfo.department.replace(/_/g, ' ')}
            </Text>
            {showIcon && (
                <ActionIcon 
                    size="sm" 
                    onClick={handleViewTeamDetails}
                    title="View team details"
                >
                    <InfoIcon style={iconMStyle} />
                </ActionIcon>
            )}
        </Group>
    );
} 