import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { cs } from 'date-fns/locale';
import {
  Box,
  Text,
  VStack,
  HStack,
  Skeleton,
  Stat,
  StatLabel,
  StatNumber,
  StatHelpText,
  useColorModeValue,
  Icon,
} from '@chakra-ui/react';
import { FaChartLine, FaArrowUp, FaArrowDown } from 'react-icons/fa';
import { Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
} from 'chart.js';
import { api } from '@/services/api';
import { Widget } from './Widget';

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
);



interface ChartDataset {
  label: string;
  data: number[];
  borderColor: string;
  backgroundColor: string;
  tension: number;
  fill: boolean;
}

interface VisitorStats {
  totalVisitors: number;
  changePercentage: number;
  chartData: {
    labels: string[];
    datasets: ChartDataset[];
  };
}

export const VisitorsWidget = () => {
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const bgColor = useColorModeValue('white', 'gray.700');
  const textColor = useColorModeValue('gray.600', 'gray.300');

  const { data: stats, isLoading, error } = useQuery<VisitorStats>({
    queryKey: ['analytics', 'visitors'],
    queryFn: async () => {
      try {
        const { data } = await api.get('/analytics/visitors', {
          params: {
            days: 30,
            groupBy: 'day'
          }
        });
        return data;
      } catch (err) {
        console.error('Error fetching visitor stats:', err);
        // Return mock data in case of error
        return generateMockData();
      }
    },
    staleTime: 15 * 60 * 1000, // 15 minutes
  });

  const changePercentage = stats?.changePercentage ?? 0;
  const isPositiveChange = changePercentage >= 0;

  const chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        mode: 'index' as const,
        intersect: false,
        backgroundColor: useColorModeValue('white', 'gray.800'),
        titleColor: textColor,
        bodyColor: textColor,
        borderColor: borderColor,
        borderWidth: 1,
        padding: 12,
        boxShadow: 'lg',
        callbacks: {
          label: (context: { parsed: { y: number } }) => {
            return `${context.parsed.y} návštěv`;
          },
        },
      },
    },
    scales: {
      x: {
        grid: {
          display: false,
        },
        ticks: {
          color: textColor,
          maxRotation: 0,
          autoSkip: true,
          maxTicksLimit: 7,
        },
        border: {
          display: false,
        },
      },
      y: {
        beginAtZero: true,
        grid: {
          borderDash: [3, 3],
          color: borderColor,
        },
        ticks: {
          color: textColor,
          precision: 0,
        },
        border: {
          display: false,
        },
      },
    },
    elements: {
      point: {
        radius: 0,
        hoverRadius: 6,
        hoverBorderWidth: 2,
      },
      line: {
        borderWidth: 2,
        tension: 0.3,
      },
    },
  };

  // Generate mock data for the chart
  const generateMockData = (): VisitorStats => {
    const labels = Array.from({ length: 30 }, (_, i) => {
      const date = new Date();
      date.setDate(date.getDate() - (29 - i));
      return format(date, 'd. M.', { locale: cs });
    });

    const baseData = Array.from({ length: 30 }, (_, i) => {
      const base = 50 + Math.floor(Math.random() * 50);
      const dayOfWeek = new Date().getDay();
      const dayFactor = dayOfWeek >= 5 ? 0.7 : 1.0;
      return Math.floor(base * dayFactor);
    });

    return {
      totalVisitors: baseData.reduce((sum, val) => sum + val, 0),
      changePercentage: 12.5,
      chartData: {
        labels,
        datasets: [
          {
            label: 'Návštěvníci',
            data: baseData,
            borderColor: 'rgba(66, 153, 225, 1)',
            backgroundColor: 'rgba(66, 153, 225, 0.5)',
            tension: 0.3,
            fill: true,
          },
        ],
      },
    };
  };

  if (isLoading) {
    return (
      <Widget title="Návštěvnost" icon={FaChartLine}>
        <VStack spacing={4}>
          <Skeleton height="200px" width="100%" borderRadius="md" />
          <HStack width="100%" justify="space-between">
            <Skeleton height="60px" flex={1} mr={2} />
            <Skeleton height="60px" flex={1} />
          </HStack>
        </VStack>
      </Widget>
    );
  }


  // Use mock data if stats is not available
  const displayStats = stats || generateMockData();

  return (
    <Widget title="Návštěvnost" icon={FaChartLine}>
      <VStack spacing={4} align="stretch">
        <Stat>
          <HStack justify="space-between">
            <Box>
              <StatLabel color={textColor}>Celkem návštěv</StatLabel>
              <StatNumber fontSize="2xl">
                {new Intl.NumberFormat('cs-CZ').format(displayStats.totalVisitors)}
              </StatNumber>
            </Box>
            <Box
              bg={isPositiveChange ? 'green.50' : 'red.50'}
              _dark={{
                bg: isPositiveChange ? 'green.900' : 'red.900',
                color: isPositiveChange ? 'green.200' : 'red.200',
              }}
              color={isPositiveChange ? 'green.600' : 'red.600'}
              px={3}
              py={1.5}
              borderRadius="full"
              display="flex"
              alignItems="center"
            >
              {isPositiveChange ? (
                <Icon as={FaArrowUp} mr={1} />
              ) : (
                <Icon as={FaArrowDown} mr={1} />
              )}
              <Text fontSize="sm" fontWeight="medium">
                {Math.abs(changePercentage)}%
              </Text>
            </Box>
          </HStack>
          <StatHelpText color={textColor}>Za posledních 30 dní</StatHelpText>
        </Stat>

        <Box height="200px" mt={4}>
          <Line data={displayStats.chartData} options={chartOptions} />
        </Box>
        
        {!stats && (
          <Box width="100%" textAlign="center" mt={2}>
            <Text fontSize="xs" color="gray.500">
              <Icon as={FaChartLine} mr={1} />
              Zobrazují se ukázková data
            </Text>
          </Box>
        )}
      </VStack>
    </Widget>
  );
};
