import { Group, Stack, Text, Card, Badge, Box, ActionIcon } from "@mantine/core";
import { PhoneIcon, CheckCircleIcon } from "@phosphor-icons/react";
import { Trans, useLingui } from "@lingui/react/macro";
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 { t } = useLingui();

  const copyToClipboard = async (phone: string) => {
    try {
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(phone);
        toast.success(t`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(t`Phone number copied!`);
      } else {
        throw new Error("Copy command failed");
      }
    } catch (err) {
      console.error("Failed to copy:", err);
      toast.error(t`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}>
                    <Trans>Enrolled</Trans>
                  </Text>
                </Group>
              </Box>
            </Group>
          </Group>
        </Card>

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

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

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

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

      {freeAgents.length > 1 ? (
        <Stack gap="xs">
          <Group gap="xs" align="center">
            <Text size="xs" fw={500} c="dimmed">
              <Trans>Free Agents</Trans>
            </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-default-hover)' }}>
                  <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"
                        aria-label={t`Copy phone number`}
                        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">
          <Trans>You're the first free agent!</Trans>
        </Text>
      )}

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

export default EnrolledFreeAgent;