import { 
  AlertCircle,
  Calendar, 
  Clock,
  Download,
  ExternalLink,
  FileDown, 
  MapPin 
} from 'lucide-react';
import React, { useEffect, useMemo, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { SEOHead } from '@/components/seo/SEOHead';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import LeafletMapWrapper from '@/components/ui/LeafletMapWrapper';
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { Skeleton } from '@/components/ui/skeleton';
import { tripsApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';
import { exportMultiPagePDF } from '@/lib/pdf-export';
import { 
  assignTimeBlocks, 
  getTimeBlockLabel as getBlockLabel,
  groupPlacesByTimeBlock as groupByTimeBlock, 
  type TimeBlock 
} from '@/lib/time-blocks';
import { cn } from '@/lib/utils';

/**
 * PublicTrip - Herkese açık seyahat görüntüleme sayfası
 * Read-only (salt okunur) - Düzenleme özellikleri YOK
 * PDF olarak dışa aktarılabilir
 */
export default function PublicTrip() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const { toast } = useToast();
  
  const [trip, setTrip] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeDayId, setActiveDayId] = useState<string | null>(null);
  const [selectedPlaceId, setSelectedPlaceId] = useState<string | null>(null);
  const [hoveredPlaceId, setHoveredPlaceId] = useState<string | null>(null);

  // Seyahati yükle
  useEffect(() => {
    const loadTrip = async () => {
      if (!slug) {
        setError('Geçersiz link');
        setLoading(false);
        return;
      }

      try {
        setLoading(true);
        const data = await tripsApi.getTripBySlug(slug);
        
        if (!data) {
          setError('Seyahat bulunamadı veya artık paylaşılmıyor');
          setLoading(false);
          return;
        }

        // Günleri tarihe göre sırala
        const sortedDays = (data.trip_days || [])
          .sort((a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime())
          .map((day: any) => ({
            id: day.id,
            date: day.date,
            places: (day.trip_places || [])
              .sort((a: any, b: any) => a.order_index - b.order_index)
              .map((tp: any) => {
                // Null guard: places ilişkisi yoksa bu kaydı atla
                if (!tp.places) {
                  console.warn('Missing place relation for trip_place:', tp.id);
                  return null;
                }

                return {
                  id: tp.places.id,
                  tripPlaceId: tp.id,
                  name: tp.places.name,
                  type: tp.places.type,
                  description: tp.places.description,
                  image: tp.places.image_url || tp.places.image,
                  lat: tp.places.latitude,
                  lng: tp.places.longitude,
                  rating: tp.places.rating,
                  duration: tp.places.duration || tp.duration || '2 saat',
                  order_index: tp.order_index,
                  dayId: day.id,
                };
              })
              .filter(Boolean),
          }));

        setTrip({
          ...data,
          days: sortedDays,
        });

        // İlk günü aktif yap
        if (sortedDays.length > 0) {
          setActiveDayId(sortedDays[0].id);
        }
      } catch (err: any) {
        console.error('Seyahat yükleme hatası:', err);
        setError('Seyahat yüklenirken bir hata oluştu');
      } finally {
        setLoading(false);
      }
    };

    loadTrip();
  }, [slug]);

  // Aktif gün
  const activeDay = useMemo(() => {
    if (!trip || !activeDayId) return null;
    return trip.days.find((d: any) => d.id === activeDayId);
  }, [trip, activeDayId]);

  // Tüm yerler (harita için)
  const allPlaces = useMemo(() => {
    if (!trip) return [];
    return trip.days.flatMap((day: any) => 
      day.places.map((place: any) => ({
        ...place,
        dayId: day.id,
      }))
    );
  }, [trip]);

  // Aktif gün yerleri (harita için)
  const activeDayPlaces = useMemo(() => {
    if (!activeDay) return [];
    return activeDay.places;
  }, [activeDay]);

  // Zaman bloğu hesaplama
  const getTimeBlocksForPlaces = useMemo(() => {
    return (places: any[]) => {
      return assignTimeBlocks(places);
    };
  }, []);

  const getTimeBlockLabel = (block: TimeBlock): string => {
    return getBlockLabel(block);
  };

  const groupPlacesByTimeBlock = (places: any[]) => {
    const timeBlockMap = getTimeBlocksForPlaces(places);
    return groupByTimeBlock(places, timeBlockMap);
  };

  // PDF Export
  const handleExportPDF = async () => {
    if (!trip) {
      toast({
        title: 'Hata',
        description: 'Seyahat bilgisi bulunamadı.',
        variant: 'destructive',
      });
      return;
    }

    try {
      toast({
        title: 'PDF Oluşturuluyor',
        description: 'Lütfen bekleyin...',
      });

      // Trip data'yı PDF formatına dönüştür
      const pdfData = {
        title: trip.title || 'Seyahat Planı',
        destination: trip.destination || '',
        start_date: trip.start_date || '',
        end_date: trip.end_date || '',
        days: trip.days?.map((day: any) => {
          const timeBlockMap = assignTimeBlocks(day.places || []);
          return {
            date: day.date,
            places: (day.places || []).map((place: any) => {
              const blockInfo = timeBlockMap.get(place.id);
              return {
                name: place.name,
                type: place.type,
                duration: place.duration || '2 saat',
                startTime: blockInfo?.startTime,
                endTime: blockInfo?.endTime,
                timeBlock: blockInfo?.timeBlock || 'morning',
                latitude: place.lat,
                longitude: place.lng,
              };
            }),
          };
        }) || [],
      };

      const filename = `${trip.destination || 'seyahat'}-plan.pdf`;
      await exportMultiPagePDF(pdfData, filename);

      toast({
        title: 'Başarılı',
        description: 'PDF başarıyla indirildi.',
      });
    } catch (error) {
      console.error('PDF export error:', error);
      toast({
        title: 'Hata',
        description: 'PDF oluşturulurken bir hata oluştu.',
        variant: 'destructive',
      });
    }
  };

  // Ana sayfaya dön
  const handleGoHome = () => {
    navigate('/');
  };

  // Loading state
  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-4 py-8">
          <Skeleton className="h-12 w-64 mb-4" />
          <Skeleton className="h-6 w-96 mb-8" />
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Skeleton className="h-[600px]" />
            <Skeleton className="h-[600px]" />
          </div>
        </div>
      </div>
    );
  }

  // Error state
  if (error || !trip) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="container mx-auto px-4 max-w-md">
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>
              {error || 'Seyahat bulunamadı'}
            </AlertDescription>
          </Alert>
          <Button onClick={handleGoHome} className="mt-4 w-full">
            Ana Sayfaya Dön
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <SEOHead
        title={`${trip.title} | Trip Planner`}
        description={trip.description || `${trip.destination} seyahat planı. ${trip.days?.length} gün boyunca gezilecek yerler ve rota.`}
        ogImage={allPlaces[0]?.image}
        ogType="article"
      />
      {/* Header */}
      <header className="border-b bg-card print:hidden">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <h1 className="text-2xl font-bold">{trip.title}</h1>
              {trip.description && (
                <p className="text-sm text-muted-foreground mt-1">{trip.description}</p>
              )}
              <div className="flex items-center gap-4 mt-2 text-sm text-muted-foreground">
                {trip.destination && (
                  <div className="flex items-center gap-1">
                    <MapPin className="h-4 w-4" />
                    <span>{trip.destination}</span>
                  </div>
                )}
                {trip.start_date && trip.end_date && (
                  <div className="flex items-center gap-1">
                    <Calendar className="h-4 w-4" />
                    <span>
                      {new Date(trip.start_date).toLocaleDateString('tr-TR')} - {new Date(trip.end_date).toLocaleDateString('tr-TR')}
                    </span>
                  </div>
                )}
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button onClick={handleExportPDF} variant="outline" size="sm">
                <FileDown className="h-4 w-4 mr-2" />
                PDF İndir
              </Button>
              <Button onClick={handleGoHome} variant="outline" size="sm">
                Ana Sayfa
              </Button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <div className="container mx-auto px-4 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Timeline - Sol Panel */}
          <div className="space-y-4">
            {/* Gün Seçici */}
            <Card className="print:hidden">
              <CardContent className="p-4">
                <ScrollArea className="w-full">
                  <div className="flex gap-2">
                    {trip.days.map((day: any, index: number) => (
                      <Button
                        key={day.id}
                        variant={activeDayId === day.id ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => setActiveDayId(day.id)}
                        className="whitespace-nowrap"
                      >
                        <Calendar className="h-4 w-4 mr-2" />
                        Gün {index + 1}
                        <span className="ml-2 text-xs opacity-70">
                          {new Date(day.date).toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' })}
                        </span>
                      </Button>
                    ))}
                  </div>
                  <ScrollBar orientation="horizontal" />
                </ScrollArea>
              </CardContent>
            </Card>

            {/* Yerler Listesi */}
            {activeDay && (
              <Card>
                <CardContent className="p-6">
                  <div className="space-y-6">
                    {(() => {
                      const timeBlocks = groupPlacesByTimeBlock(activeDay.places);
                      const blockOrder: TimeBlock[] = ['morning', 'afternoon', 'evening'];
                      
                      return blockOrder.map((blockKey) => {
                        const blockPlaces = timeBlocks[blockKey];
                        if (blockPlaces.length === 0) return null;
                        
                        return (
                          <div key={blockKey} className="space-y-3">
                            {/* Zaman bloğu başlığı */}
                            <div className="flex items-center gap-2 mb-2">
                              <span className="text-sm font-semibold text-primary">
                                {getTimeBlockLabel(blockKey)}
                              </span>
                            </div>
                            
                            {/* Blok içindeki yerler */}
                            {blockPlaces.map((place: any) => (
                              <div
                                key={place.tripPlaceId}
                                className={cn(
                                  "relative flex gap-3 p-3 rounded-lg border bg-card transition-all cursor-pointer",
                                  selectedPlaceId === place.id && "ring-2 ring-primary",
                                  hoveredPlaceId === place.id && "shadow-md"
                                )}
                                onClick={() => setSelectedPlaceId(place.id)}
                                onMouseEnter={() => setHoveredPlaceId(place.id)}
                                onMouseLeave={() => setHoveredPlaceId(null)}
                              >
                                {/* Yer görseli */}
                                {place.image && (
                                  <div className="w-16 h-16 rounded-md overflow-hidden flex-shrink-0">
                                    <img
                                      src={place.image}
                                      alt={place.name}
                                      className="w-full h-full object-cover"
                                    />
                                  </div>
                                )}
                                
                                {/* Yer bilgileri */}
                                <div className="flex-1 min-w-0">
                                  <h4 className="font-medium text-sm truncate">{place.name}</h4>
                                  <p className="text-[10px] text-muted-foreground">
                                    {place.type} • {place.duration}
                                    {place.startTime && place.endTime && (
                                      <span className="ml-1">• {place.startTime}-{place.endTime}</span>
                                    )}
                                  </p>
                                  {place.description && (
                                    <p className="text-xs text-muted-foreground mt-1 line-clamp-2">
                                      {place.description}
                                    </p>
                                  )}
                                  {place.rating && (
                                    <div className="flex items-center gap-1 mt-1">
                                      <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
                                        ⭐ {place.rating}
                                      </Badge>
                                    </div>
                                  )}
                                </div>
                              </div>
                            ))}
                          </div>
                        );
                      });
                    })()}
                  </div>
                </CardContent>
              </Card>
            )}
          </div>

          {/* Harita - Sağ Panel */}
          <div className="lg:sticky lg:top-6 h-[600px]">
            <Card className="h-full">
              <CardContent className="p-0 h-full relative">
                {/* Map Label - Helper indicator */}
                <div className="absolute top-4 left-1/2 -translate-x-1/2 z-10 bg-background/95 backdrop-blur-sm px-4 py-2 rounded-full shadow-md border border-border">
                  <span className="text-sm font-medium text-muted-foreground">
                    🗺️ Seçilen gün rotası
                  </span>
                </div>
                
                <LeafletMapWrapper
                  places={activeDayPlaces}
                  selectedPlaceId={selectedPlaceId}
                  hoveredPlaceId={hoveredPlaceId}
                  onMarkerClick={(id) => setSelectedPlaceId(id)}
                  onMarkerHover={(id) => setHoveredPlaceId(id)}
                  showPolyline={true}
                  activeDayId={activeDayId}
                />
              </CardContent>
            </Card>
          </div>
        </div>
      </div>

      {/* Print Styles */}
      <style>{`
        @media print {
          body {
            print-color-adjust: exact;
            -webkit-print-color-adjust: exact;
          }
          
          .print\\:hidden {
            display: none !important;
          }
          
          .lg\\:grid-cols-2 {
            grid-template-columns: 1fr !important;
          }
          
          .lg\\:sticky {
            position: static !important;
          }
        }
      `}</style>
    </div>
  );
}
