import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { clsx } from 'clsx';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  ReferenceLine,
  Area,
  ComposedChart,
  Legend,
  Brush,
  ReferenceDot,
} from 'recharts';
import { Card, CardHeader, CardBody } from '../../ui';
import { Button } from '../../ui';
import { Select } from '../../ui';
import { Badge } from '../../ui';
import {
  ForecastResponse,
} from '../../../api/types/forecasting';

export interface DemandChartProps {
  className?: string;
  title?: string;
  data?: ForecastResponse[];
  product?: string;
  period?: string;
  timeframe?: 'weekly' | 'monthly' | 'quarterly' | 'yearly';
  onTimeframeChange?: (timeframe: 'weekly' | 'monthly' | 'quarterly' | 'yearly') => void;
  showConfidenceInterval?: boolean;
  loading?: boolean;
  error?: string | null;
  height?: number;
  onExport?: (format: 'png' | 'pdf' | 'csv') => void;
}

interface ChartDataPoint {
  date: string;
  actualDemand?: number;
  predictedDemand?: number;
  confidenceLower?: number;
  confidenceUpper?: number;
  temperature?: number;
}

const PRODUCT_COLORS = [
  '#8884d8', // Croissants
  '#82ca9d', // Pan de molde
  '#ffc658', // Roscón de Reyes
  '#ff7c7c', // Torrijas
  '#8dd1e1', // Magdalenas
  '#d084d0', // Empanadas
  '#ffb347', // Tarta de Santiago
  '#87ceeb', // Mazapán
];

const WEATHER_ICONS: Record<string, string> = {
  'sunny': '☀️',
  'cloudy': '☁️',
  'rainy': '🌧️',
  'stormy': '⛈️',
  'snowy': '❄️',
  'foggy': '🌫️',
  'windy': '🌪️',
};

