import { useEffect, useState } from "react";
import {
  X,
  Building2,
  School,
  User,
  Image as ImageIcon,
  FileText,
  CheckCircle2,
  Clock,
  AlertTriangle,
  ShieldCheck,
  RefreshCw,
} from "lucide-react";

import AksiPengaduanRole from "./AksiPengaduanRole";

const RIWAYAT_API = "http://openplate.my.id/api/pengaduan/riwayat.php";

const statusColors = {
  Baru: "bg-blue-100 text-blue-700",
  Diproses: "bg-amber-100 text-amber-700",
  Selesai: "bg-emerald-100 text-emerald-700",
};

const alurColors = {
  "Menunggu Validasi": "bg-blue-100 text-blue-700",
  "Tidak Valid": "bg-red-100 text-red-700",
  Valid: "bg-emerald-100 text-emerald-700",
  "Diproses Pemerintah": "bg-amber-100 text-amber-700",
  "Menunggu Perbaikan SPPG": "bg-orange-100 text-orange-700",
  "Menunggu Validasi Perbaikan": "bg-purple-100 text-purple-700",
  "Masih Bermasalah": "bg-red-100 text-red-700",
  "Tindak Lanjut Ulang": "bg-orange-100 text-orange-700",
  Selesai: "bg-emerald-100 text-emerald-700",
};

const tahapLabel = {
  validasi_awal: "Validasi Awal",
  tindak_lanjut_pemerintah: "Tindak Lanjut Pemerintah",
  perbaikan_sppg: "Perbaikan SPPG",
  validasi_perbaikan: "Validasi Perbaikan",
};

const roleLabel = {
  pemerintah: "Pemerintah",
  sppg: "SPPG",
  validator: "Validator / Sekolah",
  admin: "Admin",
};

const hasilColors = {
  valid: "bg-emerald-50 text-emerald-700 border-emerald-200",
  tidak_valid: "bg-red-50 text-red-700 border-red-200",
  selesai: "bg-emerald-50 text-emerald-700 border-emerald-200",
  masih_bermasalah: "bg-red-50 text-red-700 border-red-200",
};

