import React, { useEffect, useMemo, useState } from 'react';
import {
  Box,
  Button,
  FormControl,
  FormLabel,
  Input,
  NumberInput,
  NumberInputField,
  Select,
  SimpleGrid,
  HStack,
  VStack,
  Heading,
  Divider,
  Image,
  useToast,
  Text,
  Switch,
  Badge,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  useColorModeValue,
} from '@chakra-ui/react';
import { CopyIcon } from '@chakra-ui/icons';
import AdminLayout from '@/layouts/AdminLayout';
import ScoreboardPreview from '@/components/scoreboard/ScoreboardPreview';
import {
  getScoreboardState,
  saveScoreboardState,
  updateAdminScoreboard,
  ScoreboardState,
  deriveShort,
  derivePrimaryFromLogo,
  ScoreboardTheme,
  startTimer,
  pauseTimer,
  resetTimer,
} from '@/services/scoreboard';
import { useFacrApi } from '@/hooks/useFacrApi';
import { SearchResult } from '@/services/facr/types';
import { API_URL } from '@/services/api';
import { useQuery } from '@tanstack/react-query';
import { AdminMatch, fetchAdminMatches } from '@/services/adminMatches';
import { getFacrClubInfoCache } from '@/services/facr/cache';

const themes: ScoreboardTheme[] = ['classic', 'pill', 'var1', 'var2', 'var3', 'var4'];

const resolveLogoUrl = (u?: string | null) => {
  if (!u) return undefined;
  if (u.startsWith('/uploads') || u.startsWith('/dist') || u.startsWith('/api/')) return u;
  if (/^https?:\/\//i.test(u)) {
    const base = (API_URL || '').replace(/\/$/, '');
    return `${base}/proxy/image?url=${encodeURIComponent(u)}`;
  }
  return u;
};

