import { format } from 'date-fns';
import { tr } from 'date-fns/locale';
import { 
  Calendar,
  Edit,
  MapPin, 
  MoreVertical,
  Plus, 
  Share2, 
  Trash2,
  Users
} from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Skeleton } from '@/components/ui/skeleton';
import { useAuth } from '@/contexts/AuthContext';
import { tripsApi } from '@/db/api';
import { useToast } from '@/hooks/use-toast';

const MyTrips = () => {
  const navigate = useNavigate();
  const { user } = useAuth();
  const { toast } = useToast();
  const [trips, setTrips] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [tripToDelete, setTripToDelete] = useState<{ id: string, title: string } | null>(null);

  useEffect(() => {
    loadTrips();
  }, [user]);

  const loadTrips = async () => {
    if (!user) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      const userTrips = await tripsApi.getUserTrips(user.id);
      setTrips(userTrips || []);
    } catch (error: any) {
      console.error('Seyahatler yüklenirken hata:', error);
      toast({
        title: 'Hata',
        description: 'Seyahatler yüklenirken bir hata oluştu.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteTrip = async () => {
    if (!tripToDelete) return;

    try {
      await tripsApi.delete(tripToDelete.id);
      toast({
        title: 'Başarılı',
        description: 'Seyahat silindi.',
      });
      loadTrips();
    } catch (error: any) {
      console.error('Seyahat silinirken hata:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Seyahat silinirken bir hata oluştu.',
        variant: 'destructive',
      });
    } finally {
      setTripToDelete(null);
    }
  };

  const formatDateRange = (startDate: string, endDate: string) => {
    try {
      const start = new Date(startDate);
      const end = new Date(endDate);
      return `${format(start, 'd MMM', { locale: tr })} - ${format(end, 'd MMM yyyy', { locale: tr })}`;
    } catch {
      return 'Tarih belirtilmemiş';
    }
  };

  const calculateDuration = (startDate: string, endDate: string) => {
    try {
      const start = new Date(startDate);
      const end = new Date(endDate);
      const days = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
      return `${days} gün`;
    } catch {
      return '';
    }
  };

  if (!user) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-4">
        <Card className="max-w-md w-full">
          <CardContent className="pt-6 text-center">
            <h2 className="text-2xl font-bold mb-2">Giriş Yapın</h2>
            <p className="text-muted-foreground mb-6">
              Seyahat planlarınızı görmek için giriş yapmanız gerekiyor.
            </p>
            <Button onClick={() => navigate('/')} className="rounded-full">
              Ana Sayfaya Dön
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-4 py-8">
          <div className="flex items-center justify-between mb-8">
            <Skeleton className="h-10 w-64 bg-muted" />
            <Skeleton className="h-10 w-40 bg-muted" />
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-80 bg-muted" />
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold mb-2">Seyahat Planlarım</h1>
            <p className="text-muted-foreground">
              {trips.length > 0 
                ? `${trips.length} seyahat planınız var` 
                : 'Henüz seyahat planınız yok'}
            </p>
          </div>
          <Button 
            onClick={() => navigate('/create-trip')}
            className="rounded-full"
          >
            <Plus className="h-4 w-4 mr-2" />
            Yeni Seyahat
          </Button>
        </div>

        {/* Trips Grid */}
        {trips.length === 0 ? (
          <Card className="max-w-2xl mx-auto">
            <CardContent className="pt-12 pb-12 text-center">
              <div className="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-4">
                <MapPin className="h-10 w-10 text-primary" />
              </div>
              <h2 className="text-2xl font-bold mb-2">İlk Seyahatinizi Oluşturun</h2>
              <p className="text-muted-foreground mb-6 max-w-md mx-auto">
                Hayalinizdeki seyahati planlamaya başlayın. Gideceğiniz yerleri ekleyin, 
                günlük programınızı oluşturun ve unutulmaz anılar biriktirin.
              </p>
              <Button 
                onClick={() => navigate('/create-trip')}
                size="lg"
                className="rounded-full"
              >
                <Plus className="h-5 w-5 mr-2" />
                Seyahat Oluştur
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {trips.map((trip) => (
              <Card 
                key={trip.id} 
                className="overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group"
                onClick={() => navigate(`/planner?trip_id=${trip.id}`)}
              >
                {/* Cover Image */}
                <div className="relative h-48 bg-muted overflow-hidden">
                  {trip.cover_image ? (
                    <img 
                      src={trip.cover_image} 
                      alt={trip.title}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5">
                      <MapPin className="h-16 w-16 text-primary/40" />
                    </div>
                  )}
                  
                  {/* Actions Menu */}
                  <div className="absolute top-2 right-2">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
                        <Button 
                          variant="secondary" 
                          size="icon" 
                          className="h-8 w-8 rounded-full bg-white/90 hover:bg-white"
                        >
                          <MoreVertical className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={(e) => {
                          e.stopPropagation();
                          navigate(`/planner?trip_id=${trip.id}`);
                        }}>
                          <Edit className="h-4 w-4 mr-2" />
                          Düzenle
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={(e) => {
                          e.stopPropagation();
                          // TODO: Implement share functionality
                          toast({
                            title: 'Yakında',
                            description: 'Paylaşım özelliği yakında eklenecek.',
                          });
                        }}>
                          <Share2 className="h-4 w-4 mr-2" />
                          Paylaş
                        </DropdownMenuItem>
                        <DropdownMenuItem 
                          className="text-destructive focus:text-destructive"
                          onClick={(e) => {
                            e.stopPropagation();
                            setTripToDelete({ id: trip.id, title: trip.title });
                          }}
                        >
                          <Trash2 className="h-4 w-4 mr-2" />
                          Sil
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </div>

                {/* Content */}
                <CardContent className="p-4">
                  <h3 className="font-bold text-lg mb-2 line-clamp-1">{trip.title}</h3>
                  
                  <div className="space-y-2 text-sm text-muted-foreground">
                    <div className="flex items-center gap-2">
                      <MapPin className="h-4 w-4 shrink-0" />
                      <span className="line-clamp-1">{trip.destination || 'Destinasyon belirtilmemiş'}</span>
                    </div>
                    
                    {trip.start_date && trip.end_date && (
                      <div className="flex items-center gap-2">
                        <Calendar className="h-4 w-4 shrink-0" />
                        <span>{formatDateRange(trip.start_date, trip.end_date)}</span>
                      </div>
                    )}
                    
                    <div className="flex items-center gap-2 pt-2">
                      <Badge variant="secondary" className="text-xs">
                        {calculateDuration(trip.start_date, trip.end_date)}
                      </Badge>
                      {trip.is_public && (
                        <Badge variant="outline" className="text-xs">
                          <Users className="h-3 w-3 mr-1" />
                          Herkese Açık
                        </Badge>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}

        {/* Delete Confirmation Dialog */}
        <AlertDialog open={!!tripToDelete} onOpenChange={(open) => !open && setTripToDelete(null)}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Emin misiniz?</AlertDialogTitle>
              <AlertDialogDescription>
                &quot;{tripToDelete?.title}&quot; seyahatini silmek istediğinize emin misiniz? Bu işlem geri alınamaz.
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>İptal</AlertDialogCancel>
              <AlertDialogAction 
                onClick={handleDeleteTrip}
                className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              >
                Sil
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </div>
  );
};

export default MyTrips;
