import { format } from 'date-fns';
import { tr } from 'date-fns/locale';
import { ArrowLeft, ArrowRight, CalendarIcon, Check, Heart, MapPin, Sparkles } from 'lucide-react';
import { useState } from 'react';
import type { DateRange } from 'react-day-picker';
import { useNavigate } from 'react-router-dom';
import { LoadingOverlay } from '@/components/trip/LoadingOverlay';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerDescription,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  DrawerTrigger,
} from "@/components/ui/drawer";
import { Progress } from '@/components/ui/progress';
import { useAuth } from '@/contexts/AuthContext';
import { useIsMobile } from "@/hooks/use-mobile";
import { tripDaysApi, tripsApi, tripsApiSafe } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';

interface CreateTripWizardProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const INTEREST_OPTIONS = [
  { value: 'nature', label: 'Doğa', icon: '🌲' },
  { value: 'history', label: 'Tarih', icon: '🏛️' },
  { value: 'adventure', label: 'Macera', icon: '🧗' },
  { value: 'gastronomy', label: 'Gastronomi', icon: '🍽️' },
  { value: 'photography', label: 'Fotoğrafçılık', icon: '📸' },
  { value: 'culture', label: 'Kültür', icon: '🎭' },
  { value: 'relaxation', label: 'Dinlenme', icon: '🧘' },
  { value: 'shopping', label: 'Alışveriş', icon: '🛍️' },
];

const STEPS = [
  { id: 1, title: 'Destinasyon', description: 'Nereye gitmek istersiniz?' },
  { id: 2, title: 'Tarihler', description: 'Ne zaman seyahat edeceksiniz?' },
  { id: 3, title: 'İlgi Alanları', description: 'Nelerle ilgileniyorsunuz?' },
  { id: 4, title: 'Özet', description: 'Seyahatinizi oluşturun' },
];