const DemandChart: React.FC<DemandChartProps> = ({
  className,
  title = 'Predicción de Demanda',
  data = [],
  product = '',
  period = '7',
  timeframe = 'weekly',
  onTimeframeChange,
  showConfidenceInterval = true,
  loading = false,
  error = null,
  height = 400,
  onExport,
}) => {
  const [selectedPeriod, setSelectedPeriod] = useState<{ start?: Date; end?: Date }>({});
  const [zoomedData, setZoomedData] = useState<ChartDataPoint[]>([]);
  const [hoveredPoint, setHoveredPoint] = useState<ChartDataPoint | null>(null);

  // Process forecast data for chart
  const chartData = useMemo(() => {
    console.log('🔍 Processing forecast data for chart:', data);

    const processedData: ChartDataPoint[] = data.map(forecast => {
      // Convert forecast_date to a proper date format for the chart
      const forecastDate = new Date(forecast.forecast_date);
      const dateString = forecastDate.toISOString().split('T')[0];

      return {
        date: dateString,
        actualDemand: undefined, // Not available in current forecast response
        predictedDemand: forecast.predicted_demand,
        confidenceLower: forecast.confidence_lower,
        confidenceUpper: forecast.confidence_upper,
        temperature: forecast.weather_temperature,
      };
    });

    console.log('📊 Processed chart data:', processedData);
    return processedData.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
  }, [data]);

  // Filter data based on selected period
  const filteredData = useMemo(() => {
    console.log('🔍 Filtering data - selected period:', selectedPeriod);
    console.log('🔍 Chart data before filtering:', chartData);

    if (!selectedPeriod.start || !selectedPeriod.end) {
      console.log('📊 No period filter, returning all chart data');
      return chartData;
    }

    const filtered = chartData.filter(point => {
      const pointDate = new Date(point.date);
      return pointDate >= selectedPeriod.start! && pointDate <= selectedPeriod.end!;
    });

    console.log('📊 Filtered data:', filtered);
    return filtered;
  }, [chartData, selectedPeriod]);

  // Update zoomed data when filtered data changes
  useEffect(() => {
    console.log('🔍 Setting zoomed data from filtered data:', filteredData);
    // Always update zoomed data when filtered data changes, even if empty
    setZoomedData(filteredData);
  }, [filteredData]);

  // Handle brush selection
  const handleBrushChange = useCallback((brushData: any) => {
    if (brushData && brushData.startIndex !== undefined && brushData.endIndex !== undefined) {
      const newData = filteredData.slice(brushData.startIndex, brushData.endIndex + 1);
      setZoomedData(newData);
    } else {
      setZoomedData(filteredData);
    }
  }, [filteredData]);

  // Reset zoom
  const handleResetZoom = useCallback(() => {
    setZoomedData(filteredData);
    setSelectedPeriod({});
  }, [filteredData]);

  // Custom tooltip
  const CustomTooltip = ({ active, payload, label }: any) => {
    if (!active || !payload || !payload.length) return null;

    const data = payload[0].payload as ChartDataPoint;
    const formattedDate = new Date(label).toLocaleDateString('es-ES', {
      day: 'numeric',
      month: 'short',
      year: 'numeric',
    });

    return (
      <div className="bg-card-bg border border-border-primary rounded-lg shadow-lg p-4 max-w-sm">
        <h4 className="font-semibold text-text-primary mb-2">{formattedDate}</h4>
        
        <div className="space-y-1">
          {data.predictedDemand !== undefined && (
            <div className="flex justify-between items-center">
              <span className="text-text-secondary text-sm">Demanda Predicha:</span>
              <span className="font-medium text-[var(--color-success)]">{data.predictedDemand.toFixed(1)}</span>
            </div>
          )}

          {showConfidenceInterval && data.confidenceLower !== undefined && data.confidenceUpper !== undefined && (
            <div className="flex justify-between items-center">
              <span className="text-text-secondary text-sm">Intervalo de Confianza:</span>
              <span className="text-sm text-text-tertiary">
                {data.confidenceLower.toFixed(1)} - {data.confidenceUpper.toFixed(1)}
              </span>
            </div>
          )}

          {data.temperature && (
            <div className="flex justify-between items-center">
              <span className="text-text-secondary text-sm">Temperatura:</span>
              <span className="text-sm text-text-tertiary">{data.temperature}°C</span>
            </div>
          )}
        </div>
      </div>
    );
  };


  // Loading state
  if (loading) {
    return (
      <Card className={className}>
        <CardHeader>
          <h3 className="text-lg font-semibold text-text-primary">{title}</h3>
        </CardHeader>
        <CardBody>
          <div className="flex items-center justify-center h-64">
            <div className="flex items-center space-x-2">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-color-primary"></div>
              <span className="text-text-secondary">Cargando gráfico de demanda...</span>
            </div>
          </div>
        </CardBody>
      </Card>
    );
  }

  // Error state
  if (error) {
    return (
      <Card className={className} variant="outlined">
        <CardHeader>
          <h3 className="text-lg font-semibold text-text-primary">{title}</h3>
        </CardHeader>
        <CardBody>
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <div className="text-red-500 mb-2">
                <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <p className="text-text-secondary">{error}</p>
            </div>
          </div>
        </CardBody>
      </Card>
    );
  }

  // Robust fallback logic for display data
  const displayData = zoomedData.length > 0 ? zoomedData : (filteredData.length > 0 ? filteredData : chartData);

  console.log('📊 Final display data:', {
    chartDataLength: chartData.length,
    filteredDataLength: filteredData.length,
    zoomedDataLength: zoomedData.length,
    displayDataLength: displayData.length,
    displayData: displayData
  });

  // Empty state - only show if we truly have no data
  if (displayData.length === 0) {
    return (
      <Card className={className}>
        <CardHeader>
          <h3 className="text-lg font-semibold text-text-primary">{title}</h3>
        </CardHeader>
        <CardBody>
          <div className="flex items-center justify-center h-64">
            <div className="text-center">
              <div className="text-text-tertiary mb-2">
                <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                </svg>
              </div>
              <p className="text-text-secondary">No hay datos de demanda disponibles</p>
            </div>
          </div>
        </CardBody>
      </Card>
    );
  }

  return (
    <Card className={className}>
      <CardHeader>
        <div className="flex items-center justify-between flex-wrap gap-4">
          <h3 className="text-lg font-semibold text-text-primary">{title}</h3>
          
          <div className="flex items-center gap-3 flex-wrap">
            {/* Time period selector */}
            <Select
              value={timeframe}
              onChange={(value) => onTimeframeChange?.(value as 'weekly' | 'monthly' | 'quarterly' | 'yearly')}
              className="w-32"
            >
              <option value="weekly">Semanal</option>
              <option value="monthly">Mensual</option>
              <option value="quarterly">Trimestral</option>
              <option value="yearly">Anual</option>
            </Select>

            {/* Export options */}
            {onExport && (
              <div className="flex gap-1">
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={() => onExport('png')}
                  title="Exportar como PNG"
                >
                  📊
                </Button>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={() => onExport('csv')}
                  title="Exportar datos CSV"
                >
                  📋
                </Button>
              </div>
            )}

            {/* Reset zoom */}
            {displayData.length !== filteredData.length && (
              <Button variant="ghost" size="sm" onClick={handleResetZoom}>
                Restablecer Zoom
              </Button>
            )}
          </div>
        </div>
      </CardHeader>

      <CardBody padding="lg">
        <div style={{ width: '100%', height }}>
          <ResponsiveContainer>
            <ComposedChart data={displayData} margin={{ top: 20, right: 30, left: 20, bottom: 60 }}>
              <defs>
                <linearGradient id="demandGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#10b981" stopOpacity={0.3}/>
                  <stop offset="95%" stopColor="#10b981" stopOpacity={0.05}/>
                </linearGradient>
                <linearGradient id="confidenceGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#10b981" stopOpacity={0.1}/>
                  <stop offset="95%" stopColor="#10b981" stopOpacity={0.02}/>
                </linearGradient>
              </defs>
              <CartesianGrid
                strokeDasharray="2 2"
                stroke="#e5e7eb"
                strokeOpacity={0.5}
                horizontal={true}
                vertical={false}
              />
              <XAxis
                dataKey="date"
                stroke="#6b7280"
                fontSize={11}
                tickMargin={8}
                angle={-45}
                textAnchor="end"
                height={80}
                interval={0}
                tickFormatter={(value) => {
                  const date = new Date(value);
                  return date.toLocaleDateString('es-ES', {
                    month: 'short',
                    day: 'numeric',
                    weekday: displayData.length <= 7 ? 'short' : undefined
                  });
                }}
              />
              <YAxis
                stroke="#6b7280"
                fontSize={11}
                width={60}
                tickFormatter={(value) => value.toFixed(0)}
                domain={['dataMin - 5', 'dataMax + 5']}
              />
              <Tooltip
                content={<CustomTooltip />}
                cursor={{ stroke: '#10b981', strokeWidth: 1, strokeOpacity: 0.5 }}
              />
              <Legend
                wrapperStyle={{ paddingTop: '20px' }}
                iconType="line"
              />

              {/* Confidence interval area - rendered as a range between lower and upper bounds */}
              {showConfidenceInterval && (
                <Area
                  type="monotone"
                  dataKey="confidenceUpper"
                  stroke="#10b981"
                  strokeWidth={1}
                  strokeOpacity={0.3}
                  fill="url(#confidenceGradient)"
                  fillOpacity={0.3}
                  name="Límite Superior"
                  legendType="none"
                />
              )}
              {showConfidenceInterval && (
                <Area
                  type="monotone"
                  dataKey="confidenceLower"
                  stroke="#10b981"
                  strokeWidth={1}
                  strokeOpacity={0.3}
                  fill="var(--bg-primary, #1a1a2e)"
                  fillOpacity={1}
                  name="Límite Inferior"
                  legendType="none"
                />
              )}

              {/* Background area for main prediction */}
              <Area
                type="monotone"
                dataKey="predictedDemand"
                stroke="none"
                fill="url(#demandGradient)"
                fillOpacity={0.2}
                name="Área de Demanda"
              />

              {/* Predicted demand line */}
              <Line
                type="monotone"
                dataKey="predictedDemand"
                stroke="#10b981"
                strokeWidth={3}
                dot={{
                  fill: '#10b981',
                  strokeWidth: 2,
                  stroke: '#ffffff',
                  r: 4
                }}
                activeDot={{
                  r: 6,
                  stroke: '#10b981',
                  strokeWidth: 3,
                  fill: '#ffffff'
                }}
                name="Demanda Predicha"
                connectNulls={false}
              />
            </ComposedChart>
          </ResponsiveContainer>
        </div>

        {/* Brush for zooming */}
        {filteredData.length > 20 && (
          <div className="mt-4" style={{ width: '100%', height: 80 }}>
            <ResponsiveContainer>
              <LineChart data={filteredData}>
                <Line 
                  type="monotone" 
                  dataKey="predictedDemand" 
                  stroke="#10b981" 
                  strokeWidth={1} 
                  dot={false} 
                />
                <Brush 
                  dataKey="date" 
                  height={30} 
                  stroke="#8884d8"
                  onChange={handleBrushChange}
                  tickFormatter={(value) => {
                    const date = new Date(value);
                    return date.toLocaleDateString('es-ES', { month: 'short', day: 'numeric' });
                  }}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
        )}

        {/* Enhanced Chart legend and insights */}
        <div className="mt-6 space-y-4">
          <div className="flex items-center justify-center gap-6 text-sm">
            <div className="flex items-center gap-2">
              <div className="w-4 h-0.5 bg-green-500 rounded"></div>
              <span className="text-text-secondary">Demanda Predicha</span>
            </div>
            {showConfidenceInterval && (
              <div className="flex items-center gap-2">
                <div className="w-4 h-2 bg-green-500 bg-opacity-20 rounded"></div>
                <span className="text-text-secondary">Intervalo de Confianza</span>
              </div>
            )}
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 bg-green-500 rounded-full"></div>
              <span className="text-text-secondary">Puntos de Datos</span>
            </div>
          </div>

          {/* Quick stats */}
          <div className="grid grid-cols-3 gap-4 p-4 bg-gray-50 rounded-lg">
            <div className="text-center">
              <div className="text-lg font-bold text-green-600">
                {Math.min(...displayData.map(d => d.predictedDemand || 0)).toFixed(1)}
              </div>
              <div className="text-xs text-gray-500">Mínimo</div>
            </div>
            <div className="text-center">
              <div className="text-lg font-bold text-blue-600">
                {(displayData.reduce((sum, d) => sum + (d.predictedDemand || 0), 0) / displayData.length).toFixed(1)}
              </div>
              <div className="text-xs text-gray-500">Promedio</div>
            </div>
            <div className="text-center">
              <div className="text-lg font-bold text-orange-600">
                {Math.max(...displayData.map(d => d.predictedDemand || 0)).toFixed(1)}
              </div>
              <div className="text-xs text-gray-500">Máximo</div>
            </div>
          </div>
        </div>
      </CardBody>
    </Card>
  );
};

export default DemandChart;