import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { toast } from "sonner";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";

const apiBase = import.meta.env.VITE_API_URL;

type GalleryImage = {
  id: number;
  image_url: string;
};

const GalleryManager = () => {
  const [images, setImages] = useState<GalleryImage[]>([]);
  const [uploading, setUploading] = useState(false);
  const [selectedImage, setSelectedImage] = useState<number | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);

  const fetchImages = async () => {
    try {
      const res = await fetch(`${apiBase}/api/gallery`);
      const data = await res.json();
      setImages(data);
    } catch (err) {
      console.error("Fehler beim Laden der Galerie:", err);
    }
  };

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

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("image", file);

    setUploading(true);
    try {
      const res = await fetch(`${apiBase}/api/gallery`, {
        method: "POST",
        body: formData,
      });

      if (!res.ok) throw new Error("Fehler beim Hochladen");
      toast.success("Bild erfolgreich hochgeladen!");
      await fetchImages();
    } catch (err) {
      toast.error("Fehler beim Hochladen des Bildes");
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async () => {
    if (selectedImage === null) return;

    try {
      const res = await fetch(`${apiBase}/api/gallery/${selectedImage}`, {
        method: "DELETE",
      });

      if (!res.ok) throw new Error("Fehler beim Löschen");
      toast.success("Bild gelöscht");
      await fetchImages();
    } catch (err) {
      toast.error("Fehler beim Löschen des Bildes");
    } finally {
      setDialogOpen(false);
      setSelectedImage(null);
    }
  };

  return (
    <div className="max-w-6xl mx-auto py-12 px-4">
      <h1 className="text-3xl font-bold text-frog-600 mb-6">Galerie verwalten</h1>

      {/* Upload Button */}
      <div className="mb-8">
        <label htmlFor="upload" className="cursor-pointer inline-flex items-center bg-frog-500 text-white px-4 py-2 rounded-md hover:bg-frog-600 transition">
          Bild hochladen
        </label>
        <Input
          id="upload"
          type="file"
          accept="image/*"
          className="hidden"
          onChange={handleUpload}
        />
        {uploading && <p className="text-sm text-gray-500 mt-2">Bild wird hochgeladen...</p>}
      </div>

      {/* Bilder */}
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-6">
        {images.map((img) => (
          <Card key={img.id}>
            <CardContent className="p-2">
              <img
                src={`${apiBase}${img.image_url}`}
                alt="Galeriebild"
                className="w-full h-48 object-cover rounded-md mb-2"
              />
              <Button
                variant="destructive"
                className="w-full"
                onClick={() => {
                  setSelectedImage(img.id);
                  setDialogOpen(true);
                }}
              >
                Löschen
              </Button>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Dialog zur Bestätigung */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Bild wirklich löschen?</DialogTitle>
          </DialogHeader>
          <p className="text-gray-600 mb-4">Diese Aktion kann nicht rückgängig gemacht werden.</p>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setDialogOpen(false)}>Abbrechen</Button>
            <Button variant="destructive" onClick={handleDelete}>Löschen</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default GalleryManager;