export function CreateTripWizard({ open, onOpenChange }: CreateTripWizardProps) {
  const navigate = useNavigate();
  const { user } = useAuth();
  const isMobile = useIsMobile();
  const { toast } = useToast();
  const [currentStep, setCurrentStep] = useState(1);
  const [isCreating, setIsCreating] = useState(false);

  // Form state
  const [destination, setDestination] = useState('');
  const [date, setDate] = useState<DateRange | undefined>();
  const [selectedInterests, setSelectedInterests] = useState<string[]>([]);

  const progress = (currentStep / STEPS.length) * 100;

  const handleNext = () => {
    if (currentStep === 1 && !destination.trim()) {
      toast({
        title: 'Destinasyon gerekli',
        description: 'Lütfen bir destinasyon girin',
        variant: 'destructive',
      });
      return;
    }

    if (currentStep === 2 && (!date?.from || !date?.to)) {
      toast({
        title: 'Tarih seçimi gerekli',
        description: 'Lütfen başlangıç ve bitiş tarihlerini seçin',
        variant: 'destructive',
      });
      return;
    }

    if (currentStep === 3 && selectedInterests.length === 0) {
      toast({
        title: 'İlgi alanı seçimi gerekli',
        description: 'Lütfen en az bir ilgi alanı seçin',
        variant: 'destructive',
      });
      return;
    }

    if (currentStep < STEPS.length) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

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

  const handleCreateTrip = async () => {
    if (!user || !date?.from || !date?.to) return;

    setIsCreating(true);

    try {
      // Seyahat oluştur (GÜVENLİ)
      const trip = await tripsApiSafe.create({
        title: `${destination} Seyahati`,
        destination,
        start_date: date.from.toISOString().split('T')[0],
        end_date: date.to.toISOString().split('T')[0],
        interests: selectedInterests,
      });

      // Günleri oluştur
      await tripDaysApi.createDaysForTrip(
        trip.id,
        date.from.toISOString().split('T')[0],
        date.to.toISOString().split('T')[0]
      );

      // AI ile otomatik plan oluştur
      await tripsApi.generateItinerary(
        trip.id,
        selectedInterests,
        date.from.toISOString().split('T')[0],
        date.to.toISOString().split('T')[0],
        destination,
        'auto_seed'
      );

      toast({
        title: 'Seyahat oluşturuldu! 🎉',
        description: 'AI ile otomatik plan oluşturuldu. Şimdi düzenleyebilirsiniz.',
      });

      // Planner sayfasına yönlendir
      navigate(`/planner?tripId=${trip.id}`);
      onOpenChange(false);
    } catch (error: any) {
      console.error('Seyahat oluşturma hatası:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Seyahat oluşturulurken bir hata oluştu',
        variant: 'destructive',
      });
    } finally {
      setIsCreating(false);
    }
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 1:
        return (
          <div className="space-y-4">
            <div className="flex items-center justify-center mb-6">
              <div className="rounded-full bg-primary/10 p-4">
                <MapPin className="h-8 w-8 text-primary" />
              </div>
            </div>
            <div className="space-y-2">
              <Label htmlFor="destination">Destinasyon</Label>
              <Input
                id="destination"
                placeholder="Örn: Kapadokya, Türkiye"
                value={destination}
                onChange={(e) => setDestination(e.target.value)}
                autoFocus
              />
              <p className="text-xs text-muted-foreground">
                Gitmek istediğiniz şehir veya bölgeyi yazın
              </p>
            </div>
          </div>
        );

      case 2:
        return (
          <div className="space-y-4">
            <div className="flex items-center justify-center mb-6">
              <div className="rounded-full bg-primary/10 p-4">
                <CalendarIcon className="h-8 w-8 text-primary" />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Seyahat Tarihleri</Label>
              {isMobile ? (
                <Drawer>
                  <DrawerTrigger asChild>
                    <Button
                      variant="outline"
                      className={cn(
                        'w-full justify-start text-left font-normal text-lg h-14',
                        !date && 'text-muted-foreground'
                      )}
                    >
                      <CalendarIcon className="mr-3 h-5 w-5" />
                      {date?.from ? (
                        date.to ? (
                          <>
                            {format(date.from, 'dd MMM yyyy', { locale: tr })} -{' '}
                            {format(date.to, 'dd MMM yyyy', { locale: tr })}
                          </>
                        ) : (
                          format(date.from, 'dd MMM yyyy', { locale: tr })
                        )
                      ) : (
                        <span>Tarih seçin</span>
                      )}
                    </Button>
                  </DrawerTrigger>
                  <DrawerContent>
                    <DrawerHeader>
                      <DrawerTitle>Seyahat Tarihleri</DrawerTitle>
                      <DrawerDescription>Başlangıç ve bitiş tarihlerini belirleyin</DrawerDescription>
                    </DrawerHeader>
                    <div className="flex justify-center p-1 sm:p-4">
                      <Calendar
                        initialFocus
                        mode="range"
                        defaultMonth={date?.from}
                        selected={date}
                        onSelect={setDate}
                        numberOfMonths={1}
                        locale={tr}
                        className="w-full max-w-[320px]"
                      />
                    </div>
                    <DrawerFooter>
                      <DrawerClose asChild>
                        <Button className="w-full">Seçimi Tamamla</Button>
                      </DrawerClose>
                    </DrawerFooter>
                  </DrawerContent>
                </Drawer>
              ) : (
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      className={cn(
                        'w-full justify-start text-left font-normal',
                        !date && 'text-muted-foreground'
                      )}
                    >
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {date?.from ? (
                        date.to ? (
                          <>
                            {format(date.from, 'dd MMM yyyy', { locale: tr })} -{' '}
                            {format(date.to, 'dd MMM yyyy', { locale: tr })}
                          </>
                        ) : (
                          format(date.from, 'dd MMM yyyy', { locale: tr })
                        )
                      ) : (
                        <span>Tarih seçin</span>
                      )}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      initialFocus
                      mode="range"
                      defaultMonth={date?.from}
                      selected={date}
                      onSelect={setDate}
                      numberOfMonths={2}
                      locale={tr}
                    />
                  </PopoverContent>
                </Popover>
              )}
              <p className="text-xs text-muted-foreground">
                Başlangıç ve bitiş tarihlerini seçin
              </p>
            </div>
          </div>
        );

      case 3:
        return (
          <div className="space-y-4">
            <div className="flex items-center justify-center mb-6">
              <div className="rounded-full bg-primary/10 p-4">
                <Heart className="h-8 w-8 text-primary" />
              </div>
            </div>
            <div className="space-y-2">
              <Label>İlgi Alanlarınız</Label>
              <div className="grid grid-cols-2 gap-2">
                {INTEREST_OPTIONS.map((interest) => (
                  <Badge
                    key={interest.value}
                    variant={selectedInterests.includes(interest.value) ? 'default' : 'outline'}
                    className="cursor-pointer justify-start gap-2 py-3 px-4 text-sm"
                    onClick={() => handleInterestToggle(interest.value)}
                  >
                    <span className="text-lg">{interest.icon}</span>
                    {interest.label}
                  </Badge>
                ))}
              </div>
              <p className="text-xs text-muted-foreground">
                İlgi alanlarınıza göre AI size özel öneriler sunacak
              </p>
            </div>
          </div>
        );

      case 4:
        return (
          <div className="space-y-4">
            <div className="flex items-center justify-center mb-6">
              <div className="rounded-full bg-primary/10 p-4">
                <Sparkles className="h-8 w-8 text-primary" />
              </div>
            </div>
            <div className="space-y-4 rounded-lg border p-4">
              <div>
                <p className="text-sm text-muted-foreground">Destinasyon</p>
                <p className="font-semibold">{destination}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Tarihler</p>
                <p className="font-semibold">
                  {date?.from && date?.to
                    ? `${format(date.from, 'dd MMM yyyy', { locale: tr })} - ${format(date.to, 'dd MMM yyyy', { locale: tr })}`
                    : '-'}
                </p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-2">İlgi Alanları</p>
                <div className="flex flex-wrap gap-2">
                  {selectedInterests.map((interest) => {
                    const option = INTEREST_OPTIONS.find((opt) => opt.value === interest);
                    return (
                      <Badge key={interest} variant="secondary">
                        {option?.icon} {option?.label}
                      </Badge>
                    );
                  })}
                </div>
              </div>
            </div>
            <div className="rounded-lg bg-primary/5 p-4">
              <p className="text-sm text-muted-foreground">
                ✨ AI, ilgi alanlarınıza göre otomatik olarak bir seyahat planı oluşturacak. 
                Daha sonra istediğiniz gibi düzenleyebilirsiniz.
              </p>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <>
      <LoadingOverlay isVisible={isCreating} />
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>{STEPS[currentStep - 1].title}</DialogTitle>
          <DialogDescription>{STEPS[currentStep - 1].description}</DialogDescription>
        </DialogHeader>

        {/* Progress Bar */}
        <div className="space-y-2">
          <Progress value={progress} className="h-2" />
          <div className="flex justify-between text-xs text-muted-foreground">
            <span>Adım {currentStep} / {STEPS.length}</span>
            <span>%{Math.round(progress)} tamamlandı</span>
          </div>
        </div>

        {/* Step Content */}
        <div className="py-6">{renderStepContent()}</div>

        {/* Navigation Buttons */}
        <div className="flex justify-between gap-2">
          <Button
            variant="outline"
            onClick={handleBack}
            disabled={currentStep === 1 || isCreating}
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            Geri
          </Button>

          {currentStep < STEPS.length ? (
            <Button onClick={handleNext}>
              İleri
              <ArrowRight className="ml-2 h-4 w-4" />
            </Button>
          ) : (
            <Button onClick={handleCreateTrip} disabled={isCreating}>
              {isCreating ? (
                <>
                  <span className="mr-2">Oluşturuluyor...</span>
                  <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
                </>
              ) : (
                <>
                  <Check className="mr-2 h-4 w-4" />
                  Seyahati Oluştur
                </>
              )}
            </Button>
          )}
        </div>
      </DialogContent>
    </Dialog>
    </>
  );
}
