import { TrendingUp, Droplets, Wind, Cloud, Info, Calendar } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

interface DayHistoricalData {
  year: number;
  date: string;
  temp_min: number;
  temp_max: number;
  temp_avg: number;
  precipitation: number;
}

interface HistoricalAnalysis {
  date: string;
  avg_temp_min: number;
  avg_temp_max: number;
  avg_temp: number;
  avg_precipitation: number;
  avg_humidity: number;
  avg_wind_speed: number;
  avg_cloud_cover: number;
  precipitation_probability: number;
  most_common_condition: string;
  confidence_score: number;
  historical_data: DayHistoricalData[];
  insights: string[];
}

interface HistoricalWeatherDisplayProps {
  analyses: HistoricalAnalysis[];
  loading?: boolean;
  error?: string;
  units?: 'metric' | 'imperial';
  yearsAnalyzed?: number;
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' });
};

const getConditionColor = (condition: string) => {
  switch (condition.toLowerCase()) {
    case 'açık':
      return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
    case 'parçalı bulutlu':
      return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
    case 'bulutlu':
      return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200';
    case 'yağmurlu':
      return 'bg-blue-200 text-blue-900 dark:bg-blue-800 dark:text-blue-100';
    default:
      return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200';
  }
};

const getConfidenceLabel = (score: number) => {
  if (score >= 0.8) return { label: 'Yüksek', color: 'bg-green-500' };
  if (score >= 0.6) return { label: 'Orta', color: 'bg-yellow-500' };
  return { label: 'Düşük', color: 'bg-orange-500' };
};

