import { useState } from "react";
import { ImagePlus, UploadCloud } from "lucide-react";

export default function UploadFotoSPPG({ sppgId, onUploadSuccess }) {
  const [foto, setFoto] = useState(null);
  const [preview, setPreview] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState("");

  const handleChangeFoto = (e) => {
    const file = e.target.files[0];

    if (!file) {
      return;
    }

    setFoto(file);
    setPreview(URL.createObjectURL(file));
    setMessage("");
  };

  const handleUpload = async (e) => {
    e.preventDefault();

    if (!foto) {
      setMessage("Pilih foto terlebih dahulu.");
      return;
    }

    const formData = new FormData();
    formData.append("id", sppgId);
    formData.append("foto", foto);

    try {
      setLoading(true);
      setMessage("");

      const res = await fetch(
        "http://localhost/backend/api/upload_foto_sppg.php",
        {
          method: "POST",
          body: formData,
        }
      );

      const data = await res.json();

      if (!data.success) {
        setMessage(data.message || "Upload foto gagal.");
        return;
      }

      setMessage("Foto berhasil diupload.");
      setFoto(null);

      if (onUploadSuccess) {
        onUploadSuccess(data.data);
      }
    } catch (err) {
      console.error(err);
      setMessage("Tidak bisa terhubung ke server.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="mb-4 flex items-center gap-3">
        <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-blue-50 text-blue-700">
          <ImagePlus className="h-6 w-6" />
        </div>

        <div>
          <h2 className="text-lg font-black text-slate-900">
            Upload Foto SPPG
          </h2>
          <p className="text-sm text-slate-500">
            Foto ini dapat tampil pada halaman masyarakat.
          </p>
        </div>
      </div>

      {preview && (
        <div className="mb-4 overflow-hidden rounded-2xl border border-slate-200">
          <img
            src={preview}
            alt="Preview foto SPPG"
            className="h-52 w-full object-cover"
          />
        </div>
      )}

      <form onSubmit={handleUpload} className="space-y-4">
        <label className="block cursor-pointer rounded-2xl border border-dashed border-blue-300 bg-blue-50/70 p-5 text-center transition hover:bg-blue-50">
          <UploadCloud className="mx-auto h-8 w-8 text-blue-700" />
          <p className="mt-2 text-sm font-bold text-slate-800">
            Pilih foto SPPG
          </p>
          <p className="mt-1 text-xs text-slate-500">
            Format JPG, PNG, atau WEBP. Maksimal 3MB.
          </p>

          <input
            type="file"
            accept="image/jpeg,image/png,image/webp,image/jpg"
            onChange={handleChangeFoto}
            className="hidden"
          />
        </label>

        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-2xl bg-blue-700 px-4 py-3 text-sm font-bold text-white transition hover:bg-blue-800 disabled:cursor-not-allowed disabled:opacity-60"
        >
          {loading ? "Mengupload..." : "Upload Foto"}
        </button>

        {message && (
          <p className="rounded-xl bg-slate-50 px-4 py-3 text-sm font-semibold text-slate-700">
            {message}
          </p>
        )}
      </form>
    </div>
  );
}