const formatDateTime = (value) => {
  if (!value) return "-";

  return new Date(value).toLocaleString("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

export default function DetailRiwayatPengaduan({ pengaduanId, onClose }) {
  const [data, setData] = useState(null);
  const [riwayat, setRiwayat] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const loadRiwayat = async () => {
    try {
      setLoading(true);
      setError("");

      const res = await fetch(`${RIWAYAT_API}?pengaduan_id=${pengaduanId}`);

      if (!res.ok) {
        throw new Error(`HTTP Error ${res.status}`);
      }

      const result = await res.json();

      if (!result.success) {
        setError(result.message || "Gagal mengambil riwayat pengaduan");
        setData(null);
        setRiwayat([]);
        return;
      }

      setData(result.data?.pengaduan || null);
      setRiwayat(Array.isArray(result.data?.riwayat) ? result.data.riwayat : []);
    } catch (err) {
      console.error("Gagal mengambil riwayat pengaduan:", err);
      setError("Tidak bisa mengambil riwayat pengaduan dari server.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (pengaduanId) {
      loadRiwayat();
    }
  }, [pengaduanId]);

  return (
    <div className="fixed inset-0 z-[999] flex items-center justify-center bg-black/40 px-4 py-6">
      <div className="max-h-[90vh] w-full max-w-5xl overflow-hidden rounded-3xl bg-white shadow-2xl">
        <div className="flex items-start justify-between gap-4 border-b border-slate-200 p-5">
          <div>
            <h2 className="text-xl font-black text-slate-900">
              Detail Riwayat Pengaduan
            </h2>
            <p className="mt-1 text-sm text-slate-500">
              Lihat alur pengaduan, bukti awal, tindak lanjut, dan proses penyelesaiannya.
            </p>
          </div>

          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={loadRiwayat}
              className="inline-flex items-center gap-2 rounded-xl border border-slate-200 px-3 py-2 text-sm font-bold text-slate-700 hover:bg-slate-50"
            >
              <RefreshCw className="h-4 w-4" />
              Refresh
            </button>

            <button
              type="button"
              onClick={onClose}
              className="rounded-xl bg-slate-100 p-2 text-slate-600 hover:bg-slate-200"
            >
              <X className="h-5 w-5" />
            </button>
          </div>
        </div>

        <div className="max-h-[calc(90vh-88px)] overflow-y-auto p-5">
          {loading ? (
            <div className="flex items-center justify-center py-20">
              <div className="h-8 w-8 animate-spin rounded-full border-4 border-blue-100 border-t-blue-700" />
            </div>
          ) : error ? (
            <div className="rounded-2xl border border-red-200 bg-red-50 p-4 text-sm font-semibold text-red-600">
              {error}
            </div>
          ) : !data ? (
            <div className="py-16 text-center text-sm text-slate-500">
              Data pengaduan tidak ditemukan.
            </div>
          ) : (
            <div className="space-y-6">
              <div className="rounded-3xl border border-slate-200 bg-slate-50 p-5">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                  <div>
                    <p className="text-xs font-bold uppercase tracking-wide text-slate-500">
                      ID Pengaduan
                    </p>
                    <h3 className="mt-1 text-2xl font-black text-slate-900">
                      #{data.id}
                    </h3>
                  </div>

                  <div className="flex flex-wrap gap-2">
                    <span
                      className={`rounded-full px-3 py-1 text-xs font-bold ${
                        statusColors[data.status] || "bg-slate-100 text-slate-700"
                      }`}
                    >
                      {data.status || "-"}
                    </span>

                    <span
                      className={`rounded-full px-3 py-1 text-xs font-bold ${
                        alurColors[data.status_alur] || "bg-slate-100 text-slate-700"
                      }`}
                    >
                      {data.status_alur || "-"}
                    </span>
                  </div>
                </div>

                <div className="mt-5 grid gap-4 md:grid-cols-3">
                  <div className="rounded-2xl bg-white p-4">
                    <div className="mb-2 flex items-center gap-2 font-bold text-slate-700">
                      <User className="h-4 w-4 text-blue-700" />
                      Pelapor
                    </div>

                    <p className="font-semibold text-slate-900">
                      {data.nama || "-"}
                    </p>

                    <p className="text-sm text-slate-500">
                      {data.kontak || "Kontak tidak diisi"}
                    </p>
                  </div>

                  <div className="rounded-2xl bg-white p-4">
                    <div className="mb-2 flex items-center gap-2 font-bold text-slate-700">
                      <Building2 className="h-4 w-4 text-blue-700" />
                      SPPG Diadukan
                    </div>

                    <p className="font-semibold text-slate-900">
                      {data.sppg_nama || "SPPG belum dipilih"}
                    </p>

                    <p className="text-sm text-slate-500">
                      {data.sppg_kabupaten || "-"}, {data.sppg_provinsi || "-"}
                    </p>
                  </div>

                  <div className="rounded-2xl bg-white p-4">
                    <div className="mb-2 flex items-center gap-2 font-bold text-slate-700">
                      <School className="h-4 w-4 text-blue-700" />
                      Sekolah
                    </div>

                    <p className="font-semibold text-slate-900">
                      {data.nama_sekolah || "Sekolah belum dipilih"}
                    </p>

                    <p className="text-sm text-slate-500">
                      {data.alamat_sekolah || "-"}
                    </p>
                  </div>
                </div>

                <div className="mt-4 rounded-2xl bg-white p-4">
                  <p className="text-sm font-bold text-slate-700">
                    Isi Pengaduan
                  </p>

                  <p className="mt-2 text-sm leading-relaxed text-slate-600">
                    {data.isi || "-"}
                  </p>

                  <div className="mt-3 flex flex-wrap items-center gap-3 text-sm">
                    <span className="rounded-full bg-slate-100 px-3 py-1 font-semibold text-slate-600">
                      {data.kategori || "-"}
                    </span>

                    <span className="text-slate-500">
                      Dibuat: {formatDateTime(data.created_at)}
                    </span>

                    {data.bukti_url && (
                      <a
                        href={data.bukti_url}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center gap-1 font-bold text-blue-700 hover:underline"
                      >
                        <ImageIcon className="h-4 w-4" />
                        Lihat bukti awal
                      </a>
                    )}
                  </div>
                </div>
              </div>

              <div className="rounded-3xl border border-slate-200 bg-white p-5">
                <div className="mb-5">
                  <h3 className="text-lg font-black text-slate-900">
                    Validasi Awal
                  </h3>

                  <p className="text-sm text-slate-500">
                    Hasil pengecekan awal oleh sekolah atau validator.
                  </p>
                </div>

                <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="flex items-start gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-blue-100 text-blue-700">
                      <ShieldCheck className="h-5 w-5" />
                    </div>

                    <div className="flex-1">
                      <p className="font-black text-slate-900">
                        {data.validasi_status
                          ? data.validasi_status === "valid"
                            ? "Pengaduan Valid"
                            : "Pengaduan Tidak Valid"
                          : "Belum divalidasi"}
                      </p>

                      <p className="mt-1 text-sm text-slate-600">
                        {data.validasi_catatan || "Belum ada catatan validasi."}
                      </p>

                      <div className="mt-2 flex flex-wrap gap-3 text-xs font-semibold text-slate-500">
                        <span>Oleh: {data.validasi_oleh || "-"}</span>
                        <span>Waktu: {formatDateTime(data.validasi_at)}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <AksiPengaduanRole
                pengaduan={data}
                onSuccess={loadRiwayat}
              />

              <div className="rounded-3xl border border-slate-200 bg-white p-5">
                <div className="mb-5">
                  <h3 className="text-lg font-black text-slate-900">
                    Riwayat Tindak Lanjut
                  </h3>

                  <p className="text-sm text-slate-500">
                    Semua putaran tindak lanjut, perbaikan, dan validasi ulang.
                  </p>
                </div>

                {riwayat.length === 0 ? (
                  <div className="rounded-2xl bg-slate-50 p-8 text-center text-sm text-slate-500">
                    Belum ada riwayat tindak lanjut.
                  </div>
                ) : (
                  <div className="space-y-4">
                    {riwayat.map((item) => (
                      <div
                        key={item.id}
                        className="rounded-2xl border border-slate-200 bg-slate-50 p-4"
                      >
                        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                          <div>
                            <div className="flex flex-wrap items-center gap-2">
                              <span className="rounded-full bg-blue-100 px-3 py-1 text-xs font-bold text-blue-700">
                                Putaran {item.putaran_ke}
                              </span>

                              <span className="rounded-full bg-slate-200 px-3 py-1 text-xs font-bold text-slate-700">
                                {roleLabel[item.role_pengirim] || item.role_pengirim}
                              </span>

                              <span className="rounded-full bg-white px-3 py-1 text-xs font-bold text-slate-700">
                                {tahapLabel[item.tahap] || item.tahap}
                              </span>
                            </div>

                            <p className="mt-3 text-sm leading-relaxed text-slate-700">
                              {item.catatan || "-"}
                            </p>

                            {item.hasil_validasi && (
                              <div
                                className={`mt-3 inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-sm font-bold ${
                                  hasilColors[item.hasil_validasi] ||
                                  "bg-slate-50 text-slate-700 border-slate-200"
                                }`}
                              >
                                <CheckCircle2 className="h-4 w-4" />
                                Hasil: {item.hasil_validasi}
                              </div>
                            )}
                          </div>

                          <div className="text-xs font-semibold text-slate-500">
                            <Clock className="mr-1 inline h-3.5 w-3.5" />
                            {formatDateTime(item.created_at)}
                          </div>
                        </div>

                        <div className="mt-3 flex flex-wrap gap-3 text-sm">
                          {item.foto_url && (
                            <a
                              href={item.foto_url}
                              target="_blank"
                              rel="noreferrer"
                              className="inline-flex items-center gap-1 font-bold text-blue-700 hover:underline"
                            >
                              <ImageIcon className="h-4 w-4" />
                              Lihat foto
                            </a>
                          )}

                          {item.file_url && (
                            <a
                              href={item.file_url}
                              target="_blank"
                              rel="noreferrer"
                              className="inline-flex items-center gap-1 font-bold text-blue-700 hover:underline"
                            >
                              <FileText className="h-4 w-4" />
                              Lihat file
                            </a>
                          )}

                          {!item.foto_url && !item.file_url && (
                            <span className="inline-flex items-center gap-1 text-slate-400">
                              <AlertTriangle className="h-4 w-4" />
                              Tidak ada file/foto pada tahap ini.
                            </span>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}