import React, { useState } from 'react';
import { Cloud, Sun, CloudRain, Thermometer, Wind, Droplets, Calendar, TrendingUp } from 'lucide-react';
import { Button, Card, Badge } from '../../../../components/ui';
import { PageHeader } from '../../../../components/layout';

const WeatherPage: React.FC = () => {
  const [selectedPeriod, setSelectedPeriod] = useState('week');

  const currentWeather = {
    temperature: 18,
    condition: 'partly-cloudy',
    humidity: 65,
    windSpeed: 12,
    pressure: 1013,
    uvIndex: 4,
    visibility: 10,
    description: 'Parcialmente nublado'
  };

  const forecast = [
    {
      date: '2024-01-27',
      day: 'Sábado',
      condition: 'sunny',
      tempMax: 22,
      tempMin: 12,
      humidity: 45,
      precipitation: 0,
      wind: 8,
      impact: 'high-demand',
      recommendation: 'Incrementar producción de helados y bebidas frías'
    },
    {
      date: '2024-01-28',
      day: 'Domingo',
      condition: 'partly-cloudy',
      tempMax: 19,
      tempMin: 11,
      humidity: 55,
      precipitation: 20,
      wind: 15,
      impact: 'normal',
      recommendation: 'Producción estándar'
    },
    {
      date: '2024-01-29',
      day: 'Lunes',
      condition: 'rainy',
      tempMax: 15,
      tempMin: 8,
      humidity: 85,
      precipitation: 80,
      wind: 22,
      impact: 'comfort-food',
      recommendation: 'Aumentar sopas, chocolates calientes y pan recién horneado'
    },
    {
      date: '2024-01-30',
      day: 'Martes',
      condition: 'cloudy',
      tempMax: 16,
      tempMin: 9,
      humidity: 70,
      precipitation: 40,
      wind: 18,
      impact: 'moderate',
      recommendation: 'Enfoque en productos de interior'
    },
    {
      date: '2024-01-31',
      day: 'Miércoles',
      condition: 'sunny',
      tempMax: 24,
      tempMin: 14,
      humidity: 40,
      precipitation: 0,
      wind: 10,
      impact: 'high-demand',
      recommendation: 'Incrementar productos frescos y ensaladas'
    }
  ];

  const weatherImpacts = [
    {
      condition: 'Día Soleado',
      icon: Sun,
      impact: 'Aumento del 25% en bebidas frías',
      recommendations: [
        'Incrementar producción de helados',
        'Más bebidas refrescantes',
        'Ensaladas y productos frescos',
        'Horario extendido de terraza'
      ],
      color: 'yellow'
    },
    {
      condition: 'Día Lluvioso',
      icon: CloudRain,
      impact: 'Aumento del 40% en productos calientes',
      recommendations: [
        'Más sopas y caldos',
        'Chocolates calientes',
        'Pan recién horneado',
        'Productos de repostería'
      ],
      color: 'blue'
    },
    {
      condition: 'Frío Intenso',
      icon: Thermometer,
      impact: 'Preferencia por comida reconfortante',
      recommendations: [
        'Aumentar productos horneados',
        'Bebidas calientes especiales',
        'Productos energéticos',
        'Promociones de interior'
      ],
      color: 'purple'
    }
  ];

  const seasonalTrends = [
    {
      season: 'Primavera',
      period: 'Mar - May',
      trends: [
        'Aumento en productos frescos (+30%)',
        'Mayor demanda de ensaladas',
        'Bebidas naturales populares',
        'Horarios extendidos efectivos'
      ],
      avgTemp: '15-20°C',
      impact: 'positive'
    },
    {
      season: 'Verano',
      period: 'Jun - Ago',
      trends: [
        'Pico de helados y granizados (+60%)',
        'Productos ligeros preferidos',
        'Horario matutino crítico',
        'Mayor tráfico de turistas'
      ],
      avgTemp: '25-35°C',
      impact: 'high'
    },
    {
      season: 'Otoño',
      period: 'Sep - Nov',
      trends: [
        'Regreso a productos tradicionales',
        'Aumento en bollería (+20%)',
        'Bebidas calientes populares',
        'Horarios regulares'
      ],
      avgTemp: '10-18°C',
      impact: 'stable'
    },
    {
      season: 'Invierno',
      period: 'Dec - Feb',
      trends: [
        'Máximo de productos calientes (+50%)',
        'Pan recién horneado crítico',
        'Chocolates y dulces festivos',
        'Menor tráfico general (-15%)'
      ],
      avgTemp: '5-12°C',
      impact: 'comfort'
    }
  ];

  const getWeatherIcon = (condition: string) => {
    const iconProps = { className: "w-8 h-8" };
    switch (condition) {
      case 'sunny': return <Sun {...iconProps} className="w-8 h-8 text-yellow-500" />;
      case 'partly-cloudy': return <Cloud {...iconProps} className="w-8 h-8 text-[var(--text-tertiary)]" />;
      case 'cloudy': return <Cloud {...iconProps} className="w-8 h-8 text-[var(--text-secondary)]" />;
      case 'rainy': return <CloudRain {...iconProps} className="w-8 h-8 text-blue-500" />;
      default: return <Cloud {...iconProps} />;
    }
  };

  const getConditionLabel = (condition: string) => {
    switch (condition) {
      case 'sunny': return 'Soleado';
      case 'partly-cloudy': return 'Parcialmente nublado';
      case 'cloudy': return 'Nublado';
      case 'rainy': return 'Lluvioso';
      default: return condition;
    }
  };

  const getImpactColor = (impact: string) => {
    switch (impact) {
      case 'high-demand': return 'green';
      case 'comfort-food': return 'orange';
      case 'moderate': return 'blue';
      case 'normal': return 'gray';
      default: return 'gray';
    }
  };

  const getImpactLabel = (impact: string) => {
    switch (impact) {
      case 'high-demand': return 'Alta Demanda';
      case 'comfort-food': return 'Comida Reconfortante';
      case 'moderate': return 'Demanda Moderada';
      case 'normal': return 'Demanda Normal';
      default: return impact;
    }
  };

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Datos Meteorológicos"
        description="Integra información del clima para optimizar la producción y ventas"
      />

      {/* Current Weather */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Condiciones Actuales</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <div className="flex items-center space-x-4">
            {getWeatherIcon(currentWeather.condition)}
            <div>
              <p className="text-3xl font-bold text-[var(--text-primary)]">{currentWeather.temperature}°C</p>
              <p className="text-sm text-[var(--text-secondary)]">{currentWeather.description}</p>
            </div>
          </div>

          <div className="space-y-2">
            <div className="flex items-center space-x-2">
              <Droplets className="w-4 h-4 text-blue-500" />
              <span className="text-sm text-[var(--text-secondary)]">Humedad: {currentWeather.humidity}%</span>
            </div>
            <div className="flex items-center space-x-2">
              <Wind className="w-4 h-4 text-[var(--text-tertiary)]" />
              <span className="text-sm text-[var(--text-secondary)]">Viento: {currentWeather.windSpeed} km/h</span>
            </div>
          </div>

          <div className="space-y-2">
            <div className="text-sm text-[var(--text-secondary)]">
              <span className="font-medium">Presión:</span> {currentWeather.pressure} hPa
            </div>
            <div className="text-sm text-[var(--text-secondary)]">
              <span className="font-medium">UV:</span> {currentWeather.uvIndex}
            </div>
          </div>

          <div className="space-y-2">
            <div className="text-sm text-[var(--text-secondary)]">
              <span className="font-medium">Visibilidad:</span> {currentWeather.visibility} km
            </div>
            <Badge variant="blue">Condiciones favorables</Badge>
          </div>
        </div>
      </Card>

      {/* Weather Forecast */}
      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-[var(--text-primary)]">Pronóstico Extendido</h3>
          <select
            value={selectedPeriod}
            onChange={(e) => setSelectedPeriod(e.target.value)}
            className="px-3 py-2 border border-[var(--border-secondary)] rounded-md text-sm"
          >
            <option value="week">Próxima Semana</option>
            <option value="month">Próximo Mes</option>
          </select>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
          {forecast.map((day, index) => (
            <div key={index} className="border rounded-lg p-4">
              <div className="text-center mb-3">
                <p className="font-medium text-[var(--text-primary)]">{day.day}</p>
                <p className="text-xs text-[var(--text-tertiary)]">{new Date(day.date).toLocaleDateString('es-ES')}</p>
              </div>

              <div className="flex justify-center mb-3">
                {getWeatherIcon(day.condition)}
              </div>

              <div className="text-center mb-3">
                <p className="text-sm text-[var(--text-secondary)]">{getConditionLabel(day.condition)}</p>
                <p className="text-lg font-semibold">
                  {day.tempMax}° <span className="text-sm text-[var(--text-tertiary)]">/ {day.tempMin}°</span>
                </p>
              </div>

              <div className="space-y-2 text-xs text-[var(--text-secondary)]">
                <div className="flex justify-between">
                  <span>Humedad:</span>
                  <span>{day.humidity}%</span>
                </div>
                <div className="flex justify-between">
                  <span>Lluvia:</span>
                  <span>{day.precipitation}%</span>
                </div>
                <div className="flex justify-between">
                  <span>Viento:</span>
                  <span>{day.wind} km/h</span>
                </div>
              </div>

              <div className="mt-3">
                <Badge variant={getImpactColor(day.impact)} className="text-xs">
                  {getImpactLabel(day.impact)}
                </Badge>
              </div>

              <div className="mt-2">
                <p className="text-xs text-[var(--text-secondary)]">{day.recommendation}</p>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Weather Impact Analysis */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card className="p-6">
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Impacto del Clima</h3>
          <div className="space-y-4">
            {weatherImpacts.map((impact, index) => (
              <div key={index} className="border rounded-lg p-4">
                <div className="flex items-center space-x-3 mb-3">
                  <div className={`p-2 rounded-lg bg-${impact.color}-100`}>
                    <impact.icon className={`w-5 h-5 text-${impact.color}-600`} />
                  </div>
                  <div>
                    <h4 className="font-medium text-[var(--text-primary)]">{impact.condition}</h4>
                    <p className="text-sm text-[var(--text-secondary)]">{impact.impact}</p>
                  </div>
                </div>
                
                <div className="ml-10">
                  <p className="text-sm font-medium text-[var(--text-secondary)] mb-2">Recomendaciones:</p>
                  <ul className="text-sm text-[var(--text-secondary)] space-y-1">
                    {impact.recommendations.map((rec, idx) => (
                      <li key={idx} className="flex items-center">
                        <span className="w-1 h-1 bg-gray-400 rounded-full mr-2"></span>
                        {rec}
                      </li>
                    ))}
                  </ul>
                </div>
              </div>
            ))}
          </div>
        </Card>

        {/* Seasonal Trends */}
        <Card className="p-6">
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Tendencias Estacionales</h3>
          <div className="space-y-4">
            {seasonalTrends.map((season, index) => (
              <div key={index} className="border rounded-lg p-4">
                <div className="flex items-center justify-between mb-3">
                  <div>
                    <h4 className="font-medium text-[var(--text-primary)]">{season.season}</h4>
                    <p className="text-sm text-[var(--text-tertiary)]">{season.period}</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium text-[var(--text-secondary)]">{season.avgTemp}</p>
                    <Badge variant={
                      season.impact === 'high' ? 'green' :
                      season.impact === 'positive' ? 'blue' :
                      season.impact === 'comfort' ? 'orange' : 'gray'
                    }>
                      {season.impact === 'high' ? 'Alto' :
                       season.impact === 'positive' ? 'Positivo' :
                       season.impact === 'comfort' ? 'Confort' : 'Estable'}
                    </Badge>
                  </div>
                </div>
                
                <ul className="text-sm text-[var(--text-secondary)] space-y-1">
                  {season.trends.map((trend, idx) => (
                    <li key={idx} className="flex items-center">
                      <TrendingUp className="w-3 h-3 mr-2 text-green-500" />
                      {trend}
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Weather Alerts */}
      <Card className="p-6">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Alertas Meteorológicas</h3>
        <div className="space-y-3">
          <div className="flex items-center p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
            <Sun className="w-5 h-5 text-yellow-600 mr-3" />
            <div>
              <p className="text-sm font-medium text-yellow-800">Ola de calor prevista</p>
              <p className="text-sm text-yellow-700">Se esperan temperaturas superiores a 30°C los próximos 3 días</p>
              <p className="text-xs text-yellow-600 mt-1">Recomendación: Incrementar stock de bebidas frías y helados</p>
            </div>
          </div>

          <div className="flex items-center p-3 bg-[var(--color-info)]/5 border border-[var(--color-info)]/20 rounded-lg">
            <CloudRain className="w-5 h-5 text-[var(--color-info)] mr-3" />
            <div>
              <p className="text-sm font-medium text-[var(--color-info)]">Lluvia intensa el lunes</p>
              <p className="text-sm text-[var(--color-info)]">80% probabilidad de precipitación con vientos fuertes</p>
              <p className="text-xs text-[var(--color-info)] mt-1">Recomendación: Preparar más productos calientes y de refugio</p>
            </div>
          </div>
        </div>
      </Card>
    </div>
  );
};

export default WeatherPage;