import { Group, Stack, Text, Card, Badge, Box, ActionIcon } from "@mantine/core";
import { PhoneIcon, CheckCircleIcon } from "@phosphor-icons/react";
import { useFreeAgents } from "../../queries";
import UnenrollFreeAgent from "./unenroll-free-agent";
import toast from "@/lib/sonner";
import { useAuth } from "@/contexts/auth-context";
import PlayerAvatar from "@/components/player-avatar";

const EnrolledFreeAgent: React.FC<{ tournamentId: string, isRegional?: boolean }> = ({
  tournamentId,
  isRegional
}) => {
  const { data: freeAgents } = useFreeAgents(tournamentId);
  const { user } = useAuth();

  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");
    }
  };

  if (isRegional) {
    return (
      <Stack gap="sm">
        <Card withBorder radius="md" p="md">
          <Group justify="space-between" align="center" wrap="nowrap">
            <Group gap="md" align="center">
              <PlayerAvatar name={`${user?.first_name} ${user?.last_name}`} size={48} />
              <Box>
                <Text size="sm" fw={600}>
                  {user?.first_name} {user?.last_name}
                </Text>
                <Group gap={4} align="center">
                  <CheckCircleIcon size={14} weight="fill" color="var(--mantine-color-green-6)" />
                  <Text size="xs" c="green" fw={500}>
                    Enrolled
                  </Text>
                </Group>
              </Box>
            </Group>
          </Group>
        </Card>

        <Text size="xs" c="dimmed" ta="center">
          Partners will be randomly assigned when enrollment closes
        </Text>

        <UnenrollFreeAgent tournamentId={tournamentId} isRegional={isRegional} />
      </Stack>
    );
  }

  return (
    <Stack gap="sm">
      <Text size="sm" fw={600} c="green">
        ✓ Enrolled as Free Agent
      </Text>

      <Text size="xs" c="dimmed">
        Other players looking for teammates:
      </Text>

      {freeAgents.length > 1 ? (
        <Stack gap="xs">
          <Group gap="xs" align="center">
            <Text size="xs" fw={500} c="dimmed">
              Free Agents
            </Text>
            <Badge variant="light" size="xs" color="blue">
              {freeAgents.length}
            </Badge>
          </Group>

          <Stack gap="xs">
            {freeAgents
              .filter(agent => agent.player)
              .map((agent) => (
                <Group key={agent.id} justify="space-between" align="center" wrap="nowrap" p="xs" style={{ borderRadius: '8px', backgroundColor: 'var(--mantine-color-gray-0)' }}>
                  <Text size="sm" fw={500} truncate>
                    {agent.player?.first_name} {agent.player?.last_name}
                  </Text>
                  {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>
              ))}
          </Stack>
        </Stack>
      ) : (
        <Text size="xs" c="dimmed" py="sm">
          You're the first free agent!
        </Text>
      )}

      <UnenrollFreeAgent tournamentId={tournamentId} isRegional={isRegional} />
    </Stack>
  );
};

export default EnrolledFreeAgent;