import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Box, Button, Center, HStack, Heading, Image, SimpleGrid, Text, useColorModeValue, useToast, VStack } from '@chakra-ui/react';
import AdminLayout from '@/layouts/AdminLayout';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { getAdminScoreboard, updateAdminScoreboard, ScoreboardState } from '@/services/scoreboard';

const MobileScoreboardControlPage: React.FC = () => {
  const toast = useToast();
  const qc = useQueryClient();
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderCol = useColorModeValue('gray.200', 'gray.700');

  const { data: state, isLoading } = useQuery<ScoreboardState>({
    queryKey: ['admin-scoreboard-mobile'],
    queryFn: getAdminScoreboard,
    refetchInterval: 5000,
    staleTime: 3000,
  });

  const setPartial = async (patch: Partial<ScoreboardState>) => {
    try {
      await updateAdminScoreboard(patch);
      await qc.invalidateQueries({ queryKey: ['admin-scoreboard-mobile'] });
    } catch (e) {
      toast({ title: 'Uložení selhalo', status: 'error' });
    }
  };

  // Simple local match timer (upwards). Does not persist to backend; overlay remains score-only.
  const [running, setRunning] = useState(false);
  const [elapsed, setElapsed] = useState(0); // seconds
  const startRef = useRef<number | null>(null);
  useEffect(() => {
    let raf: number;
    const tick = () => {
      if (running) {
        const now = Date.now();
        const base = startRef.current ?? now;
        startRef.current = base;
        setElapsed(Math.floor((now - base) / 1000));
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [running]);
  const resetTimer = () => { setRunning(false); setElapsed(0); startRef.current = null; };
  const mmss = useMemo(() => {
    const mm = Math.floor(elapsed / 60);
    const ss = elapsed % 60;
    return `${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`;
  }, [elapsed]);

  if (isLoading || !state) {
    return (
      <AdminLayout>
        <Center minH="50vh">Načítání…</Center>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <Box p={3}>
        <Heading size="md" mb={3}>Mobilní ovládání tabule</Heading>
        <VStack align="stretch" spacing={3}>
          <Box borderWidth="1px" borderColor={borderCol} bg={cardBg} borderRadius="lg" p={3}>
            <SimpleGrid columns={3} spacing={2} alignItems="center">
              <VStack spacing={2}>
                {state.homeLogo ? <Image src={state.homeLogo} alt="DOM" boxSize="64px" objectFit="contain" /> : null}
                <Text fontWeight="bold" textAlign="center">{state.homeShort || 'DOM'}</Text>
                <HStack>
                  <Button size="lg" onClick={() => setPartial({ homeScore: Math.max(0, (state.homeScore || 0) - 1) })}>−</Button>
                  <Button size="lg" colorScheme="green" onClick={() => setPartial({ homeScore: (state.homeScore || 0) + 1 })}>+</Button>
                </HStack>
              </VStack>
              <VStack spacing={2}>
                <Text fontSize="5xl" fontWeight="black">{state.homeScore} : {state.awayScore}</Text>
                <HStack>
                  <Button onClick={() => setRunning((r) => !r)}>{running ? 'Stop' : 'Start'}</Button>
                  <Button variant="outline" onClick={resetTimer}>Reset</Button>
                </HStack>
                <Text fontSize="2xl" fontFamily="mono">{mmss}</Text>
              </VStack>
              <VStack spacing={2}>
                {state.awayLogo ? <Image src={state.awayLogo} alt="HOS" boxSize="64px" objectFit="contain" /> : null}
                <Text fontWeight="bold" textAlign="center">{state.awayShort || 'HOS'}</Text>
                <HStack>
                  <Button size="lg" onClick={() => setPartial({ awayScore: Math.max(0, (state.awayScore || 0) - 1) })}>−</Button>
                  <Button size="lg" colorScheme="green" onClick={() => setPartial({ awayScore: (state.awayScore || 0) + 1 })}>+</Button>
                </HStack>
              </VStack>
            </SimpleGrid>
          </Box>

          <Box borderWidth="1px" borderColor={borderCol} bg={cardBg} borderRadius="lg" p={3}>
            <HStack justify="space-between">
              <Text>Vybraný zápas</Text>
              <Text fontWeight="bold">{state.externalMatchId ? state.externalMatchId : '—'}</Text>
            </HStack>
            <HStack mt={2} spacing={2}>
              <Button onClick={() => setPartial({ active: true })} colorScheme="blue">Aktivovat</Button>
              <Button variant="outline" onClick={() => setPartial({ active: false })}>Deaktivovat</Button>
              <Button variant="ghost" onClick={() => setPartial({ homeScore: 0, awayScore: 0 })}>Reset skóre</Button>
            </HStack>
          </Box>
        </VStack>
      </Box>
    </AdminLayout>
  );
};

export default MobileScoreboardControlPage;
