import { ActionIcon, Card, Flex, Text } from "@mantine/core";
import { PlayIcon } from "@phosphor-icons/react";
import React from "react";
import { BracketMaps } from "../utils/bracket-maps";

interface Match {
  lid: number;
  round: number;
  order: number | null;
  type: string;
  home: any;
  away?: any;
  reset?: boolean;
}

interface BracketViewProps {
  bracket: Match[][];
  bracketMaps: BracketMaps;
  onAnnounce?: (teamOne: any, teamTwo: any) => void;
}

const BracketView: React.FC<BracketViewProps> = ({
  bracket,
  bracketMaps,
  onAnnounce,
}) => {
  const isMatchType = (type: string, expected: string) => {
    return type?.toLowerCase() === expected.toLowerCase();
  };

  const getParentMatchOrder = (parentLid: number): number | string => {
    const parentMatch = bracketMaps.matchByLid.get(parentLid);
    if (
      parentMatch &&
      parentMatch.order !== null &&
      parentMatch.order !== undefined
    ) {
      return parentMatch.order;
    }
    return `Match ${parentLid}`;
  };

  return (
    <Flex direction="row" gap={24} justify="left" pos="relative" p="xl">
      {bracket.map((round, roundIndex) => (
        <Flex
          direction="column"
          key={roundIndex}
          gap={24}
          justify="space-around"
        >
          {round.map((match, matchIndex) => {
            if (!match) return null;

            if (
              isMatchType(match.type, "bye") ||
              isMatchType(match.type, "tbye")
            ) {
              return <Flex key={matchIndex}></Flex>;
            }

            return (
              <Flex
                direction="row"
                key={matchIndex}
                align="center"
                justify="end"
                gap={8}
              >
                <Text c="dimmed" fw="bolder">
                  {match.order}
                </Text>
                <Card
                  withBorder
                  pos="relative"
                  w={200}
                  style={{ overflow: "visible" }}
                >
                  <Card.Section withBorder p={0}>
                    <Flex align="stretch">
                      {match.home?.seed && (
                        <Text
                          size="xs"
                          fw="bold"
                          py="4"
                          bg="var(--mantine-color-default-hover)"
                          style={{
                            width: "32px",
                            textAlign: "center",
                            color: "var(--mantine-color-text)",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            borderTopLeftRadius:
                              "var(--mantine-radius-default)",
                            borderBottomLeftRadius:
                              "var(--mantine-radius-default)",
                          }}
                        >
                          {match.home.seed}
                        </Text>
                      )}
                      <div style={{ flex: 1, padding: "4px 8px" }}>
                        {match.home?.seed ? (
                          match.home.team ? (
                            <Text size="xs">{match.home.team.name}</Text>
                          ) : (
                            <Text size="xs" c="dimmed">
                              Team {match.home.seed}
                            </Text>
                          )
                        ) : match.home?.parent_lid !== null &&
                          match.home?.parent_lid !== undefined ? (
                          <Text c="dimmed" size="xs">
                            {match.home.loser ? "Loser" : "Winner"} of Match{" "}
                            {getParentMatchOrder(match.home.parent_lid)}
                          </Text>
                        ) : (
                          <Text c="dimmed" size="xs" fs="italic">
                            TBD
                          </Text>
                        )}
                      </div>
                    </Flex>
                  </Card.Section>
                  <Card.Section p={0} mb={-16}>
                    <Flex align="stretch">
                      {match.away?.seed && (
                        <Text
                          size="xs"
                          fw="bold"
                          py="4"
                          bg="var(--mantine-color-default-hover)"
                          style={{
                            width: "32px",
                            textAlign: "center",
                            color: "var(--mantine-color-text)",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            borderTopLeftRadius:
                              "var(--mantine-radius-default)",
                            borderBottomLeftRadius:
                              "var(--mantine-radius-default)",
                          }}
                        >
                          {match.away.seed}
                        </Text>
                      )}
                      <div style={{ flex: 1, padding: "4px 8px" }}>
                        {match.away?.seed ? (
                          match.away.team ? (
                            <Text size="xs">{match.away.team.name}</Text>
                          ) : (
                            <Text size="xs" c="dimmed">
                              Team {match.away.seed}
                            </Text>
                          )
                        ) : match.away?.parent_lid !== null &&
                          match.away?.parent_lid !== undefined ? (
                          <Text c="dimmed" size="xs">
                            {match.away.loser ? "Loser" : "Winner"} of Match{" "}
                            {getParentMatchOrder(match.away.parent_lid)}
                          </Text>
                        ) : match.away ? (
                          <Text c="dimmed" size="xs" fs="italic">
                            TBD
                          </Text>
                        ) : null}
                      </div>
                    </Flex>
                  </Card.Section>
                  {match.reset && (
                    <Text
                      pos="absolute"
                      top={-8}
                      left={8}
                      size="xs"
                      c="orange"
                      fw="bold"
                    >
                      IF NECESSARY
                    </Text>
                  )}
                  {onAnnounce && match.home?.team && match.away?.team && (
                    <ActionIcon
                      pos="absolute"
                      variant="filled"
                      color="green"
                      top={-20}
                      right={-12}
                      onClick={() => {
                        onAnnounce(match.home.team, match.away.team);
                      }}
                      bd="none"
                      style={{ boxShadow: "none" }}
                      size="xs"
                    >
                      <PlayIcon size={12} />
                    </ActionIcon>
                  )}
                </Card>
              </Flex>
            );
          })}
        </Flex>
      ))}
    </Flex>
  );
};

export default BracketView;
