import { Box, Text, VStack, HStack, Badge, Icon, Spinner, Alert, AlertIcon, Image, Input, Button, useToast } from '@chakra-ui/react';
import React, { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { FaCalendarAlt, FaFutbol, FaExclamationTriangle, FaMapMarkerAlt } from 'react-icons/fa';
import { useQuery } from '@tanstack/react-query';
import { api } from '../../services/api';
import { useSettings } from '@/hooks/useSettings';
import { Widget } from './Widget';
import { format, parse, isToday, isTomorrow, isAfter } from 'date-fns';
import { cs } from 'date-fns/locale';
import { Match } from '../../types';
import { fetchTeamLogoOverrides } from '@/services/adminMatches';
import { assetUrl, sanitizeClubName } from '@/utils/url';
import { TeamLogo } from '../common/TeamLogo';
import '../../styles/logos.css';

const FACR_DATE_FMT = 'dd.MM.yyyy HH:mm';

const formatMatchDate = (dateString: string) => {
  try {
    // Parse FACR date format from cache JSON (e.g., "17.08.2025 15:00")
    const date = parse(dateString, FACR_DATE_FMT, new Date());
    
    if (isToday(date)) {
      return format(date, 'HH:mm');
    } else if (isTomorrow(date)) {
      return format(date, "HH:mm '(zítra)'");
    } else {
      return format(date, 'dd.MM. HH:mm');
    }
  } catch (error) {
    console.error('Error formatting date:', error, dateString);
    return dateString;
  }
};

export const MatchesWidget = () => {
  const toast = useToast();
  const [email, setEmail] = useState<string>('');
  const [prefWeekly, setPrefWeekly] = useState<boolean>(true);
  const [prefMatches, setPrefMatches] = useState<boolean>(true);
  const [subscribing, setSubscribing] = useState<boolean>(false);
  const location = useLocation();
  const isAdminRoute = String(location.pathname || '').startsWith('/admin');

  const resolveUrl = (path: string) => {
    try {
      if (/^https?:\/\//i.test(path)) return path;
      const apiUrl = process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1';
      const origin = new URL(apiUrl).origin;
      return origin + path;
    } catch {
      return path;
    }
  };

  const subscribe = async () => {
    if (!email) {
      toast({ title: 'Zadejte email', status: 'warning' });
      return;
    }
    setSubscribing(true);
    try {
      const res = await fetch(resolveUrl('/api/v1/newsletter/subscribe'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, preferences: { weekly: prefWeekly, matches: prefMatches } })
      });
      if (!res.ok) {
        const jt = await res.json().catch(() => ({} as any));
        throw new Error(jt?.error || `HTTP ${res.status}`);
      }
      toast({ title: 'Přihlášeno k odběru', status: 'success' });
      setEmail('');
    } catch (e: any) {
      toast({ title: 'Chyba přihlášení', description: e?.message || String(e), status: 'error' });
    } finally {
      setSubscribing(false);
    }
  };
  const { settings } = useSettings();
  const { data: overrides = {} } = useQuery({
    queryKey: ['teamLogoOverrides'],
    queryFn: fetchTeamLogoOverrides,
    staleTime: 5 * 60 * 1000,
  });
  const getLogo = (teamName?: string, original?: string) => {
    const byName = (overrides as any)?.by_name || {} as Record<string, string>;
    const norm = (s: string) => String(s || '')
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .replace(/\s+/g, ' ')
      .trim()
      .toLowerCase();
    const stripPrefixes = (s: string) => {
      let x = norm(s);
      x = x.replace(/\b(mestsky|m\.?f\.?k\.?|mfk|tj|sk|sokol|fotbalovy|fotbalový|fotbalovy\s+klub|fotbalovy\s+klub)\b/g, '');
      return x.replace(/\s+/g, ' ').trim();
    };
    const byNameNorm: Record<string, string> = Object.keys(byName || {}).reduce((acc: Record<string, string>, k) => { acc[norm(k)] = byName[k]; return acc; }, {});
    const strippedPairs = Object.keys(byName || {}).map((k) => ({ key: stripPrefixes(k), url: byName[k] }));
    const pick = (name?: string, orig?: string) => {
      if (!name) return orig;
      const exact = byName[name];
      let candidate = exact || byNameNorm[norm(name)];
      if (!candidate) {
        const s = stripPrefixes(name);
        for (const { key, url } of strippedPairs) { if (key && (s.endsWith(key) || key.endsWith(s))) { candidate = url; break; } }
      }
      const chosen = candidate || orig;
      if (typeof chosen === 'string' && chosen.startsWith('/')) {
        const apiUrl = process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1';
        const origin = new URL(apiUrl).origin;
        return origin + chosen;
      }
      return chosen || (assetUrl('/dist/img/logo-club-empty.svg') as string);
    };
    return pick(teamName, original);
  };
  
  const { data: matches = [], isLoading, error } = useQuery<Match[]>({
    queryKey: ['upcomingMatchesCache'],
    queryFn: async () => {
      // Build absolute origin from API URL env (which may include /api/v1)
      const apiUrl = process.env.REACT_APP_API_URL || 'http://localhost:8080/api/v1';
      const origin = new URL(apiUrl).origin;
      const url = `${origin}/cache/prefetch/facr_club_info.json`;

      const res = await fetch(url, { headers: { 'Cache-Control': 'no-cache' } });
      if (!res.ok) throw new Error(`Failed to load cache: ${res.status}`);
      const json = await res.json();

      // Flatten competitions -> matches, enrich with competition name
      const comps = Array.isArray(json?.competitions) ? json.competitions : [];
      const items: any[] = comps.flatMap((c: any) =>
        (Array.isArray(c.matches) ? c.matches : []).map((m: any) => ({ ...m, competitionName: c.name, competition_id: c.id }))
      );

      // Parse, filter for future, sort ascending, take next 5
      const now = new Date();
      const upcoming = items
        .map((m) => ({
          ...m,
          __dt: parse(String(m.date_time || m.date), FACR_DATE_FMT, new Date()),
        }))
        .filter((m) => isAfter(m.__dt, now))
        .sort((a, b) => a.__dt.getTime() - b.__dt.getTime())
        .slice(0, 5)
        .map((m) => ({
          id: m.match_id,
          date_time: m.date_time || m.date,
          competitionName: m.competitionName,
          home: m.home || m.home_team,
          away: m.away || m.away_team,
          score: m.score,
          venue: m.venue,
          home_logo_url: getLogo(m.home || m.home_team, m.home_logo_url),
          away_logo_url: getLogo(m.away || m.away_team, m.away_logo_url),
        })) as Match[];

      return upcoming;
    },
  });

  if (isLoading) {
    return (
      <Widget title="Nadcházející zápasy">
        <VStack p={4}>
          <Spinner size="md" />
          <Text>Načítám zápasy...</Text>
        </VStack>
      </Widget>
    );
  }

  if (error) {
    return (
      <Widget title="Nadcházející zápasy">
        <Alert status="error" variant="left-accent">
          <AlertIcon />
          Nepodařilo se načíst zápasy. Zkuste to prosím později.
        </Alert>
      </Widget>
    );
  }

  if (!matches || matches.length === 0) {
    return (
      <Widget title="Nadcházející zápasy">
        <VStack p={4} spacing={4}>
          <Icon as={FaCalendarAlt} boxSize={8} color="gray.400" />
          <Text color="gray.500" textAlign="center">
            Žádné nadcházející zápasy nebyly nalezeny.
          </Text>
        </VStack>
      </Widget>
    );
  }

  return (
    <Widget title="Nadcházející zápasy">
      <VStack spacing={{ base: 2, md: 3 }} align="stretch" divider={<Box borderBottomWidth="1px" borderColor="gray.200" />}>
        {matches.map((match) => (
          <Box 
            key={match.id} 
            p={{ base: 3, md: 4 }} 
            bg="gray.50"
            _hover={{ bg: 'gray.100' }} 
            borderRadius="lg"
            transition="background-color 0.2s"
            shadow="sm"
          >
            <HStack justify="space-between" mb={1} spacing={2} flexWrap="wrap">
              <Text 
                fontSize={{ base: 'xs', sm: 'sm' }} 
                color="gray.700" 
                fontWeight="medium"
                whiteSpace="nowrap"
              >
                {formatMatchDate(match.date_time)}
              </Text>
              <Badge 
                colorScheme="blue" 
                variant="subtle" 
                fontSize="xs"
                bg="blue.50"
                color="blue.700"
              >
                {match.competitionName}
              </Badge>
            </HStack>
            
            <HStack justify="space-between" align="center">
              <HStack flex={1} minW={0} spacing={2}>
                <Box flexShrink={0} className="match-widget-logo">
                  <TeamLogo
                    teamId={(match as any).home_id}
                    teamName={match.home}
                    facrLogo={match.home_logo_url}
                    size="small"
                    fallbackIcon={<Icon as={FaFutbol} color="gray.400" boxSize={{ base: 4, md: 5 }} />}
                  />
                </Box>
                <Text 
                  fontSize={{ base: 'xs', sm: 'sm' }} 
                  fontWeight="medium" 
                  isTruncated
                  color="gray.800"
                >
                  {sanitizeClubName(match.home)}
                </Text>
              </HStack>
              <Text 
                fontSize={{ base: 'xs', sm: 'sm' }} 
                fontWeight="bold" 
                minW={{ base: '32px', sm: '40px' }} 
                textAlign="center"
                color="gray.900"
                flexShrink={0}
              >
                {match.score || 'vs'}
              </Text>
              <HStack flex={1} justify="flex-end" spacing={2} minW={0}>
                <Text 
                  fontSize={{ base: 'xs', sm: 'sm' }} 
                  fontWeight="medium" 
                  isTruncated 
                  textAlign="right"
                  color="gray.800"
                >
                  {sanitizeClubName(match.away)}
                </Text>
                <Box flexShrink={0} className="match-widget-logo">
                  <TeamLogo
                    teamId={(match as any).away_id}
                    teamName={match.away}
                    facrLogo={match.away_logo_url}
                    size="small"
                    fallbackIcon={<Icon as={FaFutbol} color="gray.400" boxSize={{ base: 4, md: 5 }} />}
                  />
                </Box>
              </HStack>
            </HStack>
            
            {match.venue && (
              <HStack mt={2} spacing={2} color="gray.500" fontSize="sm">
                <Icon as={FaMapMarkerAlt} boxSize={3} />
                <Text isTruncated>{match.venue}</Text>
              </HStack>
            )}
          </Box>
        ))}
        {/* Fan subscription form (hidden on admin pages) */}
        {!isAdminRoute && (
          <VStack p={3} spacing={2} align="stretch">
            <Text fontSize="sm" color="gray.600">Chcete dostávat novinky o zápasech e‑mailem?</Text>
            <HStack>
              <Input type="email" placeholder="váš@email.cz" value={email} onChange={(e) => setEmail(e.target.value)} />
              <Button colorScheme="red" onClick={subscribe} isLoading={subscribing}>Odebírat</Button>
            </HStack>
          </VStack>
        )}
      </VStack>
    </Widget>
  );
};
