import { Edit, Loader2, Plus, Search, Trash2, Upload, X } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Textarea } from '@/components/ui/textarea';
import { supabase } from '@/db/supabase';
import { useToast } from '@/hooks/use-toast';

// Yer türleri sabit listesi - Explore filtreleri ve AI sistemi için kritik
const PLACE_TYPES = [
  'museum',
  'historical',
  'viewpoint',
  'restaurant',
  'activity',
  'hot-air-balloon',
  'atv',
  'horse-riding',
  'tour',
  'hotel',
] as const;

interface Place {
  id: string;
  name: string;
  description: string | null;
  type: string | null;
  city: string | null;
  country: string | null;
  rating: number | null;
  image_url: string | null;
  latitude: number | null;
  longitude: number | null;
  duration: string | null;
  created_at: string;
}

interface PlaceFormValues {
  name: string;
  description: string;
  type: string;
  city: string;
  country: string;
  rating: number;
  image_url: string;
  latitude: number;
  longitude: number;
  duration: string;
}

export default function AdminPlaces() {
  const [places, setPlaces] = useState<Place[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [deletePlaceId, setDeletePlaceId] = useState<string | null>(null);
  const [editPlace, setEditPlace] = useState<Place | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const { toast } = useToast();

  const form = useForm<PlaceFormValues>({
    defaultValues: {
      name: '',
      description: '',
      type: '',
      city: '',
      country: '',
      rating: 0,
      image_url: '',
      latitude: undefined as any,
      longitude: undefined as any,
      duration: '',
    },
  });

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

  useEffect(() => {
    if (editPlace) {
      form.reset({
        name: editPlace.name,
        description: editPlace.description || '',
        type: editPlace.type || '',
        city: editPlace.city || '',
        country: editPlace.country || '',
        rating: editPlace.rating || 0,
        image_url: editPlace.image_url || '',
        latitude: editPlace.latitude ?? undefined,
        longitude: editPlace.longitude ?? undefined,
        duration: editPlace.duration || '',
      });
      setImagePreview(editPlace.image_url);
      setIsDialogOpen(true);
    }
  }, [editPlace, form]);

  const loadPlaces = async (query?: string) => {
    try {
      let q = supabase.from('places').select('*');

      if (query) {
        q = q.ilike('name', `%${query}%`);
      }

      const { data, error } = await q.order('created_at', { ascending: false });

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

  const handleImageUpload = async (file: File) => {
    if (!file) return null;

    // Dosya boyutu kontrolü (1MB)
    if (file.size > 1024 * 1024) {
      toast({
        title: 'Hata',
        description: 'Dosya boyutu 1MB\'dan küçük olmalıdır.',
        variant: 'destructive',
      });
      return null;
    }

    // Dosya tipi kontrolü
    if (!file.type.startsWith('image/')) {
      toast({
        title: 'Hata',
        description: 'Sadece resim dosyaları yüklenebilir.',
        variant: 'destructive',
      });
      return null;
    }

    try {
      setUploadingImage(true);

      // Dosya adını oluştur
      const fileExt = file.name.split('.').pop();
      const fileName = `place-${Date.now()}.${fileExt}`;
      const filePath = `places/${fileName}`;

      // Resmi yükle
      const { data, error } = await supabase.storage
        .from('site-assets')
        .upload(filePath, file, {
          cacheControl: '3600',
          upsert: false
        });

      if (error) throw error;

      // Public URL'i al
      const { data: { publicUrl } } = supabase.storage
        .from('site-assets')
        .getPublicUrl(filePath);

      setImagePreview(publicUrl);
      form.setValue('image_url', publicUrl);

      toast({
        title: 'Başarılı',
        description: 'Resim başarıyla yüklendi.',
      });

      return publicUrl;
    } catch (error: any) {
      console.error('Resim yüklenirken hata:', error);
      toast({
        title: 'Hata',
        description: error.message || 'Resim yüklenemedi.',
        variant: 'destructive',
      });
      return null;
    } finally {
      setUploadingImage(false);
    }
  };

  const handleRemoveImage = async () => {
    const currentImageUrl = form.getValues('image_url');
    
    if (currentImageUrl && currentImageUrl.includes('site-assets')) {
      try {
        // URL'den dosya yolunu çıkar
        const urlParts = currentImageUrl.split('/');
        const fileName = urlParts[urlParts.length - 1];
        const filePath = `places/${fileName}`;

        await supabase.storage
          .from('site-assets')
          .remove([filePath]);
      } catch (error) {
        console.error('Resim silinirken hata:', error);
      }
    }

    setImagePreview(null);
    form.setValue('image_url', '');
  };

  const onSubmit = async (values: PlaceFormValues) => {
    try {
      if (editPlace) {
        const { error } = await (supabase as any)
          .from('places')
          .update(values)
          .eq('id', editPlace.id);

        if (error) throw error;

        toast({
          title: 'Başarılı',
          description: 'Yer güncellendi.',
        });
      } else {
        const { error } = await (supabase as any)
          .from('places')
          .insert([values]);

        if (error) throw error;

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

      setIsDialogOpen(false);
      setEditPlace(null);
      form.reset();
      loadPlaces();
    } catch (error) {
      console.error('Yer kaydedilirken hata:', error);
      toast({
        title: 'Hata',
        description: 'Yer kaydedilemedi.',
        variant: 'destructive',
      });
    }
  };

  const deletePlace = async () => {
    if (!deletePlaceId) return;

    try {
      // 1️⃣ Kullanım kontrolü - Bu yer aktif seyahat planlarında kullanılıyor mu?
      const { count } = await supabase
        .from('trip_places')
        .select('*', { count: 'exact', head: true })
        .eq('place_id', deletePlaceId);

      if ((count ?? 0) > 0) {
        toast({
          title: 'Silinemez',
          description: 'Bu yer aktif seyahat planlarında kullanılıyor.',
          variant: 'destructive',
        });
        setDeletePlaceId(null);
        return;
      }

      // 2️⃣ Güvenli silme - Kullanımda değilse sil
      const { error } = await supabase
        .from('places')
        .delete()
        .eq('id', deletePlaceId);

      if (error) throw error;

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

      setDeletePlaceId(null);
      loadPlaces();
    } catch (error) {
      console.error('Yer silinirken hata:', error);
      toast({
        title: 'Hata',
        description: 'Yer silinemedi.',
        variant: 'destructive',
      });
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Yerler</h1>
          <p className="text-muted-foreground">Destinasyonları ve yerleri yönetin</p>
        </div>
        <Dialog open={isDialogOpen} onOpenChange={(open) => {
          setIsDialogOpen(open);
          if (!open) {
            setEditPlace(null);
            setImagePreview(null);
            form.reset();
          }
        }}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Yeni Yer Ekle
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>{editPlace ? 'Yer Düzenle' : 'Yeni Yer Ekle'}</DialogTitle>
              <DialogDescription>
                Yer bilgilerini girin ve kaydedin.
              </DialogDescription>
            </DialogHeader>
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="name"
                    rules={{ required: 'Yer adı gereklidir' }}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Yer Adı</FormLabel>
                        <FormControl>
                          <Input placeholder="Örn: Ayasofya" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="type"
                    rules={{ required: 'Tür seçimi zorunludur' }}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Tür</FormLabel>
                        <Select onValueChange={field.onChange} value={field.value}>
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue placeholder="Tür seçin" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {PLACE_TYPES.map((type) => (
                              <SelectItem key={type} value={type}>
                                {type}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormField
                  control={form.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Açıklama</FormLabel>
                      <FormControl>
                        <Textarea placeholder="Yer hakkında açıklama..." {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={form.control}
                    name="city"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Şehir</FormLabel>
                        <FormControl>
                          <Input placeholder="Örn: İstanbul" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="country"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Ülke</FormLabel>
                        <FormControl>
                          <Input placeholder="Örn: Türkiye" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className="grid grid-cols-4 gap-4">
                  <FormField
                    control={form.control}
                    name="rating"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Puan</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.1" min="0" max="5" {...field} onChange={(e) => field.onChange(parseFloat(e.target.value))} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="duration"
                    rules={{ required: 'Süre zorunludur' }}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Süre *</FormLabel>
                        <FormControl>
                          <Input placeholder="Örn: 2 saat" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="latitude"
                    rules={{ 
                      required: 'Enlem zorunludur',
                      validate: (v) => {
                        if (v === 0) return 'Geçerli bir enlem koordinatı girin';
                        if (v < -90 || v > 90) return 'Enlem -90 ile 90 arasında olmalıdır';
                        return true;
                      }
                    }}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Enlem *</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.000001" 
                            placeholder="Örn: 41.008240"
                            {...field} 
                            onChange={(e) => {
                              const val = e.target.value;
                              field.onChange(val === '' ? undefined : parseFloat(val));
                            }} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="longitude"
                    rules={{ 
                      required: 'Boylam zorunludur',
                      validate: (v) => {
                        if (v === 0) return 'Geçerli bir boylam koordinatı girin';
                        if (v < -180 || v > 180) return 'Boylam -180 ile 180 arasında olmalıdır';
                        return true;
                      }
                    }}
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Boylam *</FormLabel>
                        <FormControl>
                          <Input 
                            type="number" 
                            step="0.000001" 
                            placeholder="Örn: 28.978359"
                            {...field} 
                            onChange={(e) => {
                              const val = e.target.value;
                              field.onChange(val === '' ? undefined : parseFloat(val));
                            }} 
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                
                {/* Resim Yükleme Bölümü */}
                <div className="space-y-2">
                  <Label>Yer Görseli</Label>
                  <div className="space-y-4">
                    {imagePreview && (
                      <div className="relative w-full h-48 rounded-lg border overflow-hidden bg-muted">
                        <img
                          src={imagePreview}
                          alt="Önizleme"
                          className="w-full h-full object-cover"
                        />
                        <Button
                          type="button"
                          variant="destructive"
                          size="icon"
                          className="absolute top-2 right-2"
                          onClick={handleRemoveImage}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    )}
                    <div className="flex items-center gap-4">
                      <Input
                        type="file"
                        accept="image/*"
                        onChange={(e) => {
                          const file = e.target.files?.[0];
                          if (file) handleImageUpload(file);
                        }}
                        disabled={uploadingImage}
                        className="cursor-pointer"
                      />
                      {uploadingImage && (
                        <Loader2 className="h-5 w-5 animate-spin text-primary" />
                      )}
                    </div>
                    <p className="text-xs text-muted-foreground">
                      PNG, JPG veya WEBP. Maksimum 1MB. Resim yükledikten sonra otomatik olarak URL alanına eklenecektir.
                    </p>
                  </div>
                </div>

                <FormField
                  control={form.control}
                  name="image_url"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Görsel URL (Manuel)</FormLabel>
                      <FormControl>
                        <Input placeholder="https://..." {...field} />
                      </FormControl>
                      <p className="text-xs text-muted-foreground">
                        Yukarıdan resim yükleyebilir veya buraya manuel URL girebilirsiniz.
                      </p>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <DialogFooter>
                  <Button type="submit">
                    {editPlace ? 'Güncelle' : 'Ekle'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </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="Yer ara..."
            value={searchQuery}
            onChange={(e) => {
              setSearchQuery(e.target.value);
              loadPlaces(e.target.value);
            }}
            className="pl-10"
          />
        </div>
      </div>

      <div className="border rounded-lg">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Yer Adı</TableHead>
              <TableHead>Tür</TableHead>
              <TableHead>Şehir</TableHead>
              <TableHead>Ülke</TableHead>
              <TableHead>Puan</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-24 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-4 w-32 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-4 w-32 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-4 w-12 bg-muted" /></TableCell>
                  <TableCell><Skeleton className="h-8 w-20 ml-auto bg-muted" /></TableCell>
                </TableRow>
              ))
            ) : places.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                  Yer bulunamadı
                </TableCell>
              </TableRow>
            ) : (
              places.map((place) => (
                <TableRow key={place.id}>
                  <TableCell className="font-medium">{place.name}</TableCell>
                  <TableCell>{place.type || '-'}</TableCell>
                  <TableCell>{place.city || '-'}</TableCell>
                  <TableCell>{place.country || '-'}</TableCell>
                  <TableCell>{place.rating ? `${place.rating} ★` : '-'}</TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => setEditPlace(place)}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => setDeletePlaceId(place.id)}
                        className="text-destructive hover:text-destructive"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      <AlertDialog open={!!deletePlaceId} onOpenChange={() => setDeletePlaceId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Yeri Sil</AlertDialogTitle>
            <AlertDialogDescription>
              Bu yeri silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>İptal</AlertDialogCancel>
            <AlertDialogAction onClick={deletePlace} className="bg-destructive hover:bg-destructive/90">
              Sil
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
