import React from "react";
import { Group, Text, UnstyledButton } from "@mantine/core";
import { Trans } from "@lingui/react/macro";
import { CrownIcon } from "@phosphor-icons/react";
import { TeamInfo } from "@/features/teams/types";
import TeamAvatar from "@/components/team-avatar";

interface WinnerSelectorProps {
  home?: TeamInfo;
  away?: TeamInfo;
  pickedId?: string;
  onSelect: (teamId: string) => void;
}

const TeamChip = ({
  team,
  picked,
  onSelect,
}: {
  team?: TeamInfo;
  picked: boolean;
  onSelect: (teamId: string) => void;
}) => {
  if (!team) {
    return (
      <Group
        gap={8}
        wrap="nowrap"
        justify="center"
        p="6px 10px"
        style={{
          flex: 1,
          minWidth: 0,
          border: "1px dashed var(--mantine-color-default-border)",
          borderRadius: "var(--mantine-radius-md)",
        }}
      >
        <Text size="xs" c="dimmed">
          <Trans>TBD</Trans>
        </Text>
      </Group>
    );
  }

  return (
    <UnstyledButton
      onClick={() => onSelect(team.id)}
      style={{ flex: 1, minWidth: 0 }}
      aria-pressed={picked}
    >
      <Group
        gap={8}
        wrap="nowrap"
        p="6px 10px"
        style={{
          border: `1px solid ${
            picked
              ? "var(--mantine-color-green-light-color)"
              : "var(--mantine-color-default-border)"
          }`,
          borderRadius: "var(--mantine-radius-md)",
          backgroundColor: picked
            ? "var(--mantine-color-green-light)"
            : "transparent",
          transition: "background-color 200ms ease, border-color 200ms ease",
        }}
      >
        <TeamAvatar team={team} size={26} radius="sm" disableFullscreen />
        <Text
          size="xs"
          fw={600}
          truncate
          style={{ flex: 1, minWidth: 0 }}
        >
          {team.name}
        </Text>
        {picked && (
          <CrownIcon
            size={14}
            weight="fill"
            style={{
              color: "gold",
              filter: "drop-shadow(0 1px 1px rgba(0,0,0,0.3))",
              flexShrink: 0,
            }}
          />
        )}
      </Group>
    </UnstyledButton>
  );
};

export const WinnerSelector: React.FC<WinnerSelectorProps> = ({
  home,
  away,
  pickedId,
  onSelect,
}) => (
  <Group gap="xs" wrap="nowrap" align="center">
    <TeamChip
      team={home}
      picked={!!home && pickedId === home.id}
      onSelect={onSelect}
    />
    <Text size="xs" c="dimmed" fw={700}>
      <Trans>vs</Trans>
    </Text>
    <TeamChip
      team={away}
      picked={!!away && pickedId === away.id}
      onSelect={onSelect}
    />
  </Group>
);
