import { Group, Stack, Text, Card, Badge, Box, ActionIcon } from "@mantine/core";
import { UserIcon, PhoneIcon } from "@phosphor-icons/react";
import { useFreeAgents } from "../../queries";
import UnenrollFreeAgent from "./unenroll-free-agent";
import toast from "@/lib/sonner";

const EnrolledFreeAgent: React.FC<{ tournamentId: string }> = ({
  tournamentId
}) => {
  const { data: freeAgents } = useFreeAgents(tournamentId);

  const copyToClipboard = async (phone: string) => {
    try {
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(phone);
        toast.success("Phone number copied!");
        return;
      }

      const textArea = document.createElement("textarea");
      textArea.value = phone;
      textArea.style.display = "hidden";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      const successful = document.execCommand('copy');
      document.body.removeChild(textArea);

      if (successful) {
        toast.success("Phone number copied!");
      } else {
        throw new Error("Copy command failed");
      }
    } catch (err) {
      console.error("Failed to copy:", err);
      toast.error("Failed to copy");
    }
  };

  return (
    <Stack gap="md">
      <Group justify="space-between" align="center">
        <Group gap="xs" align="center">
          <UserIcon size={16} />
          <Text size="sm" fw={500}>
            Enrolled as Free Agent
          </Text>
        </Group>
      </Group>

      <Text size="xs" c="dimmed">
        You're on the free agent list. Other free agents looking for teams:
      </Text>

      {freeAgents.length > 1 ? (
        <Card withBorder radius="md" p="sm">
          <Stack gap="xs">
            {freeAgents
              .filter(agent => agent.player)
              .map((agent) => (
                <Group key={agent.id} justify="space-between" align="center" wrap="nowrap">
                  <Box style={{ flex: 1, minWidth: 0 }}>
                    <Text size="sm" fw={500} truncate>
                      {agent.player?.first_name} {agent.player?.last_name}
                    </Text>
                  </Box>
                  {agent.phone && (
                    <Group gap={4} align="center" style={{ flexShrink: 0 }}>
                      <ActionIcon
                        variant="subtle"
                        size="sm"
                        onClick={() => copyToClipboard(agent.phone!)}
                        style={{ cursor: 'pointer' }}
                      >
                        <PhoneIcon size={12} />
                      </ActionIcon>
                      <Text
                        size="xs"
                        c="dimmed"
                        style={{ cursor: 'pointer' }}
                        onClick={() => copyToClipboard(agent.phone!)}
                      >
                        {agent.phone}
                      </Text>
                    </Group>
                  )}
                </Group>
              ))}

            {freeAgents.length > 1 && (
              <Badge
                variant="light"
                size="xs"
                color="blue"
                style={{ alignSelf: 'flex-start', marginTop: '4px' }}
              >
                {freeAgents.length} free agents total
              </Badge>
            )}
          </Stack>
        </Card>
      ) : (
        <Card withBorder radius="md" p="sm">
          <Text size="sm" c="dimmed" ta="center">
            You're the only free agent so far
          </Text>
        </Card>
      )}
      <UnenrollFreeAgent tournamentId={tournamentId} />
    </Stack>
  );
};

export default EnrolledFreeAgent;