import { Calendar, Eye, Search, Trash2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

interface Trip {
  id: string;
  title: string;
  destination: string | null;
  start_date: string | null;
  end_date: string | null;
  is_public: boolean;
  created_at: string;
  user_id: string;
  profiles: {
    username: string;
  } | null;
}

export default function AdminTrips() {
  const [trips, setTrips] = useState<Trip[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [deleteTripId, setDeleteTripId] = useState<string | null>(null);
  const { toast } = useToast();

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

  const loadTrips = async () => {
    try {
      const { data, error } = await supabase
        .from('trips')
        .select(`
          *,
          profiles:user_id (username)
        `)
        .order('created_at', { ascending: false });

      if (error) throw error;
      setTrips(data || []);
    } catch (error) {
      console.error('Seyahatler yüklenirken hata:', error);
      toast({
        title: 'Hata',
        description: 'Seyahatler yüklenemedi.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const deleteTrip = async () => {
    if (!deleteTripId) return;

    try {
      const { error } = await supabase
        .from('trips')
        .delete()
        .eq('id', deleteTripId);

      if (error) throw error;

      toast({
        title: 'Başarılı',
        description: 'Seyahat silindi.',
      });

      setDeleteTripId(null);
      loadTrips();
    } catch (error) {
      console.error('Seyahat silinirken hata:', error);
      toast({
        title: 'Hata',
        description: 'Seyahat silinemedi.',
        variant: 'destructive',
      });
    }
  };

  const togglePublic = async (tripId: string, currentStatus: boolean) => {
    try {
      const { error } = await (supabase as any)
        .from('trips')
        .update({ is_public: !currentStatus })
        .eq('id', tripId);

      if (error) throw error;

      toast({
        title: 'Başarılı',
        description: 'Seyahat durumu güncellendi.',
      });

      loadTrips();
    } catch (error) {
      console.error('Durum güncellenirken hata:', error);
      toast({
        title: 'Hata',
        description: 'Durum güncellenemedi.',
        variant: 'destructive',
      });
    }
  };

  const filteredTrips = trips.filter(
    (trip) =>
      trip.title?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      trip.destination?.toLowerCase().includes(searchQuery.toLowerCase()) ||
      trip.profiles?.username?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Seyahatler</h1>
          <p className="text-muted-foreground">Tüm seyahat planlarını yönetin</p>
        </div>
      </div>

      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Seyahat ara..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>
      </div>

      <div className="border rounded-lg">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Başlık</TableHead>
              <TableHead>Destinasyon</TableHead>
              <TableHead>Kullanıcı</TableHead>
              <TableHead>Tarihler</TableHead>
              <TableHead>Durum</TableHead>
              <TableHead className="text-right">İşlemler</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <TableRow key={i}>
                  <TableCell><Skeleton className="h-4 w-40 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-4 w-32 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-4 w-24 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-4 w-32 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-6 w-20 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-8 w-20 ml-auto bg-muted" /></TableCell>
                </TableRow>
              ))
            ) : filteredTrips.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                  Seyahat bulunamadı
                </TableCell>
              </TableRow>
            ) : (
              filteredTrips.map((trip) => (
                <TableRow key={trip.id}>
                  <TableCell className="font-medium">{trip.title}</TableCell>
                  <TableCell>{trip.destination || '-'}</TableCell>
                  <TableCell>{trip.profiles?.username || 'Bilinmiyor'}</TableCell>
                  <TableCell>
                    {trip.start_date && trip.end_date ? (
                      <div className="flex items-center gap-1 text-sm">
                        <Calendar className="h-3 w-3" />
                        {new Date(trip.start_date).toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' })}
                        {' - '}
                        {new Date(trip.end_date).toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' })}
                      </div>
                    ) : (
                      '-'
                    )}
                  </TableCell>
                  <TableCell>
                    <Badge
                      variant={trip.is_public ? 'default' : 'secondary'}
                      className="cursor-pointer"
                      onClick={() => togglePublic(trip.id, trip.is_public)}
                    >
                      {trip.is_public ? 'Herkese Açık' : 'Özel'}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => window.open(`/planner?trip=${trip.id}`, '_blank')}
                      >
                        <Eye className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => setDeleteTripId(trip.id)}
                        className="text-destructive hover:text-destructive"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <AlertDialog open={!!deleteTripId} onOpenChange={() => setDeleteTripId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Seyahati Sil</AlertDialogTitle>
            <AlertDialogDescription>
              Bu seyahati silmek istediğinizden emin misiniz? Bu işlem geri alınamaz ve tüm günler ve yerler de silinecektir.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>İptal</AlertDialogCancel>
            <AlertDialogAction onClick={deleteTrip} className="bg-destructive hover:bg-destructive/90">
              Sil
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
