import { AlertCircle, Loader2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';
import { toursApi } from '@/db/api';
import type { AITourAnalysis, Tour } from '@/types';
import { getServiceTypeMetadata } from '@/types/service-types';
import TourCard from './TourCard';

interface TourModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  analysis: AITourAnalysis;
  destination: string;
  placeTypes: string[];
  travelers: number;
  onTourSelect: (tour: Tour) => void;
}

export default function TourModal({
  open,
  onOpenChange,
  analysis,
  destination,
  placeTypes,
  travelers,
  onTourSelect,
}: TourModalProps) {
  const [tours, setTours] = useState<Tour[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Get service type metadata from the shared enum
  const serviceTypeMetadata = getServiceTypeMetadata(analysis.recommended_type);
  
  // Use AI-provided display metadata if available, otherwise fall back to enum metadata
  const displayLabel = analysis.display_metadata?.service_type_label || serviceTypeMetadata?.label || analysis.recommended_type || 'Önerilen Hizmet';
  const groupLabel = analysis.display_metadata?.group_label || 'Önerilen Turlar';

  useEffect(() => {
    if (open) {
      loadTours();
    }
  }, [open, destination, analysis.recommended_type]);

  const loadTours = async () => {
    setLoading(true);
    setError(null);

    try {
      console.log('🔍 Loading tours with params:', {
        destination,
        recommended_type: analysis.recommended_type,
        place_types: placeTypes,
        travelers,
        daily_tour_slug: analysis.daily_tour_slug
      });

      const result = await toursApi.searchTours({
        destination,
        recommended_type: analysis.recommended_type,
        place_types: placeTypes,
        travelers,
        daily_tour_slug: analysis.daily_tour_slug, // Pass AI-recommended tour slug
      });

      console.log('✅ Tours loaded:', result);
      setTours(result);

      if (result.length === 0) {
        setError('Bu kriterlere uygun tur bulunamadı. Lütfen daha sonra tekrar deneyin.');
      }
    } catch (err: any) {
      console.error('❌ Error loading tours:', err);
      console.error('  - Error message:', err?.message);
      console.error('  - Error details:', err);
      setError(`Turlar yüklenirken bir hata oluştu: ${err?.message || 'Bilinmeyen hata'}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh]">
        <DialogHeader>
          <DialogTitle>{groupLabel}</DialogTitle>
          <DialogDescription>
            {destination} için {displayLabel} türünde turlar
          </DialogDescription>
        </DialogHeader>

        <ScrollArea className="h-[calc(90vh-120px)] pr-4">
          {loading && (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          )}

          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {!loading && !error && tours.length > 0 && (
            <div className="grid gap-6 md:grid-cols-2">
              {tours.map((tour, idx) => (
                <TourCard
                  key={tour.id}
                  tour={tour}
                  onSelect={onTourSelect}
                  isRecommended={idx === 0}
                />
              ))}
            </div>
          )}
        </ScrollArea>
      </DialogContent>
    </Dialog>
  );
}