const ScoreboardAdminPage: React.FC = () => {
  const cardBg = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.700');
  const inputBg = useColorModeValue('white', 'gray.700');
  const [state, setState] = useState<ScoreboardState | null>(null);
  const [loading, setLoading] = useState(true);
  const toast = useToast();
  const [activeTab, setActiveTab] = useState<number>(0); // 0 upcoming, 1 recent

  // Club search inline (home/away target)
  const [clubQuery, setClubQuery] = useState('');
  const [assignTo, setAssignTo] = useState<'home' | 'away'>('home');
  const { searchClubs, searchResults, searchLoading, searchError } = useFacrApi();

  useEffect(() => {
    (async () => {
      const s = await getScoreboardState();
      setState(s);
      setLoading(false);
    })();
  }, []);

  // Poll while timer is running to reflect live time
  useEffect(() => {
    if (!state?.running) return;
    let mounted = true;
    const id = setInterval(async () => {
      try {
        const s = await getScoreboardState();
        if (mounted) setState(s);
      } catch {}
    }, 1000);
    return () => {
      mounted = false;
      clearInterval(id);
    };
  }, [state?.running]);

  // Load matches for linking
  const { data: adminMatches = [] } = useQuery<AdminMatch[]>({
    queryKey: ['admin-matches'],
    queryFn: fetchAdminMatches,
    staleTime: 60_000,
  });

  // Load competitions/matches from cached FACR blob
  const { data: facrCache } = useQuery<any>({
    queryKey: ['facr-club-info-cache'],
    queryFn: getFacrClubInfoCache,
    staleTime: 120_000,
    refetchInterval: 120_000,
  });

  // Normalize matches from FACR cache to AdminMatch-ish shape
  const facrMatches: AdminMatch[] = useMemo(() => {
    const out: AdminMatch[] = [];
    try {
      const comps = facrCache?.competitions || [];
      for (const c of comps) {
        const cname = String(c?.name || c?.code || '').trim();
        const matches = c?.matches || [];
        for (const m of matches) {
          out.push({
            match_id: m?.match_id || m?.id || '',
            id: m?.match_id || m?.id || '',
            home: m?.home || '',
            away: m?.away || '',
            date_time: m?.date_time || m?.kickoff || '',
            home_logo_url: m?.home_logo_url || '',
            away_logo_url: m?.away_logo_url || '',
            competition: cname,
            league: cname,
          });
        }
      }
    } catch {}
    return out;
  }, [facrCache]);

  // Build competition list from both sources
  const competitions = React.useMemo(() => {
    const set = new Set<string>();
    for (const m of adminMatches) {
      const comp = String(m.competition || m.league || '').trim();
      if (comp) set.add(comp);
    }
    for (const m of facrMatches) {
      const comp = String((m as any).competition || (m as any).league || '').trim();
      if (comp) set.add(comp);
    }
    return ['Vše', ...Array.from(set)];
  }, [adminMatches, facrMatches]);

  const [compFilter, setCompFilter] = useState<string>('Vše');
  const [matchQuery, setMatchQuery] = useState('');

  const parsedMatches = React.useMemo(() => {
    const parseTs = (m: AdminMatch) => {
      const dt = String(m.date_time || m.date || '').slice(0, 16);
      // Accept RFC3339 or "YYYY-MM-DD HH:MM"
      let t = Date.parse(dt);
      if (isNaN(t) && dt.includes(' ')) {
        t = Date.parse(dt.replace(' ', 'T') + ':00');
      }
      return t;
    };
    const now = Date.now();
    let list: AdminMatch[] = [...(adminMatches || []), ...facrMatches];
    if (compFilter && compFilter !== 'Vše') {
      list = list.filter((m) => String((m as any).competition || (m as any).league || '').trim() === compFilter);
    }
    if (matchQuery.trim()) {
      const q = matchQuery.trim().toLowerCase();
      list = list.filter((m) =>
        String(m.home || '').toLowerCase().includes(q) ||
        String(m.away || '').toLowerCase().includes(q) ||
        String((m as any).competition || (m as any).league || '').toLowerCase().includes(q)
      );
    }
    const withTs = list.map((m) => ({ m, ts: parseTs(m) }));
    const upcoming = withTs
      .filter((x) => typeof x.ts === 'number' && !isNaN(x.ts) && x.ts >= now)
      .sort((a, b) => a.ts - b.ts)
      .map((x) => x.m);
    const recent = withTs
      .filter((x) => typeof x.ts === 'number' && !isNaN(x.ts) && x.ts < now)
      .sort((a, b) => b.ts - a.ts)
      .map((x) => x.m);
    return { upcoming, recent };
  }, [adminMatches, facrMatches, compFilter, matchQuery]);

  useEffect(() => {
    const q = clubQuery.trim();
    if (!q) return;
    const t = setTimeout(() => {
      searchClubs(q).catch(() => {});
    }, 400);
    return () => clearTimeout(t);
  }, [clubQuery, searchClubs]);

  const setPartial = async (patch: Partial<ScoreboardState>) => {
    const next = await saveScoreboardState(patch);
    setState(next);
  };

  const applyMatch = async (m: AdminMatch) => {
    if (!state) return;
    // Populate names, logos and short codes
    const homeName = String(m.home || m.home_team || '').trim();
    const awayName = String(m.away || m.away_team || '').trim();
    const homeLogo = resolveLogoUrl(m.home_logo_url || '') || '';
    const awayLogo = resolveLogoUrl(m.away_logo_url || '') || '';
    const updates: Partial<ScoreboardState> = {
      homeName,
      awayName,
      homeShort: deriveShort(homeName),
      awayShort: deriveShort(awayName),
      homeLogo: homeLogo || state.homeLogo,
      awayLogo: awayLogo || state.awayLogo,
      externalMatchId: String(m.match_id || m.id || ''),
    };
    // Try to detect colors from logos
    const [cHome, cAway] = await Promise.all([
      derivePrimaryFromLogo(homeLogo || state.homeLogo),
      derivePrimaryFromLogo(awayLogo || state.awayLogo),
    ]);
    if (cHome) updates.primaryColor = cHome;
    if (cAway) updates.secondaryColor = cAway;
    const next = await saveScoreboardState(updates);
    setState(next);
    toast({ title: 'Zápas vybrán', description: 'Základní údaje byly předvyplněny.', status: 'success' });
  };

  const applyClub = async (club: SearchResult) => {
    const logo = resolveLogoUrl(club.logo_url) || undefined;
    const color = await derivePrimaryFromLogo(logo || undefined);
    if (assignTo === 'home') {
      await setPartial({
        homeName: club.name || 'DOMÁCÍ',
        homeShort: deriveShort(club.name || ''),
        homeLogo: logo,
        primaryColor: color || state?.primaryColor,
      });
    } else {
      await setPartial({
        awayName: club.name || 'HOSTÉ',
        awayShort: deriveShort(club.name || ''),
        awayLogo: logo,
        secondaryColor: color || state?.secondaryColor,
      });
    }
    toast({ title: `Nastaveno pro ${assignTo === 'home' ? 'domácí' : 'hosty'}`, status: 'success' });
  };

  if (loading || !state) return (
    <AdminLayout>
      <Box>Načítání…</Box>
    </AdminLayout>
  );

  return (
    <AdminLayout>
      <Box>
        <Heading size="lg" mb={2}>Tabule (Scoreboard)</Heading>
        <Text color="gray.500" mb={2}>Napojte tabuli na konkrétní zápas a ovládejte skóre v reálném čase. Pokud je tabule aktivní a propojená se zápasem, propisujeme živé skóre i do veřejné homepage.</Text>
        <HStack spacing={3} mb={4}>
          <Badge colorScheme="green">OBS</Badge>
          {(() => { const href = (typeof window !== 'undefined' ? window.location.origin.replace(/\/$/, '') : '') + '/overlay/scoreboard'; return (
            <>
              <Button as="a" href={href} target="_blank" rel="noreferrer">Otevřít overlay</Button>
              <HStack spacing={2}>
                <Text fontSize="sm" color="gray.500">Veřejná URL pro OBS: {href}</Text>
                <Button size="sm" leftIcon={<CopyIcon />} onClick={() => { try { navigator.clipboard.writeText(href); } catch (_) {} }}>Kopírovat</Button>
              </HStack>
            </>
          ); })()}
        </HStack>

        {/* Match linking (initial element) */}
        <Box borderWidth="1px" borderRadius="lg" p={4} bg={cardBg} mb={6}>
          <Heading size="md" mb={3}>Napojení na zápas (FAČR)</Heading>
          <SimpleGrid columns={{ base: 1, md: 3 }} spacing={3} mb={3}>
            <FormControl>
              <FormLabel>Soutěž</FormLabel>
              <Select value={compFilter} onChange={(e) => setCompFilter(e.target.value)}>
                {competitions.map((c) => (<option key={c} value={c}>{c}</option>))}
              </Select>
            </FormControl>
            <FormControl>
              <FormLabel>Hledat zápas</FormLabel>
              <Input placeholder="Hledat podle názvu týmu nebo soutěže" value={matchQuery} onChange={(e)=>setMatchQuery(e.target.value)} />
            </FormControl>
            <FormControl display="flex" alignItems="center">
              <FormLabel mb={0}>Tabule aktivní</FormLabel>
              <Switch isChecked={!!state?.active} onChange={async (e) => {
                const next = await saveScoreboardState({ active: e.target.checked });
                setState(next);
              }} />
              {state?.externalMatchId ? <Badge ml={3} colorScheme="blue">Zápas: {state.externalMatchId}</Badge> : <Badge ml={3}>Bez zápasu</Badge>}
            </FormControl>
          </SimpleGrid>

          <Tabs index={activeTab} onChange={setActiveTab} variant="enclosed" size="sm">
            <TabList>
              <Tab>Nadcházející</Tab>
              <Tab>Nedávné</Tab>
            </TabList>
            <TabPanels>
              <TabPanel px={0}>
                <VStack align="stretch" spacing={2} maxH="320px" overflowY="auto">
                  {parsedMatches.upcoming.map((m) => (
                    <HStack key={`${m.match_id || m.id}`} spacing={3} p={2} borderWidth="1px" borderRadius="md" _hover={{ bg: 'gray.50' }}>
                      {m.home_logo_url ? <Image src={resolveLogoUrl(m.home_logo_url)} alt={String(m.home)} boxSize="28px" objectFit="contain" /> : null}
                      <Text fontWeight="semibold">{String(m.home)} vs {String(m.away)}</Text>
                      <Badge ml="auto">{String(m.date_time || m.date || '').slice(0,16).replace('T',' ')}</Badge>
                      <Button size="sm" onClick={() => applyMatch(m)}>Vybrat zápas</Button>
                    </HStack>
                  ))}
                </VStack>
              </TabPanel>
              <TabPanel px={0}>
                <VStack align="stretch" spacing={2} maxH="320px" overflowY="auto">
                  {parsedMatches.recent.map((m) => (
                    <HStack key={`${m.match_id || m.id}`} spacing={3} p={2} borderWidth="1px" borderRadius="md" _hover={{ bg: 'gray.50' }}>
                      {m.home_logo_url ? <Image src={resolveLogoUrl(m.home_logo_url)} alt={String(m.home)} boxSize="28px" objectFit="contain" /> : null}
                      <Text fontWeight="semibold">{String(m.home)} vs {String(m.away)}</Text>
                      <Badge ml="auto" colorScheme="purple">{String(m.date_time || m.date || '').slice(0,16).replace('T',' ')}</Badge>
                      <Button size="sm" variant="outline" onClick={() => applyMatch(m)}>Vybrat zápas</Button>
                    </HStack>
                  ))}
                </VStack>
              </TabPanel>
            </TabPanels>
          </Tabs>

          <HStack mt={3}>
            <Button
              colorScheme="blue"
              onClick={async () => {
                if (!state?.externalMatchId) { toast({ title: 'Zvolte zápas', description: 'Nejprve vyberte zápas ze seznamu výše.', status: 'warning' }); return; }
                const next = await saveScoreboardState({ active: true });
                setState(next);
                toast({ title: 'Tabule aktivována', description: 'Živá data se budou propsat i na homepage.', status: 'success' });
              }}
            >Aktivovat pro vybraný zápas</Button>
            <Button
              variant="ghost"
              onClick={async () => {
                const next = await saveScoreboardState({ externalMatchId: '', active: false });
                setState(next);
                toast({ title: 'Odpojeno', description: 'Tabule odpojena od zápasu.', status: 'info' });
              }}
            >Odpojit od zápasu</Button>
          </HStack>
        </Box>

        {/* Live preview */}
        <Box display="flex" justifyContent="center" mb={6}>
          <ScoreboardPreview state={state} />
        </Box>

        <SimpleGrid columns={{ base: 1, md: 2 }} spacing={6}>
          <Box>
            <Heading size="md" mb={3}>Základní údaje</Heading>
            <SimpleGrid columns={2} spacing={4}>
              <FormControl>
                <FormLabel>Domácí tým</FormLabel>
                <Input
                  value={state.homeName}
                  onChange={async (e) => {
                    const v = e.target.value;
                    await setPartial({ homeName: v, homeShort: state.homeShort?.trim() ? state.homeShort : deriveShort(v) });
                  }}
                />
              </FormControl>
              <FormControl>
                <FormLabel>Zkratka domácích</FormLabel>
                <Input
                  value={state.homeShort || ''}
                  maxLength={3}
                  onChange={async (e) => {
                    await setPartial({ homeShort: e.target.value.toUpperCase().slice(0,3) });
                  }}
                />
              </FormControl>
              <FormControl>
                <FormLabel>Hostující tým</FormLabel>
                <Input
                  value={state.awayName}
                  onChange={async (e) => {
                    const v = e.target.value;
                    await setPartial({ awayName: v, awayShort: state.awayShort?.trim() ? state.awayShort : deriveShort(v) });
                  }}
                />
              </FormControl>
              <FormControl>
                <FormLabel>Zkratka hostů</FormLabel>
                <Input
                  value={state.awayShort || ''}
                  maxLength={3}
                  onChange={async (e) => {
                    await setPartial({ awayShort: e.target.value.toUpperCase().slice(0,3) });
                  }}
                />
              </FormControl>
              <FormControl>
                <FormLabel>Logo domácích (URL)</FormLabel>
                <Input
                  value={state.homeLogo || ''}
                  onChange={async (e) => {
                    await setPartial({ homeLogo: e.target.value });
                  }}
                />
              </FormControl>
              <FormControl>
                <FormLabel>Logo hostů (URL)</FormLabel>
                <Input
                  value={state.awayLogo || ''}
                  onChange={async (e) => {
                    await setPartial({ awayLogo: e.target.value });
                  }}
                />
              </FormControl>
              <FormControl>
                <FormLabel>Skóre domácích</FormLabel>
                <NumberInput value={state.homeScore} min={0} onChange={async (_, n) => setPartial({ homeScore: Number.isFinite(n) ? n : 0 })}>
                  <NumberInputField />
                </NumberInput>
              </FormControl>
              <FormControl>
                <FormLabel>Skóre hostů</FormLabel>
                <NumberInput value={state.awayScore} min={0} onChange={async (_, n) => setPartial({ awayScore: Number.isFinite(n) ? n : 0 })}>
                  <NumberInputField />
                </NumberInput>
              </FormControl>
              <FormControl>
                <FormLabel>Délka poločasu (min)</FormLabel>
                <NumberInput value={state.halfLength} min={1} max={60} onChange={async (_, n) => setPartial({ halfLength: Number.isFinite(n) ? n : 45 })}>
                  <NumberInputField />
                </NumberInput>
              </FormControl>
              <FormControl>
                <FormLabel>Styl</FormLabel>
                <Select value={state.theme} onChange={async (e) => setPartial({ theme: e.target.value as ScoreboardTheme })}>
                  {themes.map((t) => (
                    <option key={t} value={t}>{t}</option>
                  ))}
                </Select>
              </FormControl>
            </SimpleGrid>
          </Box>

          <Box>
            <Heading size="md" mb={3}>Barvy a vyhledání klubu</Heading>
            <SimpleGrid columns={2} spacing={4}>
              <FormControl>
                <FormLabel>Barva domácích</FormLabel>
                <Input type="color" value={state.primaryColor || '#1e3a8a'} onChange={async (e) => setPartial({ primaryColor: e.target.value })} />
              </FormControl>
              <FormControl>
                <FormLabel>Barva hostů</FormLabel>
                <Input type="color" value={state.secondaryColor || '#2563eb'} onChange={async (e) => setPartial({ secondaryColor: e.target.value })} />
              </FormControl>
            </SimpleGrid>

            <Divider my={4} />
            <HStack spacing={3} align="flex-start">
              <Select value={assignTo} onChange={(e) => setAssignTo((e.target.value as 'home'|'away') || 'home')} maxW="160px">
                <option value="home">Nastavit domácí</option>
                <option value="away">Nastavit hosty</option>
              </Select>
              <Input placeholder="Hledat klub (FAČR)" value={clubQuery} onChange={(e) => setClubQuery(e.target.value)} />
              <Button isLoading={searchLoading} onClick={() => clubQuery.trim() && searchClubs(clubQuery.trim())}>Hledat</Button>
            </HStack>
            {searchError ? (
              <Text color="red.500" mt={2}>Chyba vyhledávání: {searchError.message}</Text>
            ) : null}
            <VStack align="stretch" spacing={2} mt={3} maxH="260px" overflowY="auto">
              {searchResults?.slice(0, 8).map((r) => (
                <HStack key={`${r.club_type}-${r.club_id}`} spacing={3} p={2} borderWidth="1px" borderRadius="md" _hover={{ bg: 'gray.50' }} cursor="pointer" onClick={() => applyClub(r)}>
                  {r.logo_url ? <Image src={resolveLogoUrl(r.logo_url)} alt={r.name} boxSize="28px" objectFit="contain" /> : null}
                  <Box>
                    <Text fontWeight="medium">{r.name}</Text>
                    <Text fontSize="sm" color="gray.500">{r.club_type}</Text>
                  </Box>
                </HStack>
              ))}
            </VStack>
          </Box>
        </SimpleGrid>

        <Divider my={6} />

        <HStack spacing={3}>
          <Button onClick={() => setPartial({ homeScore: (state.homeScore || 0) + 1 })}>+ Gól DOM</Button>
          <Button onClick={() => setPartial({ homeScore: Math.max(0, (state.homeScore || 0) - 1) })}>− Gól DOM</Button>
          <Button onClick={() => setPartial({ awayScore: (state.awayScore || 0) + 1 })}>+ Gól HOS</Button>
          <Button onClick={() => setPartial({ awayScore: Math.max(0, (state.awayScore || 0) - 1) })}>− Gól HOS</Button>
          <Button variant="outline" onClick={() => setPartial({ homeScore: 0, awayScore: 0 })}>Reset skóre</Button>
        </HStack>

        <Divider my={6} />

        {/* Timer controls */}
        <Box borderWidth="1px" borderRadius="lg" p={4} bg={cardBg} mb={6}>
          <Heading size="md" mb={3}>Časovač</Heading>
          <HStack spacing={4} align="center" flexWrap="wrap">
            <Text fontSize="4xl" fontFamily="mono" minW="120px">{state.timer || '00:00'}</Text>
            {state.running ? (
              <Badge colorScheme="green">Běží</Badge>
            ) : (
              <Badge>Stojí</Badge>
            )}
            <HStack>
              <Button colorScheme="green" onClick={async () => {
                await startTimer();
                const s = await getScoreboardState();
                setState(s);
              }}>Start</Button>
              <Button onClick={async () => {
                await pauseTimer();
                const s = await getScoreboardState();
                setState(s);
              }}>Pauza</Button>
              <Button variant="outline" onClick={async () => {
                await resetTimer();
                const s = await getScoreboardState();
                setState(s);
              }}>Reset</Button>
            </HStack>
          </HStack>
          <HStack mt={3} spacing={3} align="center">
            <FormControl maxW="160px" isDisabled={!!state.running}>
              <FormLabel>Nastavit čas (MM:SS)</FormLabel>
              <Input
                value={state.timer || '00:00'}
                onChange={async (e) => {
                  const v = e.target.value.trim();
                  // allow edit only when not running
                  if (!state.running) {
                    const next = await saveScoreboardState({ timer: v });
                    setState(next);
                  }
                }}
              />
            </FormControl>
          </HStack>
        </Box>

        <Heading size="md" mb={3}>Import / Export</Heading>
        <HStack spacing={4} align="center" flexWrap="wrap">
          <Button
            onClick={() => {
              try {
                const blob = new Blob([JSON.stringify(state, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'scoreboard-state.json';
                a.click();
                URL.revokeObjectURL(url);
              } catch (e) {
                toast({ title: 'Export selhal', status: 'error' });
              }
            }}
          >Exportovat JSON</Button>
          <Button as="label">
            Importovat JSON
            <Input type="file" accept="application/json" display="none" onChange={async (e) => {
              try {
                const f = e.target.files?.[0];
                if (!f) return;
                const text = await f.text();
                const data = JSON.parse(text);
                // Patch via admin API when possible
                await updateAdminScoreboard(data);
                setState(await getScoreboardState());
                toast({ title: 'Import dokončen', status: 'success' });
              } catch (err: any) {
                toast({ title: 'Import selhal', description: err?.message || 'Neplatný soubor', status: 'error' });
              } finally {
                try { if (e.target) (e.target as HTMLInputElement).value = ''; } catch {}
              }
            }} />
          </Button>
        </HStack>

        <Divider my={8} />
        <Heading size="md" mb={2}>Návod k použití (CZ)</Heading>
        <VStack align="start" spacing={2} color="gray.700">
          <Text>1) V horní části vyberte soutěž, případně vyhledejte zápas podle názvu týmu. Klikněte na „Vybrat zápas“.</Text>
          <Text>2) Pole „Domácí/Hosté“, loga a zkratky se předvyplní. Barvy se pokusíme odhadnout z log.</Text>
          <Text>3) Zapněte přepínač „Tabule aktivní“ nebo použijte tlačítko „Aktivovat pro vybraný zápas“.</Text>
          <Text>4) Skóre upravujte tlačítky níže nebo ručním zadáním. Změny se ukládají průběžně.</Text>
          <Text>5) Pokud je tabule aktivní a propojená se zápasem, živé skóre se propisuje do veřejné homepage (nejbližší zápas) a do JSON cache.</Text>
          <Text>6) Přepněte vzhled tabule (styl) dle potřeby. Pro přenos do streamu použijte veřejnou adresu /overlay/scoreboard.</Text>
          <Text>Tip: Při importu JSON použijte předchozí export, formát je kompatibilní.</Text>
        </VStack>
      </Box>
    </AdminLayout>
  );
};

export default ScoreboardAdminPage;
