import { useState } from 'react';
import { Calendar, Clock, DollarSign, Heart, Loader2, MapPin, Mountain, Sparkles, TrendingUp, Users } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { generatePersonalizedRoute } from '@/services/openai-service';
import type { UserPreferences, RouteRecommendation } from '@/types/route';
import { toast } from 'sonner';

interface RouteGeneratorWizardProps {
  onComplete: (route: RouteRecommendation) => void;
  onCancel: () => void;
}

const INTEREST_OPTIONS = [
  { id: 'history', label: 'Tarih & Kültür', icon: '🏛️' },
  { id: 'nature', label: 'Doğa & Yürüyüş', icon: '🌳' },
  { id: 'adventure', label: 'Aktivite & Macera', icon: '🎈' },
  { id: 'photography', label: 'Fotoğrafçılık', icon: '📸' },
  { id: 'food', label: 'Yemek & Gastronomi', icon: '🍽️' },
  { id: 'relaxation', label: 'Dinlenme', icon: '🧘' },
];

export function RouteGeneratorWizard({ onComplete, onCancel }: RouteGeneratorWizardProps) {
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [preferences, setPreferences] = useState<UserPreferences>({
    duration: 3,
    interests: [],
    budget: 'medium',
    travelStyle: 'moderate',
  });
  const [generatedRoute, setGeneratedRoute] = useState<RouteRecommendation | null>(null);

  const handleInterestToggle = (interestId: string) => {
    setPreferences((prev) => ({
      ...prev,
      interests: prev.interests.includes(interestId)
        ? prev.interests.filter((i) => i !== interestId)
        : [...prev.interests, interestId],
    }));
  };

  const handleGenerate = async () => {
    if (preferences.interests.length === 0) {
      toast.error('Lütfen en az bir ilgi alanı seçin');
      return;
    }

    setLoading(true);
    try {
      const route = await generatePersonalizedRoute(preferences);
      setGeneratedRoute(route);
      setStep(2);
      toast.success('Rota başarıyla oluşturuldu!');
    } catch (error: any) {
      console.error('Rota oluşturma hatası:', error);
      toast.error(error.message || 'Rota oluşturulamadı. Lütfen tekrar deneyin.');
    } finally {
      setLoading(false);
    }
  };

  const handleConfirm = () => {
    if (generatedRoute) {
      onComplete(generatedRoute);
    }
  };

  return (
    <div className="w-full max-w-4xl mx-auto">
      {/* Step Indicator */}
      <div className="flex items-center justify-center mb-8 gap-2">
        <div className={`flex items-center gap-2 ${step >= 1 ? 'text-primary' : 'text-muted-foreground'}`}>
          <div className={`w-8 h-8 rounded-full flex items-center justify-center border-2 ${step >= 1 ? 'bg-primary text-primary-foreground border-primary' : 'border-muted-foreground'}`}>
            1
          </div>
          <span className="text-sm font-medium hidden sm:inline">Tercihler</span>
        </div>
        <div className={`h-0.5 w-12 ${step >= 2 ? 'bg-primary' : 'bg-muted-foreground/30'}`} />
        <div className={`flex items-center gap-2 ${step >= 2 ? 'text-primary' : 'text-muted-foreground'}`}>
          <div className={`w-8 h-8 rounded-full flex items-center justify-center border-2 ${step >= 2 ? 'bg-primary text-primary-foreground border-primary' : 'border-muted-foreground'}`}>
            2
          </div>
          <span className="text-sm font-medium hidden sm:inline">Önizleme</span>
        </div>
      </div>

      {/* Step 1: Preferences */}
      {step === 1 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Sparkles className="h-5 w-5 text-primary" />
              Kişiselleştirilmiş Rota Oluşturucu
            </CardTitle>
            <CardDescription>
              Seyahat tercihlerinizi bize bildirin, sizin için mükemmel bir Kapadokya rotası oluşturalım.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Duration */}
            <div className="space-y-3">
              <Label className="flex items-center gap-2">
                <Calendar className="h-4 w-4" />
                Seyahat Süresi
              </Label>
              <RadioGroup
                value={preferences.duration.toString()}
                onValueChange={(value) => setPreferences({ ...preferences, duration: parseInt(value) })}
                className="grid grid-cols-2 sm:grid-cols-4 gap-3"
              >
                {[2, 3, 4, 5].map((days) => (
                  <div key={days}>
                    <RadioGroupItem value={days.toString()} id={`days-${days}`} className="peer sr-only" />
                    <Label
                      htmlFor={`days-${days}`}
                      className="flex flex-col items-center justify-center rounded-lg border-2 border-muted bg-card p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 cursor-pointer transition-all"
                    >
                      <span className="text-2xl font-bold">{days}</span>
                      <span className="text-xs text-muted-foreground">gün</span>
                    </Label>
                  </div>
                ))}
              </RadioGroup>
            </div>

            {/* Interests */}
            <div className="space-y-3">
              <Label className="flex items-center gap-2">
                <Heart className="h-4 w-4" />
                İlgi Alanlarınız
              </Label>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                {INTEREST_OPTIONS.map((interest) => (
                  <div
                    key={interest.id}
                    onClick={() => handleInterestToggle(interest.id)}
                    className={`flex items-center gap-3 p-3 rounded-lg border-2 cursor-pointer transition-all ${
                      preferences.interests.includes(interest.id)
                        ? 'border-primary bg-primary/5'
                        : 'border-muted hover:border-primary/50'
                    }`}
                  >
                    <Checkbox
                      checked={preferences.interests.includes(interest.id)}
                      onCheckedChange={() => handleInterestToggle(interest.id)}
                    />
                    <div className="flex items-center gap-2">
                      <span className="text-xl">{interest.icon}</span>
                      <span className="text-sm font-medium">{interest.label}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Budget */}
            <div className="space-y-3">
              <Label className="flex items-center gap-2">
                <DollarSign className="h-4 w-4" />
                Bütçe Seviyesi
              </Label>
              <RadioGroup
                value={preferences.budget}
                onValueChange={(value: any) => setPreferences({ ...preferences, budget: value })}
                className="grid grid-cols-3 gap-3"
              >
                {[
                  { value: 'low', label: 'Ekonomik', icon: '💰' },
                  { value: 'medium', label: 'Orta', icon: '💵' },
                  { value: 'high', label: 'Lüks', icon: '💎' },
                ].map((option) => (
                  <div key={option.value}>
                    <RadioGroupItem value={option.value} id={`budget-${option.value}`} className="peer sr-only" />
                    <Label
                      htmlFor={`budget-${option.value}`}
                      className="flex flex-col items-center justify-center rounded-lg border-2 border-muted bg-card p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 cursor-pointer transition-all"
                    >
                      <span className="text-2xl mb-1">{option.icon}</span>
                      <span className="text-sm font-medium">{option.label}</span>
                    </Label>
                  </div>
                ))}
              </RadioGroup>
            </div>

            {/* Travel Style */}
            <div className="space-y-3">
              <Label className="flex items-center gap-2">
                <TrendingUp className="h-4 w-4" />
                Seyahat Temposu
              </Label>
              <RadioGroup
                value={preferences.travelStyle}
                onValueChange={(value: any) => setPreferences({ ...preferences, travelStyle: value })}
                className="grid grid-cols-3 gap-3"
              >
                {[
                  { value: 'relaxed', label: 'Rahat', desc: 'günde 2-3 yer' },
                  { value: 'moderate', label: 'Orta', desc: 'günde 4-5 yer' },
                  { value: 'intensive', label: 'Yoğun', desc: 'günde 6+ yer' },
                ].map((option) => (
                  <div key={option.value}>
                    <RadioGroupItem value={option.value} id={`style-${option.value}`} className="peer sr-only" />
                    <Label
                      htmlFor={`style-${option.value}`}
                      className="flex flex-col items-center justify-center rounded-lg border-2 border-muted bg-card p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 cursor-pointer transition-all"
                    >
                      <span className="text-sm font-bold mb-1">{option.label}</span>
                      <span className="text-xs text-muted-foreground">{option.desc}</span>
                    </Label>
                  </div>
                ))}
              </RadioGroup>
            </div>

            {/* Start Date (Optional) */}
            <div className="space-y-3">
              <Label htmlFor="start-date" className="flex items-center gap-2">
                <Calendar className="h-4 w-4" />
                Başlangıç Tarihi (İsteğe Bağlı)
              </Label>
              <Input
                id="start-date"
                type="date"
                value={preferences.startDate || ''}
                onChange={(e) => setPreferences({ ...preferences, startDate: e.target.value })}
              />
            </div>

            {/* Actions */}
            <div className="flex gap-3 pt-4">
              <Button variant="outline" onClick={onCancel} className="flex-1">
                İptal
              </Button>
              <Button onClick={handleGenerate} disabled={loading} className="flex-1">
                {loading ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Oluşturuluyor...
                  </>
                ) : (
                  <>
                    <Sparkles className="h-4 w-4 mr-2" />
                    Rota Oluştur
                  </>
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Step 2: Preview */}
      {step === 2 && generatedRoute && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MapPin className="h-5 w-5 text-primary" />
              Kişiselleştirilmiş Kapadokya Rotanız
            </CardTitle>
            <CardDescription>
              Önerilen rotayı inceleyin ve seyahat planınıza ekleyin.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* Summary */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              <div className="flex items-center gap-2 p-3 rounded-lg bg-muted">
                <Calendar className="h-4 w-4 text-primary" />
                <div>
                  <div className="text-xs text-muted-foreground">Süre</div>
                  <div className="font-bold">{generatedRoute.days.length} gün</div>
                </div>
              </div>
              <div className="flex items-center gap-2 p-3 rounded-lg bg-muted">
                <MapPin className="h-4 w-4 text-primary" />
                <div>
                  <div className="text-xs text-muted-foreground">Yerler</div>
                  <div className="font-bold">
                    {generatedRoute.days.reduce((sum, day) => sum + day.places.length, 0)}
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-2 p-3 rounded-lg bg-muted">
                <Mountain className="h-4 w-4 text-primary" />
                <div>
                  <div className="text-xs text-muted-foreground">Mesafe</div>
                  <div className="font-bold">{generatedRoute.totalDistance} km</div>
                </div>
              </div>
              <div className="flex items-center gap-2 p-3 rounded-lg bg-muted">
                <DollarSign className="h-4 w-4 text-primary" />
                <div>
                  <div className="text-xs text-muted-foreground">Tahm. Maliyet</div>
                  <div className="font-bold">${generatedRoute.estimatedCost}</div>
                </div>
              </div>
            </div>

            {/* Daily Itinerary */}
            <ScrollArea className="h-[400px] pr-4">
              <div className="space-y-6">
                {generatedRoute.days.map((day) => (
                  <div key={day.day} className="space-y-3">
                    <h3 className="font-bold text-lg flex items-center gap-2">
                      <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20">
                        {day.day}. Gün
                      </Badge>
                      <span className="text-sm text-muted-foreground">{day.date}</span>
                    </h3>
                    <div className="space-y-3 pl-4 border-l-2 border-muted ml-4">
                      {day.places.map((place, idx) => (
                        <div key={idx} className="relative group">
                          <div className="flex items-start gap-4 p-3 rounded-lg bg-muted/30 group-hover:bg-muted transition-colors">
                            {place.imageUrl && (
                              <img src={place.imageUrl} alt={place.name} className="w-16 h-16 rounded-md object-cover shrink-0" />
                            )}
                            <div>
                              <div className="font-bold text-sm">{place.name}</div>
                              <div className="text-xs text-muted-foreground mb-1">{place.category} • {place.duration} dk</div>
                              <p className="text-xs line-clamp-2">{place.description}</p>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </ScrollArea>

            {/* Actions */}
            <div className="flex gap-3 pt-4 border-t">
              <Button variant="outline" onClick={() => setStep(1)} className="flex-1">
                Geri
              </Button>
              <Button onClick={handleConfirm} className="flex-1">
                Planıma Ekle
              </Button>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
