import { useEffect, useState } from "react";
import {
  Upload,
  Send,
  ShieldCheck,
  Building2,
  CheckCircle2,
  AlertTriangle,
  FileText,
  Image as ImageIcon,
} from "lucide-react";

const API = {
  validasiAwal: "http://openplate.my.id/api/pengaduan/validasi_awal.php",
  tindakLanjutPemerintah:
    "http://openplate.my.id/api/pengaduan/tindak_lanjut_pemerintah.php",
  perbaikanSPPG: "http://openplate.my.id/api/pengaduan/perbaikan_sppg.php",
  validasiPerbaikan:
    "http://openplate.my.id/api/pengaduan/validasi_perbaikan.php",
};

const MAX_FOTO_SIZE = 5 * 1024 * 1024;
const MAX_FILE_SIZE = 10 * 1024 * 1024;

const allowedFotoTypes = [
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/webp",
];

const allowedFileTypes = [
  "application/pdf",
  "application/msword",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "image/jpeg",
  "image/jpg",
  "image/png",
  "image/webp",
];

const allowedFileExtensions = [
  "pdf",
  "doc",
  "docx",
  "jpg",
  "jpeg",
  "png",
  "webp",
];

const getFileExtension = (fileName = "") => {
  return fileName.split(".").pop()?.toLowerCase() || "";
};

