import { useState } from "react";
import { Box, Card, Text, Select, Button, Group, Stack, Badge, Divider } from "@mantine/core";
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 { 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}`
        : "Player";

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

      setSelectedPlayerId(null);
    } catch (error) {
      toast.error("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">
              Award Manual Badge
            </Text>
          </Box>

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

          {selectedBadgeId && (
            <>
              <Divider />

              <Stack gap="md">
                <Select
                  label="Select Player"
                  placeholder="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"
                  >
                    Award Badge
                  </Button>
                </Group>
              </Stack>
            </>
          )}
        </Stack>
      </Card>
    </Box>
  );
};

export default AwardBadges;