export function HistoricalWeatherDisplay({ 
  analyses, 
  loading, 
  error, 
  units = 'metric',
  yearsAnalyzed = 5 
}: HistoricalWeatherDisplayProps) {
  const tempUnit = units === 'metric' ? '°C' : '°F';

  if (loading) {
    return (
      <Card className="bg-gradient-to-br from-purple-50 to-indigo-50 dark:from-purple-950/20 dark:to-indigo-950/20 border-purple-200 dark:border-purple-800">
        <CardHeader className="pb-3">
          <div className="flex items-center gap-2">
            <Skeleton className="h-5 w-5 rounded" />
            <Skeleton className="h-5 w-48" />
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-24 w-full rounded-lg" />
            ))}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="bg-purple-50 dark:bg-purple-950/20 border-purple-200 dark:border-purple-800">
        <CardContent className="p-4">
          <div className="flex items-start gap-2">
            <TrendingUp className="h-5 w-5 text-purple-600 dark:text-purple-400 shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="text-sm font-medium text-purple-900 dark:text-purple-100">Geçmiş Hava Durumu Analizi</p>
              <p className="text-xs text-purple-700 dark:text-purple-300 mt-1">{error}</p>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!analyses || analyses.length === 0) {
    return null;
  }

  return (
    <Card className="bg-gradient-to-br from-purple-50 to-indigo-50 dark:from-purple-950/20 dark:to-indigo-950/20 border-purple-200 dark:border-purple-800">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <TrendingUp className="h-5 w-5 text-purple-600 dark:text-purple-400" />
            <span className="text-purple-900 dark:text-purple-100">
              Akıllı Hava Durumu Tahmini
            </span>
          </CardTitle>
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Badge variant="outline" className="gap-1 border-purple-300 dark:border-purple-700">
                  <Calendar className="h-3 w-3" />
                  {yearsAnalyzed} Yıl
                </Badge>
              </TooltipTrigger>
              <TooltipContent>
                <p>Son {yearsAnalyzed} yılın verilerine dayalı analiz</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>
        <p className="text-xs text-purple-700 dark:text-purple-300 mt-1">
          Geçmiş verilere dayalı akıllı tahmin
        </p>
      </CardHeader>
      
      <CardContent className="space-y-3">
        {analyses.map((analysis, index) => {
          const confidence = getConfidenceLabel(analysis.confidence_score);
          
          return (
            <div
              key={analysis.date}
              className="bg-white/80 dark:bg-gray-900/40 backdrop-blur-sm rounded-lg p-4 border border-purple-100 dark:border-purple-900"
            >
              {/* Date Header */}
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
                    {formatDate(analysis.date)}
                  </span>
                  <Badge className={getConditionColor(analysis.most_common_condition)}>
                    {analysis.most_common_condition}
                  </Badge>
                </div>
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-1.5">
                        <span className="text-xs text-gray-600 dark:text-gray-400">Güven:</span>
                        <div className={`h-2 w-16 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden`}>
                          <div 
                            className={`h-full ${confidence.color}`}
                            style={{ width: `${analysis.confidence_score * 100}%` }}
                          />
                        </div>
                        <span className="text-xs font-medium text-gray-700 dark:text-gray-300">
                          {confidence.label}
                        </span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>Tahmin güvenilirliği: {Math.round(analysis.confidence_score * 100)}%</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              </div>

              {/* Temperature */}
              <div className="grid grid-cols-3 gap-3 mb-3">
                <div className="text-center">
                  <p className="text-xs text-gray-600 dark:text-gray-400 mb-1">Min</p>
                  <p className="text-lg font-bold text-blue-600 dark:text-blue-400">
                    {Math.round(analysis.avg_temp_min)}{tempUnit}
                  </p>
                </div>
                <div className="text-center">
                  <p className="text-xs text-gray-600 dark:text-gray-400 mb-1">Ortalama</p>
                  <p className="text-xl font-bold text-gray-900 dark:text-gray-100">
                    {Math.round(analysis.avg_temp)}{tempUnit}
                  </p>
                </div>
                <div className="text-center">
                  <p className="text-xs text-gray-600 dark:text-gray-400 mb-1">Max</p>
                  <p className="text-lg font-bold text-orange-600 dark:text-orange-400">
                    {Math.round(analysis.avg_temp_max)}{tempUnit}
                  </p>
                </div>
              </div>

              {/* Weather Stats */}
              <div className="grid grid-cols-3 gap-2 mb-3">
                <div className="flex items-center gap-1.5 text-xs">
                  <Droplets className="h-3.5 w-3.5 text-blue-500" />
                  <span className="text-gray-700 dark:text-gray-300">
                    {Math.round(analysis.precipitation_probability * 100)}%
                  </span>
                </div>
                <div className="flex items-center gap-1.5 text-xs">
                  <Wind className="h-3.5 w-3.5 text-gray-500" />
                  <span className="text-gray-700 dark:text-gray-300">
                    {Math.round(analysis.avg_wind_speed)} m/s
                  </span>
                </div>
                <div className="flex items-center gap-1.5 text-xs">
                  <Cloud className="h-3.5 w-3.5 text-gray-400" />
                  <span className="text-gray-700 dark:text-gray-300">
                    {Math.round(analysis.avg_cloud_cover)}%
                  </span>
                </div>
              </div>

              {/* Insights */}
              {analysis.insights && analysis.insights.length > 0 && (
                <div className="bg-purple-50 dark:bg-purple-900/20 rounded-md p-2 border border-purple-100 dark:border-purple-800">
                  <div className="flex items-start gap-2">
                    <Info className="h-3.5 w-3.5 text-purple-600 dark:text-purple-400 shrink-0 mt-0.5" />
                    <div className="flex-1">
                      {analysis.insights.map((insight, idx) => (
                        <p key={idx} className="text-xs text-purple-800 dark:text-purple-200">
                          • {insight}
                        </p>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* Historical Years Summary */}
              {analysis.historical_data && analysis.historical_data.length > 0 && (
                <div className="mt-3 pt-3 border-t border-purple-100 dark:border-purple-800">
                  <p className="text-xs text-gray-600 dark:text-gray-400 mb-2">
                    Geçmiş Yıllar ({analysis.historical_data.length} yıl):
                  </p>
                  <div className="flex gap-1 flex-wrap">
                    {analysis.historical_data.map((yearData) => (
                      <TooltipProvider key={yearData.year}>
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Badge 
                              variant="outline" 
                              className="text-xs px-1.5 py-0.5 border-purple-200 dark:border-purple-700"
                            >
                              {yearData.year}
                            </Badge>
                          </TooltipTrigger>
                          <TooltipContent>
                            <div className="text-xs">
                              <p>{yearData.year}: {Math.round(yearData.temp_avg)}°C</p>
                              <p>Yağış: {yearData.precipitation.toFixed(1)}mm</p>
                            </div>
                          </TooltipContent>
                        </Tooltip>
                      </TooltipProvider>
                    ))}
                  </div>
                </div>
              )}
            </div>
          );
        })}

        <div className="text-center pt-2">
          <p className="text-xs text-purple-600 dark:text-purple-400">
            💡 Bu tahminler son {yearsAnalyzed} yılın aynı tarihlerdeki hava durumu verilerine dayanmaktadır
          </p>
        </div>
      </CardContent>
    </Card>
  );
}