export default function AksiPengaduanRole({ pengaduan, onSuccess }) {
  const role = localStorage.getItem("role");

  const [catatan, setCatatan] = useState("");
  const [hasil, setHasil] = useState("valid");
  const [foto, setFoto] = useState(null);
  const [file, setFile] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!pengaduan) return;

    if (pengaduan.status_alur === "Menunggu Validasi Perbaikan") {
      setHasil("selesai");
    } else {
      setHasil("valid");
    }
  }, [pengaduan?.id, pengaduan?.status_alur]);

  const resetForm = () => {
    setCatatan("");

    if (pengaduan?.status_alur === "Menunggu Validasi Perbaikan") {
      setHasil("selesai");
    } else {
      setHasil("valid");
    }

    setFoto(null);
    setFile(null);
  };

  const handleFotoChange = (selectedFile) => {
    if (!selectedFile) return;

    if (!allowedFotoTypes.includes(selectedFile.type)) {
      alert("Format foto harus JPG, JPEG, PNG, atau WEBP.");
      return;
    }

    if (selectedFile.size > MAX_FOTO_SIZE) {
      alert("Ukuran foto maksimal 5MB.");
      return;
    }

    setFoto(selectedFile);
  };

  const handleFileChange = (selectedFile) => {
    if (!selectedFile) return;

    const ext = getFileExtension(selectedFile.name);

    if (
      !allowedFileTypes.includes(selectedFile.type) &&
      !allowedFileExtensions.includes(ext)
    ) {
      alert("Format file harus PDF, DOC, DOCX, JPG, JPEG, PNG, atau WEBP.");
      return;
    }

    if (selectedFile.size > MAX_FILE_SIZE) {
      alert("Ukuran file maksimal 10MB.");
      return;
    }

    setFile(selectedFile);
  };

  const validateBukti = () => {
    if (!catatan.trim()) {
      alert("Catatan wajib diisi.");
      return false;
    }

    if (!foto) {
      alert("Foto bukti wajib diupload.");
      return false;
    }

    if (!file) {
      alert("File bukti wajib diupload.");
      return false;
    }

    return true;
  };

  const submitFormData = async (url, extra = {}) => {
    if (!validateBukti()) return;

    try {
      setLoading(true);

      const formData = new FormData();
      formData.append("pengaduan_id", pengaduan.id);
      formData.append("catatan", catatan.trim());
      formData.append("foto", foto);
      formData.append("file", file);

      Object.entries(extra).forEach(([key, value]) => {
        formData.append(key, value);
      });

      const res = await fetch(url, {
        method: "POST",
        body: formData,
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Aksi gagal diproses.");
        return;
      }

      alert(result.message || "Aksi berhasil diproses.");
      resetForm();
      onSuccess?.();
    } catch (err) {
      console.error(err);
      alert("Tidak bisa terhubung ke server.");
    } finally {
      setLoading(false);
    }
  };

  const submitValidator = async () => {
    if (!validateBukti()) return;

    try {
      setLoading(true);

      const isValidasiAwal =
        pengaduan.status_alur === "Menunggu Validasi" ||
        pengaduan.status_alur === "Baru" ||
        !pengaduan.validasi_status;

      const hasilFinal =
        pengaduan.status_alur === "Menunggu Validasi Perbaikan"
          ? hasil === "masih_bermasalah"
            ? "masih_bermasalah"
            : "selesai"
          : hasil === "tidak_valid"
          ? "tidak_valid"
          : "valid";

      const formData = new FormData();
      formData.append("pengaduan_id", pengaduan.id);
      formData.append("hasil", hasilFinal);
      formData.append("catatan", catatan.trim());
      formData.append("validasi_oleh", "Validator Sekolah");
      formData.append("foto", foto);
      formData.append("file", file);

      const url = isValidasiAwal ? API.validasiAwal : API.validasiPerbaikan;

      const res = await fetch(url, {
        method: "POST",
        body: formData,
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Validasi gagal diproses.");
        return;
      }

      alert(result.message || "Validasi berhasil disimpan.");
      resetForm();
      onSuccess?.();
    } catch (err) {
      console.error(err);
      alert("Tidak bisa terhubung ke server.");
    } finally {
      setLoading(false);
    }
  };

  if (!pengaduan) return null;

  const canPemerintah =
    role === "pemerintah" &&
    ["Valid", "Masih Bermasalah", "Tindak Lanjut Ulang"].includes(
      pengaduan.status_alur
    );

  const canSPPG =
    role === "sppg" &&
    [
      "Diproses Pemerintah",
      "Menunggu Perbaikan SPPG",
      "Tindak Lanjut Ulang",
    ].includes(pengaduan.status_alur);

  const canValidator =
    role === "validator" &&
    ["Menunggu Validasi", "Baru", "Menunggu Validasi Perbaikan"].includes(
      pengaduan.status_alur
    );

  if (!canPemerintah && !canSPPG && !canValidator) {
    return (
      <div className="rounded-3xl border border-slate-200 bg-slate-50 p-5">
        <div className="flex items-start gap-3">
          <ShieldCheck className="mt-0.5 h-5 w-5 text-blue-700" />

          <div>
            <p className="font-black text-slate-900">Tidak Ada Aksi Saat Ini</p>

            <p className="mt-1 text-sm text-slate-600">
              Role Anda hanya dapat melihat detail, atau pengaduan ini belum
              berada pada tahap yang sesuai untuk diproses.
            </p>

            <p className="mt-2 text-xs font-semibold text-slate-500">
              Status alur saat ini: {pengaduan.status_alur || "-"}
            </p>
          </div>
        </div>
      </div>
    );
  }

  const title = canPemerintah
    ? "Aksi Pemerintah"
    : canSPPG
    ? "Aksi SPPG"
    : "Aksi Validator / Sekolah";

  const description = canPemerintah
    ? "Upload foto dan file bukti tindak lanjut. Status akan berubah setelah bukti dikirim."
    : canSPPG
    ? "Upload foto dan file bukti perbaikan. Setelah dikirim, validator/sekolah akan mengecek ulang."
    : "Validasi pengaduan atau hasil perbaikan menggunakan catatan, foto, dan file bukti.";

  return (
    <div className="rounded-3xl border border-blue-100 bg-blue-50 p-5">
      <div className="mb-4 flex items-start gap-3">
        <div className="flex h-11 w-11 items-center justify-center rounded-2xl bg-blue-100 text-blue-700">
          {canPemerintah && <ShieldCheck className="h-5 w-5" />}
          {canSPPG && <Building2 className="h-5 w-5" />}
          {canValidator && <CheckCircle2 className="h-5 w-5" />}
        </div>

        <div>
          <h3 className="font-black text-slate-900">{title}</h3>

          <p className="mt-1 text-sm text-slate-600">{description}</p>

          <p className="mt-2 text-xs font-semibold text-blue-700">
            Semua aksi wajib menyertakan catatan, foto bukti, dan file bukti.
          </p>
        </div>
      </div>

      {canValidator && (
        <div className="mb-4">
          <label className="mb-1.5 block text-sm font-bold text-slate-700">
            Hasil Validasi *
          </label>

          <select
            value={hasil}
            onChange={(e) => setHasil(e.target.value)}
            className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-200"
          >
            {pengaduan.status_alur === "Menunggu Validasi Perbaikan" ? (
              <>
                <option value="selesai">Selesai / Sudah Diperbaiki</option>
                <option value="masih_bermasalah">Masih Bermasalah</option>
              </>
            ) : (
              <>
                <option value="valid">Valid / Pengaduan Benar</option>
                <option value="tidak_valid">Tidak Valid</option>
              </>
            )}
          </select>
        </div>
      )}

      <div className="mb-4">
        <label className="mb-1.5 block text-sm font-bold text-slate-700">
          Catatan *
        </label>

        <textarea
          value={catatan}
          onChange={(e) => setCatatan(e.target.value)}
          rows={4}
          placeholder="Tulis catatan proses, alasan validasi, tindak lanjut, atau perbaikan..."
          className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-200"
        />
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <label className="cursor-pointer rounded-2xl border-2 border-dashed border-blue-200 bg-white p-4 text-center hover:border-blue-400">
          <ImageIcon className="mx-auto mb-2 h-6 w-6 text-blue-700" />

          <p className="text-sm font-bold text-slate-800">
            Upload Foto Bukti *
          </p>

          <p className="mt-1 text-xs text-slate-500">
            JPG, JPEG, PNG, WEBP. Maksimal 5MB.
          </p>

          <input
            type="file"
            accept="image/jpeg,image/jpg,image/png,image/webp"
            className="hidden"
            onChange={(e) => handleFotoChange(e.target.files?.[0])}
          />

          {foto ? (
            <div className="mt-3 rounded-xl bg-blue-50 px-3 py-2 text-xs font-semibold text-blue-700">
              {foto.name}
            </div>
          ) : (
            <div className="mt-3 inline-flex items-center gap-1 text-xs font-bold text-blue-700">
              <Upload className="h-3.5 w-3.5" />
              Pilih Foto
            </div>
          )}
        </label>

        <label className="cursor-pointer rounded-2xl border-2 border-dashed border-blue-200 bg-white p-4 text-center hover:border-blue-400">
          <FileText className="mx-auto mb-2 h-6 w-6 text-blue-700" />

          <p className="text-sm font-bold text-slate-800">
            Upload File Bukti *
          </p>

          <p className="mt-1 text-xs text-slate-500">
            PDF, DOC, DOCX, atau gambar. Maksimal 10MB.
          </p>

          <input
            type="file"
            accept=".pdf,.doc,.docx,image/jpeg,image/jpg,image/png,image/webp"
            className="hidden"
            onChange={(e) => handleFileChange(e.target.files?.[0])}
          />

          {file ? (
            <div className="mt-3 rounded-xl bg-blue-50 px-3 py-2 text-xs font-semibold text-blue-700">
              {file.name}
            </div>
          ) : (
            <div className="mt-3 inline-flex items-center gap-1 text-xs font-bold text-blue-700">
              <Upload className="h-3.5 w-3.5" />
              Pilih File
            </div>
          )}
        </label>
      </div>

      <div className="mt-4 rounded-2xl border border-yellow-200 bg-yellow-50 p-4 text-sm text-yellow-800">
        <div className="flex items-start gap-2">
          <AlertTriangle className="mt-0.5 h-4 w-4 flex-shrink-0" />
          <p>
            Perubahan status tidak dapat dilakukan tanpa bukti. Foto dan file
            akan tersimpan sebagai riwayat tindak lanjut pengaduan.
          </p>
        </div>
      </div>

      <button
        type="button"
        disabled={loading}
        onClick={() => {
          if (canPemerintah) {
            submitFormData(API.tindakLanjutPemerintah, {
              pengirim: "Pemerintah",
            });
            return;
          }

          if (canSPPG) {
            submitFormData(API.perbaikanSPPG);
            return;
          }

          if (canValidator) {
            submitValidator();
          }
        }}
        className="mt-4 inline-flex w-full items-center justify-center gap-2 rounded-xl bg-blue-700 px-4 py-3 text-sm font-black text-white hover:bg-blue-800 disabled:opacity-60"
      >
        <Send className="h-4 w-4" />
        {loading ? "Mengirim..." : "Kirim Bukti dan Proses"}
      </button>
    </div>
  );
}