import { supabase } from '@/db/supabase';
import { Check, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { placesApi, tripDaysApi } from '@/db/api';
import { useTripStore } from '@/store/useTripStore';
import { cn } from '@/lib/utils';
import { DaySelectionStep } from './wizard/DaySelectionStep';
import { PlaceSearchStep } from './wizard/PlaceSearchStep';
import { PreviewStep } from './wizard/PreviewStep';
import { TimeBlockSelectionStep } from './wizard/TimeBlockSelectionStep';

interface AddPlaceWizardProps {
  tripId: string;
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  initialDayId?: string;
  initialTimeBlock?: string;
}

const STEPS = [
  { id: 'day', title: 'Gün Seçimi' },
  { id: 'time', title: 'Vakit Seçimi' },
  { id: 'search', title: 'Yer Arama' },
  { id: 'preview', title: 'Önizleme' },
];

export const AddPlaceWizard: React.FC<AddPlaceWizardProps> = ({
  tripId,
  isOpen,
  onClose,
  onSuccess,
  initialDayId,
  initialTimeBlock,
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [isLoadingDays, setIsLoadingDays] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const addPlaceToDay = useTripStore(state => state.addPlaceToDay);
  const [days, setDays] = useState<any[]>([]);
  
  const [formData, setFormData] = useState({
    dayId: initialDayId || '',
    dayNumber: 0,
    date: '',
    timeBlock: initialTimeBlock || '',
    place: null as any,
    notes: '',
  });

  useEffect(() => {
    if (isOpen) {
      fetchDays();
      // If we have initial values, we can skip some steps if needed, 
      // but usually better to let user see the flow or jump to search
      if (initialDayId && initialTimeBlock) {
        setCurrentStep(2); // Jump to search
      } else if (initialDayId) {
        setCurrentStep(1); // Jump to time block
      }
    } else {
      // Reset state on close
      setCurrentStep(0);
      setFormData({
        dayId: '',
        dayNumber: 0,
        date: '',
        timeBlock: '',
        place: null,
        notes: '',
      });
    }
  }, [isOpen, tripId, initialDayId, initialTimeBlock]);

  const fetchDays = async () => {
    setIsLoadingDays(true);
    try {
      const tripDays = await tripDaysApi.getByTripId(tripId);
      setDays(tripDays);
      
      if (initialDayId) {
        const selectedDay = tripDays.find(d => d.id === initialDayId);
        if (selectedDay) {
          setFormData(prev => ({
            ...prev,
            dayId: selectedDay.id,
            dayNumber: selectedDay.day_number,
            date: selectedDay.date
          }));
        }
      }
    } catch (error) {
      console.error('Günler getirilirken hata:', error);
      toast.error('Gün bilgileri alınamadı.');
    } finally {
      setIsLoadingDays(false);
    }
  };

  const handleNext = () => {
    if (currentStep < STEPS.length - 1) {
      setCurrentStep(prev => prev + 1);
    } else {
      handleSave();
    }
  };

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

  const handleSave = async () => {
    if (!formData.dayId || !formData.place) {
      toast.error('Lütfen tüm gerekli alanları doldurun.');
      return;
    }

    setIsSaving(true);
    try {
      // 1. First, check if place exists in our DB, if not, we might need to create it 
      // or just use the info from search. 
      // For simplicity in this wizard, we'll try to find by name or create a minimal entry.
      // But wait, our trip_places needs a place_id.
      
      let placeId = '';
      
      // Try to find if this place already exists in our system
      const existingPlaces = await placesApi.search(formData.place.name);
      const exactMatch = existingPlaces.find(p => p.name === formData.place.name);
      
      if (exactMatch) {
        placeId = exactMatch.id;
      } else {
        // Create a new place entry from search result
        // We'll use a RPC or direct insert if allowed
        const { data: newPlace, error: placeError } = await (supabase as any)
          .from('places')
          .insert([{
            name: formData.place.name,
            address: formData.place.address,
            image_url: formData.place.image_url,
            description: formData.place.snippet,
            // You might want to parse lat/lng if available from a more robust API
          }])
          .select()
          .single();
        
        if (placeError) throw placeError;
        placeId = newPlace.id;
      }

      // 2. Add to trip_day
      await addPlaceToDay(placeId, formData.dayId, {
        time_block: formData.timeBlock,
        notes: formData.notes,
      });

      toast.success('Yer başarıyla eklendi!');
      if (onSuccess) onSuccess();
      onClose();
    } catch (error: any) {
      console.error('Kaydetme hatası:', error);
      toast.error('Kaydedilirken bir hata oluştu: ' + error.message);
    } finally {
      setIsSaving(false);
    }
  };

  const isNextDisabled = () => {
    if (currentStep === 0) return !formData.dayId || isLoadingDays;
    if (currentStep === 1) return !formData.timeBlock;
    if (currentStep === 2) return !formData.place;
    return false;
  };

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

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="sm:max-w-[500px] p-0 overflow-hidden flex flex-col max-h-[90vh]">
        <DialogHeader className="p-6 pb-2">
          <DialogTitle className="flex items-center justify-between">
            <span>Yeni Yer Ekle</span>
            <span className="text-xs font-normal text-muted-foreground">Adım {currentStep + 1} / {STEPS.length}</span>
          </DialogTitle>
          <div className="pt-4">
            <Progress value={progress} className="h-1" />
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto p-6 pt-2">
          {currentStep === 0 && (
            <DaySelectionStep
              days={days}
              selectedDayId={formData.dayId}
              onSelect={(id, num, date) => setFormData(prev => ({ ...prev, dayId: id, dayNumber: num, date: date || '' }))}
            />
          )}
          {currentStep === 1 && (
            <TimeBlockSelectionStep
              selectedBlock={formData.timeBlock}
              onSelect={(block) => setFormData(prev => ({ ...prev, timeBlock: block }))}
            />
          )}
          {currentStep === 2 && (
            <PlaceSearchStep
              initialQuery={formData.place?.name || ''}
              selectedPlace={formData.place}
              onSelect={(place) => setFormData(prev => ({ ...prev, place }))}
            />
          )}
          {currentStep === 3 && (
            <PreviewStep
              data={formData}
              onNotesChange={(notes) => setFormData(prev => ({ ...prev, notes }))}
            />
          )}
        </div>

        <DialogFooter className="p-6 pt-2 border-t bg-muted/20">
          <div className="flex w-full justify-between items-center">
            <Button
              variant="ghost"
              onClick={handleBack}
              disabled={currentStep === 0 || isSaving}
              className={cn(currentStep === 0 && "invisible")}
            >
              <ChevronLeft className="w-4 h-4 mr-2" />
              Geri
            </Button>
            
            <Button
              onClick={handleNext}
              disabled={isNextDisabled() || isSaving}
              className="min-w-[100px]"
            >
              {isSaving ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : currentStep === STEPS.length - 1 ? (
                <>
                  <Check className="w-4 h-4 mr-2" />
                  Tamamla
                </>
              ) : (
                <>
                  İleri
                  <ChevronRight className="w-4 h-4 ml-2" />
                </>
              )}
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};


