import { useState } from "react";
import { Box, Card, Text, Select, Button, Group, Stack, Badge, Divider } from "@mantine/core";
import { Trans, useLingui } from "@lingui/react/macro";
import { awardManualBadge } from "@/features/badges/server";
import { useAllBadges } from "@/features/badges/queries";
import toast from "@/lib/sonner";
import { usePlayers } from "@/features/players/queries";

const AwardBadges = () => {
  const { t } = useLingui();
  const { data: players } = usePlayers();
  const { data: allBadges } = useAllBadges();

  const [selectedPlayerId, setSelectedPlayerId] = useState<string | null>(null);
  const [selectedBadgeId, setSelectedBadgeId] = useState<string | null>(null);
  const [isAwarding, setIsAwarding] = useState(false);

  const manualBadges = allBadges.filter((badge) => badge.type === "manual");

  const handleAwardBadge = async () => {
    if (!selectedPlayerId || !selectedBadgeId) return;

    setIsAwarding(true);
    try {
      await awardManualBadge({
        data: {
          playerId: selectedPlayerId,
          badgeId: selectedBadgeId,
        },
      });

      const selectedPlayer = players.find((p) => p.id === selectedPlayerId);
      const playerName = selectedPlayer
        ? `${selectedPlayer.first_name} ${selectedPlayer.last_name}`
        : t`Player`;

      toast.success(t`Badge awarded to ${playerName}`);

      setSelectedPlayerId(null);
    } catch (error) {
      toast.error(t`Failed to award badge`);
    } finally {
      setIsAwarding(false);
    }
  };

  const playerOptions = players.map((player) => ({
    value: player.id,
    label: `${player.first_name} ${player.last_name}`,
  }));

  const badgeOptions = manualBadges.map((badge) => ({
    value: badge.id,
    label: badge.name,
  }));

  const selectedBadge = manualBadges.find((b) => b.id === selectedBadgeId);

  return (
    <Box p="md">
      <Card withBorder radius="md" p="md">
        <Stack gap="lg">
          <Box>
            <Text size="lg" fw={600} mb="xs">
              <Trans>Award Manual Badge</Trans>
            </Text>
          </Box>

          <Select
            label={t`Badge Type`}
            placeholder={t`Select a badge`}
            data={badgeOptions}
            value={selectedBadgeId}
            onChange={setSelectedBadgeId}
            searchable
            clearable
            size="md"
          />

          {selectedBadgeId && (
            <>
              <Divider />

              <Stack gap="md">
                <Select
                  label={t`Select Player`}
                  placeholder={t`Choose a player`}
                  data={playerOptions}
                  value={selectedPlayerId}
                  onChange={setSelectedPlayerId}
                  searchable
                  clearable
                  size="md"
                  autoFocus
                />

                <Group justify="flex-end">
                  <Button
                    onClick={handleAwardBadge}
                    disabled={!selectedPlayerId}
                    loading={isAwarding}
                    size="md"
                  >
                    <Trans>Award Badge</Trans>
                  </Button>
                </Group>
              </Stack>
            </>
          )}
        </Stack>
      </Card>
    </Box>
  );
};

export default AwardBadges;
