import { format } from 'date-fns';
import { tr } from 'date-fns/locale';
import { 
  Calendar as CalendarIcon, 
  MapPin, 
  Search, 
  Sparkles, 
  Users,
  Plane,
  Trees,
  Landmark,
  Camera,
  Mountain,
  UtensilsCrossed
} from 'lucide-react';
import React, { useEffect, useState } from 'react';
import type { DateRange } from 'react-day-picker';
import { useLocation, useNavigate } from 'react-router-dom';
import { HotelSearch } from '@/components/trip/HotelSearch';
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 { 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from '@/components/ui/skeleton';
import { useAuth } from '@/contexts/AuthContext';
import { useCurrentTrip } from '@/contexts/CurrentTripContext';
import { placesApi, siteSettingsApi, tripDaysApi, tripPlacesApi, tripsApi, tripsApiSafe } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import { useIsMobile } from "@/hooks/use-mobile";
import { cn } from '@/lib/utils';

const CreateTrip = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { user, profile } = useAuth();
  const { toast } = useToast();
  const { setCurrentTripId } = useCurrentTrip();
  const [date, setDate] = useState<DateRange | undefined>({
    from: new Date(),
    to: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
  });
  const [travelers, setTravelers] = useState('2');
  const [selectedInterests, setSelectedInterests] = useState<string[]>([]);
  const [heroImage, setHeroImage] = useState<string | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [startLocation, setStartLocation] = useState<{
    type: 'hotel' | 'custom' | 'city_center';
    name?: string;
    lat?: number;
    lng?: number;
  }>({
    type: 'city_center',
    name: 'Göreme Merkez',
    lat: 38.6431,
    lng: 34.8289,
  });
  
  const isMobile = useIsMobile();
  
  // Explore'dan gelen pendingPlaceId'yi al
  const pendingPlaceId = location.state?.pendingPlaceId;

  useEffect(() => {
    loadHeroImage();
  }, []); // ✅ Sadece 1 kez çalışıyor

  const loadHeroImage = async () => {
    try {
      const setting = await siteSettingsApi.getByKey('hero_image');
      if (setting?.value) {
        setHeroImage(setting.value); // ✅ Sadece setHeroImage yapıyor
      }
    } catch (error) {
      console.error('Hero görsel yüklenirken hata:', error);
      // ✅ Hata durumunda heroImage null kalıyor, skeleton gösterilmeye devam ediyor
    }
  };
  
  const interests = [
    { id: 'balloon', label: 'Sıcak Hava Balonu', icon: Plane },
    { id: 'nature', label: 'Doğa ve Yürüyüş', icon: Trees },
    { id: 'history', label: 'Tarih ve Kültür', icon: Landmark },
    { id: 'photography', label: 'Fotoğraf Çekimi', icon: Camera },
    { id: 'adventure', label: 'Aktivite/Macera', icon: Mountain },
    { id: 'gastronomy', label: 'Gastronomi', icon: UtensilsCrossed },
  ];

  const toggleInterest = (interestId: string) => {
    setSelectedInterests(prev => 
      prev.includes(interestId)
        ? prev.filter(id => id !== interestId)
        : [...prev, interestId]
    );
  };

  const createTripRecord = async (startDate: string, endDate: string) => {
    const destination = 'Kapadokya, Türkiye';
    return await tripsApiSafe.create({
      title: `${destination} Seyahati`,
      destination,
      start_date: startDate,
      end_date: endDate,
      interests: selectedInterests.length > 0 ? selectedInterests : undefined,
      is_public: false,
      start_location_type: startLocation.type,
      start_location_name: startLocation.name,
      start_lat: startLocation.lat,
      start_lng: startLocation.lng,
      number_of_travelers: parseInt(travelers),
      user_id: profile?.id || null,
    });
  };

  const createTripDays = async (tripId: string, startDate: string, endDate: string) => {
    await tripDaysApi.createDaysForTrip(
      tripId,
      startDate,
      endDate
    );
  };

  const generateTripPlan = async (tripId: string, startDate: string, endDate: string) => {
    const destination = 'Kapadokya, Türkiye';
    try {
      await tripsApi.generateItinerary(
        tripId,
        selectedInterests,
        startDate,
        endDate,
        destination,
        'auto_seed'
      );
    } catch (error: any) {
      console.error('Plan oluşturma hatası:', error);
      toast({
        title: 'Plan Oluşturulamadı',
        description: 'Otomatik plan oluşturulurken bir sorun oluştu, ancak seyahatiniz oluşturuldu. Kendiniz yer ekleyebilirsiniz.',
        variant: 'destructive',
      });
    }
  };

  const addPendingPlace = async (tripId: string) => {
    if (!pendingPlaceId) return;
    
    try {
      const tripDays = await tripDaysApi.getByTripId(tripId);
      if (tripDays && tripDays.length > 0) {
        const firstDayId = tripDays[0].id;
        const existingPlace = await tripPlacesApi.getByDayAndPlace(firstDayId, pendingPlaceId);

        if (!existingPlace) {
          const placesInDay = await tripPlacesApi.getByDayId(firstDayId);
          const lastOrderIndex = placesInDay.length > 0 
            ? Math.max(...placesInDay.map(p => p.order_index || 0)) 
            : 0;

          const place = await placesApi.getById(pendingPlaceId);
          await tripPlacesApi.addToDay({
            place_id: pendingPlaceId,
            trip_day_id: firstDayId,
            order_index: lastOrderIndex + 1,
            duration: place?.duration || '2 saat',
          });

          toast({
            title: 'Başarılı',
            description: 'Seçtiğiniz yer seyahatinize eklendi!',
          });
        }
      }
    } catch (error) {
      console.error('Pending place ekleme hatası:', error);
    }
  };

  const handleCreateTrip = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!date?.from || !date?.to) {
      toast({
        title: 'Hata',
        description: 'Lütfen tarih seçin',
        variant: 'destructive',
      });
      return;
    }

    if ((startLocation.type === 'hotel' || startLocation.type === 'custom') && 
        (!startLocation.lat || !startLocation.lng)) {
      toast({
        title: 'Eksik Bilgi',
        description: 'Lütfen konaklama noktanızı seçin veya "Merkezden Başla" seçeneğini kullanın',
        variant: 'destructive',
      });
      return;
    }

    const startDate = date.from!.toISOString().split('T')[0];
    const endDate = date.to!.toISOString().split('T')[0];

    try {
      setIsCreating(true);
      // We pass the profile.id if available (linked Supabase profile UUID)
      const trip = await createTripRecord(startDate, endDate);
      setCurrentTripId(trip.id);
      await createTripDays(trip.id, startDate, endDate);
      await generateTripPlan(trip.id, startDate, endDate);
      await addPendingPlace(trip.id);
      navigate(`/planner?trip_id=${trip.id}`, { replace: true });
    } catch (error: any) {
      console.error('Seyahat oluşturma hatası:', error);
      toast({
        title: 'Hata',
        description: error?.message || 'Bilinmeyen hata',
        variant: 'destructive',
      });
      setIsCreating(false);
    }
  };

  // Son aramalar (örnek veri)
  const recentSearches = [
    { destination: 'Kapadokya, Türkiye', dates: '10-17 Mart 2026', travelers: 2 },
    { destination: 'Kapadokya, Türkiye', dates: '1-5 Nisan 2026', travelers: 4 },
    { destination: 'Kapadokya, Türkiye', dates: '20-25 Nisan 2026', travelers: 2 },
  ];

  return (
    <>
      <div className="flex flex-col md:flex-row min-h-[calc(100vh-64px)] overflow-hidden">
      {/* Form Area */}
      <div className="w-full md:w-1/2 flex items-center justify-center p-8 lg:p-16 bg-white dark:bg-background overflow-y-auto">
        <div className="max-w-md w-full">
          <div className="mb-10">
            <h1 className="text-3xl font-bold mb-2">Kapadokya maceranızı planlayın</h1>
            <p className="text-muted-foreground">Tarihleri belirleyin, ilgi alanlarınızı seçin ve yola çıkın.</p>
          </div>

          <form onSubmit={handleCreateTrip} className="space-y-6">
            <div className="space-y-2">
              <Label htmlFor="destination">Destinasyon</Label>
              <div className="relative">
                <MapPin className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input 
                  id="destination" 
                  value="Kapadokya, Türkiye"
                  className="pl-10 h-12 bg-muted cursor-not-allowed"
                  disabled
                  readOnly
                />
              </div>
              <p className="text-xs text-muted-foreground">Bu seyahat için destinasyon sabittir</p>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Tarihler</Label>
                {isMobile ? (
                  <Drawer>
                    <DrawerTrigger asChild>
                      <Button
                        variant="outline"
                        className={cn(
                          "w-full h-12 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!, "d MMM", { locale: tr })} - {" "}
                              {format(date.to!, "d MMM", { locale: tr })}
                            </>
                          ) : (
                            format(date.from!, "d MMM", { locale: tr })
                          )
                        ) : (
                          <span>Tarih seçin</span>
                        )}
                      </Button>
                    </DrawerTrigger>
                    <DrawerContent className="p-0">
                      <DrawerHeader className="border-b">
                        <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 className="border-t p-4">
                        <DrawerClose asChild>
                          <Button className="w-full">Seçimi Tamamla</Button>
                        </DrawerClose>
                      </DrawerFooter>
                    </DrawerContent>
                  </Drawer>
                ) : (
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        className={cn(
                          "w-full h-12 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!, "d MMM", { locale: tr })} - {" "}
                              {format(date.to!, "d MMM", { locale: tr })}
                            </>
                          ) : (
                            format(date.from!, "d MMM", { 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>
                )}
              </div>

              <div className="space-y-2">
                <Label>Yolcu Sayısı</Label>
                <Select value={travelers} onValueChange={setTravelers}>
                  <SelectTrigger className="h-12">
                    <Users className="mr-2 h-4 w-4 text-muted-foreground" />
                    <SelectValue placeholder="Seçin" />
                  </SelectTrigger>
                  <SelectContent>
                    {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((num) => (
                      <SelectItem key={num} value={num.toString()}>
                        {num} Yolcu
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Konaklama Başlangıç Noktası */}
            <HotelSearch value={startLocation} onChange={setStartLocation} />

            {/* İlgi Alanları */}
            <div className="space-y-3">
              <div className="flex items-center gap-2">
                <Sparkles className="h-4 w-4 text-primary" />
                <Label>İlgi Alanlarınız</Label>
              </div>
              <p className="text-sm text-muted-foreground">
                Seyahat planınızı kişiselleştirmek için ilgi alanlarınızı seçin
              </p>
              <div className="flex flex-wrap gap-2">
                {interests.map((interest) => {
                  const IconComponent = interest.icon;
                  return (
                    <Badge
                      key={interest.id}
                      variant={selectedInterests.includes(interest.id) ? "default" : "outline"}
                      className={cn(
                        "cursor-pointer py-2 px-4 text-sm transition-all",
                        selectedInterests.includes(interest.id)
                          ? "bg-primary text-white hover:bg-primary/90"
                          : "hover:bg-primary/10 hover:border-primary"
                      )}
                      onClick={() => toggleInterest(interest.id)}
                    >
                      <IconComponent className="h-4 w-4 mr-1.5" />
                      {interest.label}
                    </Badge>
                  );
                })}
              </div>
            </div>

            <Button type="submit" size="lg" className="w-full h-14 rounded-full bg-primary text-lg font-bold">
              Seyahat Oluştur
            </Button>
          </form>

          <div className="mt-12 pt-8 border-t">
            <h4 className="text-sm font-semibold mb-4 text-muted-foreground uppercase tracking-wider">Son Aramalar</h4>
            <div className="space-y-3">
              {recentSearches.map((search, i) => (
                <div key={i} className="flex items-center gap-3 p-3 rounded-xl hover:bg-muted cursor-pointer transition-colors border border-transparent hover:border-border">
                  <div className="w-10 h-10 rounded-lg bg-accent/10 text-accent flex items-center justify-center shrink-0">
                    <MapPin className="h-5 w-5" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-medium truncate">{search.destination}</div>
                    <div className="text-xs text-muted-foreground">{search.dates} • {search.travelers} kişi</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Hero Image Area */}
      <div className="hidden md:block w-1/2 relative bg-slate-200 min-h-[calc(100vh-64px)]">
        {heroImage ? (
          <>
            <img 
              src={heroImage} 
              alt="Seyahat" 
              className="w-full h-full object-cover absolute inset-0"
            />
            <div className="absolute inset-0 bg-black/20" />
            <div className="absolute bottom-12 left-12 right-12 text-white">
              <h2 className="text-4xl font-bold mb-4 italic">"Dünya bir kitaptır ve seyahat etmeyenler onun sadece bir sayfasını okurlar."</h2>
              <p className="text-xl text-white/80">— Aziz Augustinus</p>
            </div>
          </>
        ) : (
          <Skeleton className="w-full h-full absolute inset-0 bg-muted" />
        )}
      </div>
    </div>

    {/* Loading Overlay */}
    <LoadingOverlay isVisible={isCreating} />
  </>
  );
};

export default CreateTrip;
