import React, { useMemo, useState, useEffect } from 'react';
import Card from '@/components/Card';
import UniformityBarChart from '@/components/pages/production/uniformity/chart/UniformityBarChart';
import UniformityGaugeChart from '@/components/pages/production/uniformity/chart/UniformityGaugeChart';
import UniformityBarChartSkeleton from '@/components/pages/production/uniformity/skeleton/UniformityBarChartSkeleton';
import UniformityGaugeChartSkeleton from '@/components/pages/production/uniformity/skeleton/UniformityGaugeChartSkeleton';
import { Uniformity, type ChartData } from '@/types/api/production/uniformity';
import { Icon } from '@iconify/react';

interface UniformityChartProps {
  uniformityData?: Uniformity | null;
  isFiltered?: boolean;
}

const UniformityChart = ({
  uniformityData,
  isFiltered = false,
}: UniformityChartProps) => {
  const [currentWeekIndex, setCurrentWeekIndex] = useState(0);

  const chartData = useMemo((): ChartData | undefined => {
    if (!uniformityData?.chart_data) return undefined;
    return uniformityData.chart_data;
  }, [uniformityData]);

  useEffect(() => {
    if (uniformityData?.chart_data?.gauge_chart?.week_info) {
      const { current_week_index } =
        uniformityData.chart_data.gauge_chart.week_info;
      setCurrentWeekIndex(current_week_index);
    }
  }, [uniformityData]);

  const barChartData = useMemo(() => {
    if (!chartData?.bar_chart || !chartData?.gauge_chart) {
      return [];
    }

    const { bar_chart, gauge_chart } = chartData;
    const currentWeekData = gauge_chart.available_weeks[currentWeekIndex];

    if (!currentWeekData || !currentWeekData.has_data) {
      return [];
    }

    const currentWeekStr = String(currentWeekData.week);
    const weekData = bar_chart.all_weeks[currentWeekStr];

    if (!weekData || !weekData.has_data) {
      return [];
    }

    return weekData.weight_distribution.map((range) => ({
      name: range.range,
      uv: range.bird_count,
      isIdeal: range.is_ideal_range,
      idealRange: range.ideal_range,
      outsideRange: range.outside_range,
    }));
  }, [chartData, currentWeekIndex]);

  const gaugeChartData = useMemo(() => {
    if (!chartData?.gauge_chart || !uniformityData) return undefined;

    const { gauge_chart } = chartData;
    const currentWeekData = gauge_chart.available_weeks[currentWeekIndex];

    if (!currentWeekData || !currentWeekData.has_data) {
      return undefined;
    }

    const hasPrevWeek = currentWeekIndex > 0;
    const hasNextWeek =
      currentWeekIndex < gauge_chart.available_weeks.length - 1;

    return {
      value: currentWeekData.uniformity_percentage,
      label: 'Uniformity',
      week: `Week ${currentWeekData.week}`,
      currentValue: currentWeekData.ideal_count,
      totalValue: currentWeekData.total_count,
      hasPrevWeek,
      hasNextWeek,
    };
  }, [chartData, currentWeekIndex, uniformityData]);

  const handleWeekChange = (direction: 'prev' | 'next') => {
    if (!chartData?.gauge_chart) return;

    const { available_weeks } = chartData.gauge_chart;

    if (direction === 'prev' && currentWeekIndex > 0) {
      setCurrentWeekIndex((prev) => prev - 1);
    } else if (
      direction === 'next' &&
      currentWeekIndex < available_weeks.length - 1
    ) {
      setCurrentWeekIndex((prev) => prev + 1);
    }
  };

  const shouldShowEmptyState = !isFiltered;

  return (
    <section className='w-full grid grid-cols-1 xl:grid-cols-2 2xl:grid-cols-[1fr_350px] gap-3'>
      <Card
        variant='bordered'
        className={{
          wrapper:
            '2xl:col-span-1 w-full rounded-xl border border-base-content/10',
          body: 'h-96 p-4',
        }}
      >
        <div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-3'>
          <div className='text-base font-semibold leading-7 flex gap-3 items-center'>
            Performance Overview{' '}
            <Icon
              icon='heroicons:information-circle'
              width={20}
              height={20}
              className='inline text-neutral-500'
            />
          </div>
        </div>
        <div className='w-full h-full flex items-center justify-center'>
          {shouldShowEmptyState ||
          !uniformityData ||
          barChartData.length === 0 ? (
            <UniformityBarChartSkeleton />
          ) : (
            <UniformityBarChart data={barChartData} />
          )}
        </div>
      </Card>
      <Card
        variant='bordered'
        className={{
          wrapper:
            '2xl:col-span-1 w-full rounded-xl border border-base-content/10',
          body:
            shouldShowEmptyState || !uniformityData || !gaugeChartData
              ? 'h-110 p-4'
              : 'p-4',
        }}
      >
        <div className='flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-3'>
          <div className='text-base font-semibold leading-7 flex gap-3 items-center'>
            Weekly Performance{' '}
            <Icon
              icon='heroicons:information-circle'
              width={20}
              height={20}
              className='inline text-neutral-500'
            />
          </div>
        </div>
        {shouldShowEmptyState || !uniformityData || !gaugeChartData ? (
          <UniformityGaugeChartSkeleton />
        ) : (
          <UniformityGaugeChart
            value={gaugeChartData.value}
            label={gaugeChartData.label}
            week={gaugeChartData.week}
            currentValue={gaugeChartData.currentValue}
            totalValue={gaugeChartData.totalValue}
            onWeekChange={handleWeekChange}
            hasPrevWeek={gaugeChartData.hasPrevWeek}
            hasNextWeek={gaugeChartData.hasNextWeek}
          />
        )}
      </Card>
    </section>
  );
};

export default UniformityChart;
