"use client";

import { uploadFile } from "@/server/actions/image";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { formatFileSize } from "@/lib/utils";

export default function ImageUploadButton({
  onUploaded,
}: {
  onUploaded: (url: string) => void;
}) {
  const [image, setImage] = useState<File | undefined>(undefined);
  const [loading, setLoading] = useState(false);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 1024 * 1024 * 2) return toast.error("Datei ist zu groß.");
    if (file.type.startsWith("image/")) {
      return toast.error("Nur Bilder können hochgeladen werden.");
    }
    setImage(file);
  };

  const handleUpload = async () => {
    if (!image) return;
    setLoading(true);
    const formData = new FormData();
    formData.append("file", image); // Append file with a field name
    try {
      const url = await uploadFile(formData);
      if (typeof url !== "string") toast.error("Etwas ist fehlgeschlagen");
      else {
        onUploaded(url);
        toast.success("Upload erfolgreich");
      }
    } catch (e) {
      console.error("Fehler aufgetreten: " + e);
    }
    setLoading(false);
  };

  return (
    <div className="flex max-w-lg items-center gap-4">
      <Button
        disabled={loading || !image}
        onClick={(e) => {
          e.preventDefault();
          handleUpload();
        }}
      >
        {loading ? "laden..." : "Bild Hochladen"}
      </Button>
      <Input
        id="file"
        type="file"
        accept="image/*"
        onChange={handleFileChange}
      />
      {image && <p className="w-full">{formatFileSize(image.size)}</p>}
    </div>
  );
}
