import { Clock, MapPin, TrendingDown } from 'lucide-react';
import React from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { cn } from '@/lib/utils';

interface OptimizedPlace {
  tripPlaceId: string;
  placeId: string;
  name: string;
  newOrderIndex: number;
  oldOrderIndex: number;
}

interface OptimizationResult {
  optimizedOrder: OptimizedPlace[];
  distanceBeforeKm: number;
  distanceAfterKm: number;
  estimatedSavings: {
    distanceKm: number;
    timeMinutes: number;
  };
  explanation: string;
}

interface OptimizePreviewModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  originalPlaces: Array<{
    id: string;
    tripPlaceId: string;
    name: string;
    order_index: number;
  }>;
  optimizationResult: OptimizationResult | null;
  onConfirm: () => void;
  isApplying?: boolean;
}

export function OptimizePreviewModal({
  open,
  onOpenChange,
  originalPlaces,
  optimizationResult,
  onConfirm,
  isApplying = false,
}: OptimizePreviewModalProps) {
  if (!optimizationResult) return null;

  // Orijinal sıralama
  const sortedOriginal = [...originalPlaces].sort((a, b) => a.order_index - b.order_index);

  // Yeni sıralama
  const sortedOptimized = [...optimizationResult.optimizedOrder].sort(
    (a, b) => a.newOrderIndex - b.newOrderIndex
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <MapPin className="h-5 w-5 text-primary" />
            Rota Optimizasyonu Önizlemesi
          </DialogTitle>
          <DialogDescription>
            Önerilen rota değişikliklerini inceleyin ve onaylayın
          </DialogDescription>
        </DialogHeader>

        {/* Tahmini Tasarruf */}
        <div className="bg-primary/5 border border-primary/20 rounded-lg p-4 mb-4">
          <div className="flex items-center gap-2 mb-3">
            <TrendingDown className="h-5 w-5 text-primary" />
            <h3 className="font-semibold text-primary">Tahmini Tasarruf</h3>
          </div>
          
          {/* Önce/Sonra Mesafe Karşılaştırması */}
          <div className="grid grid-cols-2 gap-4 mb-3 pb-3 border-b border-primary/10">
            <div className="text-center">
              <div className="text-xs text-muted-foreground mb-1">Önce</div>
              <div className="text-2xl font-bold text-foreground">
                {optimizationResult.distanceBeforeKm.toFixed(1)} km
              </div>
            </div>
            <div className="text-center">
              <div className="text-xs text-muted-foreground mb-1">Sonra</div>
              <div className="text-2xl font-bold text-primary">
                {optimizationResult.distanceAfterKm.toFixed(1)} km
              </div>
            </div>
          </div>

          {/* Tasarruf Detayları */}
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div className="flex items-center gap-2">
              <MapPin className="h-4 w-4 text-muted-foreground" />
              <span className="text-muted-foreground">Tasarruf:</span>
              <span className="font-semibold text-primary">
                {optimizationResult.estimatedSavings.distanceKm.toFixed(1)} km
              </span>
            </div>
            <div className="flex items-center gap-2">
              <Clock className="h-4 w-4 text-muted-foreground" />
              <span className="text-muted-foreground">Süre:</span>
              <span className="font-semibold text-primary">
                ~{optimizationResult.estimatedSavings.timeMinutes} dk
              </span>
            </div>
          </div>
          
          {/* Yüzde Tasarruf */}
          {optimizationResult.distanceBeforeKm > 0 && (
            <div className="mt-3 pt-3 border-t border-primary/10 text-center">
              <span className="text-sm text-muted-foreground">
                %{Math.round((optimizationResult.estimatedSavings.distanceKm / optimizationResult.distanceBeforeKm) * 100)} daha kısa rota
              </span>
            </div>
          )}
        </div>

        {/* AI Açıklaması */}
        {optimizationResult.explanation && (
          <div className="bg-muted/50 rounded-lg p-4 mb-4">
            <h3 className="font-semibold mb-2 text-sm">Açıklama</h3>
            <p className="text-sm text-muted-foreground">
              {optimizationResult.explanation}
            </p>
          </div>
        )}

        {/* Önce/Sonra Karşılaştırması */}
        <div className="grid md:grid-cols-2 gap-4">
          {/* Eski Sıra */}
          <div>
            <h3 className="font-semibold mb-3 text-sm flex items-center gap-2">
              <Badge variant="outline">Mevcut Sıra</Badge>
            </h3>
            <div className="space-y-2">
              {sortedOriginal.map((place, index) => (
                <div
                  key={place.id}
                  className="flex items-center gap-2 p-2 rounded-md bg-muted/30"
                >
                  <div className="flex items-center justify-center w-6 h-6 rounded-full bg-muted text-xs font-semibold">
                    {index + 1}
                  </div>
                  <span className="text-sm flex-1">{place.name}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Yeni Sıra */}
          <div>
            <h3 className="font-semibold mb-3 text-sm flex items-center gap-2">
              <Badge variant="default">Önerilen Sıra</Badge>
            </h3>
            <div className="space-y-2">
              {sortedOptimized.map((place, index) => {
                const originalPlace = originalPlaces.find(p => p.tripPlaceId === place.tripPlaceId);
                const hasChanged = originalPlace && originalPlace.order_index !== place.newOrderIndex;
                
                return (
                  <div
                    key={place.tripPlaceId}
                    className={cn(
                      "flex items-center gap-2 p-2 rounded-md transition-colors",
                      hasChanged 
                        ? "bg-primary/10 border border-primary/30" 
                        : "bg-muted/30"
                    )}
                  >
                    <div className={cn(
                      "flex items-center justify-center w-6 h-6 rounded-full text-xs font-semibold",
                      hasChanged ? "bg-primary text-primary-foreground" : "bg-muted"
                    )}>
                      {index + 1}
                    </div>
                    <span className="text-sm flex-1">{place.name}</span>
                    {hasChanged && (
                      <Badge variant="secondary" className="text-xs">
                        Değişti
                      </Badge>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <DialogFooter className="mt-6">
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isApplying}
          >
            Vazgeç
          </Button>
          <Button
            onClick={onConfirm}
            disabled={isApplying}
          >
            {isApplying ? 'Uygulanıyor...' : 'Bu Sırayı Uygula'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
