import { useState, useEffect, useMemo } from "react";
import {
  CheckCircle,
  XCircle,
  Eye,
  Upload,
  Camera,
  RefreshCw,
  Search,
  MapPin,
  School,
  Utensils,
  Wallet,
  PackageCheck,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAuditLog } from "../../hooks/useAuditLog";
import { useNotifications } from "../../hooks/useNotifications";
import { toast } from "sonner";

const API_BASE = "http://localhost/backend";
const LIST_VALIDASI_API = `${API_BASE}/api/menu-harian/list-validasi.php`;
const UPDATE_VALIDASI_API = `${API_BASE}/api/menu-harian/update-validasi.php`;
const UPLOAD_FOTO_API = `${API_BASE}/api/upload_foto_omprengan.php`;

const formatRp = (value) => {
  return "Rp " + Number(value || 0).toLocaleString("id-ID");
};

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

  return new Date(value).toLocaleDateString("id-ID", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });
};

const fileUrl = (path) => {
  if (!path) return "";
  if (String(path).startsWith("http")) return path;
  return `${API_BASE}/${path}`;
};

const isPuskesmas = (item) => item?.lokasi_mbg_tipe === "puskesmas";

const getMenuItems = (item) => {
  if (Array.isArray(item.menu_items) && item.menu_items.length > 0) {
    return item.menu_items;
  }

  if (Array.isArray(item.items) && item.items.length > 0) {
    return item.items;
  }

  if (
    item.nama_menu &&
    item.nama_menu !== "Menu Siswa" &&
    item.nama_menu !== "Menu Ibu Hamil" &&
    item.nama_menu !== "Menu Ibu Menyusui"
  ) {
    return [item.nama_menu];
  }

  return [];
};

const getLokasiMbgLabel = (item) => {
  if (isPuskesmas(item)) {
    const nama = item.puskesmas_nama || "Puskesmas belum dipilih";
    const daerah = item.puskesmas_daerah || item.lokasi || "";
    return daerah ? `${nama} - ${daerah}` : nama;
  }

  const namaSekolah = item.nama_sekolah || "Sekolah belum dipilih";
  const jenjang = item.jenjang ? ` • ${item.jenjang}` : "";
  return `${namaSekolah}${jenjang}`;
};

const getWilayahLabel = (item) => {
  if (isPuskesmas(item)) {
    return item.lokasi || item.puskesmas_daerah || "-";
  }

  return item.alamat_sekolah || item.lokasi || "-";
};

const getPorsiValue = (item) => {
  if (isPuskesmas(item)) {
    return Number(item.jumlah_omprengan || 0);
  }

  return Number(item.jumlah_siswa || item.jumlah_omprengan || 0);
};

const getPorsiTitle = (item) => {
  return isPuskesmas(item) ? "Porsi/Penerima" : "Porsi/Siswa";
};

export default function ValidasiData() {
  const [items, setItems] = useState([]);
  const [status, setStatus] = useState("menunggu_validasi");
  const [tanggal, setTanggal] = useState("");
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState(null);
  const [catatan, setCatatan] = useState("");
  const [fotoBukti, setFotoBukti] = useState("");
  const [uploading, setUploading] = useState(false);
  const [savingId, setSavingId] = useState(null);
  const [error, setError] = useState("");

  const { addLog } = useAuditLog();
  const { addNotification } = useNotifications();

  const role = localStorage.getItem("role") || "validator";
  const sekolahId =
    localStorage.getItem("sekolah_id") ||
    localStorage.getItem("user_sekolah_id") ||
    "";

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

      const params = new URLSearchParams({
        role,
        status,
      });

      if (tanggal) params.set("tanggal", tanggal);
      if (search.trim()) params.set("search", search.trim());

      if ((role === "validator" || role === "sekolah") && sekolahId) {
        params.set("sekolah_id", sekolahId);
      }

      const res = await fetch(`${LIST_VALIDASI_API}?${params.toString()}`);
      const result = await res.json();

      if (!result.success) {
        setError(result.message || "Gagal mengambil data validasi.");
        setItems([]);
        return;
      }

      setItems(Array.isArray(result.data?.items) ? result.data.items : []);
    } catch (err) {
      console.error("Gagal mengambil laporan validasi:", err);
      setError("Tidak bisa mengambil data dari server validasi.");
      setItems([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [status, tanggal]);

  const filteredItems = useMemo(() => {
    const keyword = search.trim().toLowerCase();

    if (!keyword) return items;

    return items.filter((item) => {
      const combined = [
        item.nama_sppg,
        item.nama_sekolah,
        item.puskesmas_nama,
        item.puskesmas_daerah,
        item.lokasi_mbg_tipe,
        item.provinsi,
        item.kabupaten,
        item.lokasi,
        item.status,
        ...(getMenuItems(item) || []),
      ]
        .join(" ")
        .toLowerCase();

      return combined.includes(keyword);
    });
  }, [items, search]);

  const handleUploadBukti = async (file) => {
    if (!file) return;

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

    try {
      setUploading(true);

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

      const data = await res.json();

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

      const url = data.data?.url || data.file_url || "";
      setFotoBukti(url);
      toast.success("Foto verifikasi terupload");
    } catch (err) {
      console.error("Gagal upload bukti validator:", err);
      toast.error("Tidak bisa upload foto bukti verifikasi.");
    } finally {
      setUploading(false);
    }
  };

  const handleValidasi = async (item, hasil) => {
    if (!fotoBukti) {
      toast.error("Wajib upload foto bukti verifikasi sebelum memvalidasi!");
      return;
    }

    if (!catatan.trim()) {
      toast.error("Wajib mengisi catatan validasi!");
      return;
    }

    try {
      setSavingId(item.id);

      const res = await fetch(UPDATE_VALIDASI_API, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          id: item.id,
          hasil: hasil === "Sesuai" ? "sesuai" : "tidak_sesuai",
          catatan_validasi: `${catatan}\n\nFoto bukti validator: ${fotoBukti}`,
        }),
      });

      const result = await res.json();

      if (!result.success) {
        toast.error(result.message || "Gagal menyimpan validasi.");
        return;
      }

      setItems((prev) => prev.filter((i) => i.id !== item.id));

      addLog({
        actor: "Validator",
        action: `Memvalidasi laporan: ${hasil}`,
        target: `${item.nama_sppg || item.sppg_id} - ${item.tanggal}`,
        role: "validator",
      });

      addNotification({
        title: `Laporan Divalidasi: ${hasil}`,
        message: `Laporan tanggal ${item.tanggal} ditandai "${hasil}" oleh validator.`,
        type: hasil === "Sesuai" ? "success" : "alert",
      });

      setSelected(null);
      setCatatan("");
      setFotoBukti("");

      toast.success(`Laporan berhasil divalidasi: ${hasil}`);
    } catch (err) {
      console.error("Gagal validasi laporan:", err);
      toast.error("Tidak bisa terhubung ke server validasi.");
    } finally {
      setSavingId(null);
    }
  };

  return (
    <div className="p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-black text-foreground">
          Validasi Laporan SPPG
        </h1>
        <p className="text-sm text-muted-foreground mt-1">
          Tinjau laporan dan foto dari SPPG, upload foto bukti verifikasi, lalu tandai Sesuai atau Tidak Sesuai.
        </p>
      </div>

      <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
        <p className="text-sm font-bold text-blue-800 mb-1">Alur Validasi</p>
        <ol className="text-xs text-blue-700 space-y-1 list-decimal list-inside">
          <li>Lihat menu makanan dan distribusi yang dikirim pihak SPPG</li>
          <li>Cek foto bukti bahan/omprengan dan makanan jadi</li>
          <li>Upload foto bukti verifikasi dari validator</li>
          <li>Tulis catatan hasil pengamatan</li>
          <li>
            Tandai <strong>Sesuai</strong> atau <strong>Tidak Sesuai</strong> — hasil ini akan terlihat oleh masyarakat
          </li>
        </ol>
      </div>

      <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
        <div className="bg-card rounded-xl border border-border p-4 text-center">
          <p className="text-3xl font-black text-amber-600">{items.length}</p>
          <p className="text-xs text-muted-foreground mt-1">
            Laporan Menunggu Validasi
          </p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4 text-center">
          <p className="text-3xl font-black text-primary">{filteredItems.length}</p>
          <p className="text-xs text-muted-foreground mt-1">Tampil di Filter</p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4 text-center">
          <p className="text-3xl font-black text-emerald-600">
            {items
              .reduce((acc, item) => acc + Number(item.jumlah_omprengan || 0), 0)
              .toLocaleString("id-ID")}
          </p>
          <p className="text-xs text-muted-foreground mt-1">Total Omprengan</p>
        </div>

        <div className="bg-card rounded-xl border border-border p-4 text-center">
          <p className="text-3xl font-black text-purple-600">
            {items
              .reduce((acc, item) => acc + getPorsiValue(item), 0)
              .toLocaleString("id-ID")}
          </p>
          <p className="text-xs text-muted-foreground mt-1">Total Porsi/Penerima</p>
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border p-4">
        <div className="grid grid-cols-1 gap-3 lg:grid-cols-[180px_220px_1fr_auto]">
          <input
            type="date"
            value={tanggal}
            onChange={(e) => setTanggal(e.target.value)}
            className="rounded-xl border border-input bg-background px-3 py-2 text-sm outline-none"
          />

          <select
            value={status}
            onChange={(e) => setStatus(e.target.value)}
            className="rounded-xl border border-input bg-background px-3 py-2 text-sm outline-none"
          >
            <option value="menunggu_validasi">Menunggu Validasi</option>
            <option value="tervalidasi">Tervalidasi</option>
            <option value="tidak_sesuai">Tidak Sesuai</option>
            <option value="semua">Semua Status</option>
          </select>

          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Cari SPPG, sekolah, wilayah, menu, atau susu..."
              className="w-full rounded-xl border border-input bg-background py-2 pl-10 pr-3 text-sm outline-none"
            />
          </div>

          <Button
            type="button"
            onClick={loadData}
            className="rounded-xl bg-primary"
          >
            <RefreshCw className={`w-4 h-4 mr-1 ${loading ? "animate-spin" : ""}`} />
            Refresh
          </Button>
        </div>
      </div>

      {error && (
        <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-600">
          {error}
        </div>
      )}

      {loading ? (
        <div className="flex justify-center py-12">
          <div className="w-6 h-6 border-2 border-primary/20 border-t-primary rounded-full animate-spin" />
        </div>
      ) : filteredItems.length === 0 ? (
        <div className="text-center py-16 text-muted-foreground text-sm bg-card rounded-xl border border-border">
          Tidak ada laporan yang perlu divalidasi saat ini.
        </div>
      ) : (
        <div className="space-y-4">
          {filteredItems.map((item) => (
            <div
              key={item.id}
              className="bg-card rounded-xl border border-border overflow-hidden"
            >
              <div className="p-4 sm:p-5">
                <div className="flex items-start justify-between gap-3 flex-wrap">
                  <div className="flex-1">
                    <div className="flex flex-wrap items-center gap-2 mb-2">
                      <span className="px-2 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-700">
                        {item.status || "Menunggu Validasi"}
                      </span>

                      <span className="px-2 py-0.5 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">
                        {item.kategori || "Reguler"}
                      </span>

                      <span className="text-xs text-muted-foreground font-mono">
                        ID #{item.id}
                      </span>
                    </div>

                    <p className="font-black text-lg text-foreground">
                      {item.nama_sppg || "SPPG"}
                    </p>

                    <div className="mt-2 flex flex-wrap gap-3 text-xs text-muted-foreground">
                      <span className="inline-flex items-center gap-1">
                        <School className="w-3.5 h-3.5 text-primary" />
                        {getLokasiMbgLabel(item)}
                      </span>

                      <span className="inline-flex items-center gap-1">
                        <MapPin className="w-3.5 h-3.5 text-emerald-600" />
                        {getWilayahLabel(item)} •{" "}
                        {item.kabupaten || item.provinsi
                          ? `${item.kabupaten || "-"}, ${item.provinsi || "-"}`
                          : "Lokasi MBG"}
                      </span>

                      <span>{formatDate(item.tanggal)} • {item.waktu || "-"}</span>
                    </div>

                    <div className="mt-3 grid grid-cols-1 gap-2 text-xs sm:grid-cols-3">
                      <div className="rounded-xl bg-muted/50 p-3">
                        <p className="font-bold text-foreground flex items-center gap-1">
                          <PackageCheck className="w-3.5 h-3.5 text-emerald-600" />
                          Omprengan
                        </p>
                        <p className="mt-1 text-muted-foreground">
                          {Number(item.jumlah_omprengan || 0).toLocaleString("id-ID")}
                        </p>
                      </div>

                      <div className="rounded-xl bg-muted/50 p-3">
                        <p className="font-bold text-foreground flex items-center gap-1">
                          <Utensils className="w-3.5 h-3.5 text-amber-600" />
                          {getPorsiTitle(item)}
                        </p>
                        <p className="mt-1 text-muted-foreground">
                          {getPorsiValue(item).toLocaleString("id-ID")}
                        </p>
                      </div>

                      <div className="rounded-xl bg-muted/50 p-3">
                        <p className="font-bold text-foreground flex items-center gap-1">
                          <Wallet className="w-3.5 h-3.5 text-blue-600" />
                          Dana
                        </p>
                        <p className="mt-1 text-muted-foreground">
                          {formatRp(item.dana_total)}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="mt-4 rounded-xl border border-border bg-muted/30 p-4">
                  <p className="text-xs font-semibold text-muted-foreground mb-2 uppercase tracking-wide">
                    Menu Makanan Hari Ini
                  </p>

                  <div className="flex flex-wrap gap-2">
                    {getMenuItems(item).length === 0 ? (
                      <span className="text-sm text-muted-foreground">Menu belum ada</span>
                    ) : (
                      getMenuItems(item).map((menu, index) => (
                        <span
                          key={`${item.id}-${menu}-${index}`}
                          className="rounded-full bg-background px-3 py-1 text-xs font-semibold text-foreground border border-border"
                        >
                          {menu}
                        </span>
                      ))
                    )}
                  </div>
                </div>

                {(item.foto_bahan_url || item.foto_makanan_url) && (
                  <div className="mt-4">
                    <p className="text-xs font-semibold text-muted-foreground mb-2 uppercase tracking-wide">
                      Foto dari SPPG
                    </p>

                    <div className="flex gap-3 flex-wrap">
                      {item.foto_bahan_url && (
                        <a href={fileUrl(item.foto_bahan_url)} target="_blank" rel="noreferrer">
                          <div className="relative group">
                            <img
                              src={fileUrl(item.foto_bahan_url)}
                              alt="Foto Bahan"
                              className="w-40 h-28 rounded-xl object-cover border border-border shadow-sm group-hover:opacity-90 transition"
                            />
                            <div className="absolute bottom-1 left-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded">
                              Bahan/Omprengan
                            </div>
                          </div>
                        </a>
                      )}

                      {item.foto_makanan_url && (
                        <a href={fileUrl(item.foto_makanan_url)} target="_blank" rel="noreferrer">
                          <div className="relative group">
                            <img
                              src={fileUrl(item.foto_makanan_url)}
                              alt="Foto Makanan"
                              className="w-40 h-28 rounded-xl object-cover border border-border shadow-sm group-hover:opacity-90 transition"
                            />
                            <div className="absolute bottom-1 left-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded">
                              Makanan Jadi
                            </div>
                          </div>
                        </a>
                      )}
                    </div>
                  </div>
                )}

                {item.catatan && (
                  <div className="mt-4 rounded-xl bg-blue-50 p-3 text-xs text-blue-700">
                    <b>Catatan SPPG:</b> {item.catatan}
                  </div>
                )}

                {selected !== item.id && item.status === "menunggu_validasi" && (
                  <Button
                    size="sm"
                    variant="outline"
                    className="mt-4 rounded-full text-xs"
                    onClick={() => {
                      setSelected(item.id);
                      setFotoBukti("");
                      setCatatan("");
                    }}
                  >
                    <Eye className="w-3.5 h-3.5 mr-1" />
                    Tinjau dan Validasi
                  </Button>
                )}
              </div>

              {selected === item.id && (
                <div className="border-t border-border bg-muted/30 p-4 sm:p-5 space-y-5">
                  <p className="text-sm font-bold text-foreground flex items-center gap-2">
                    <Camera className="w-4 h-4 text-primary" />
                    Isi Hasil Verifikasi Validator
                  </p>

                  <div>
                    <label className="text-xs font-semibold mb-2 block">
                      Foto Bukti Verifikasi <span className="text-red-500">*</span>
                      <span className="text-muted-foreground font-normal ml-1">
                        (foto yang diambil validator saat verifikasi)
                      </span>
                    </label>

                    <label
                      className={`flex items-center gap-4 border-2 border-dashed rounded-xl p-4 cursor-pointer transition-colors w-full ${
                        fotoBukti
                          ? "border-emerald-400 bg-emerald-50"
                          : "border-amber-400 bg-amber-50 hover:bg-amber-100"
                      }`}
                    >
                      {fotoBukti ? (
                        <>
                          <img
                            src={fotoBukti}
                            alt="bukti validator"
                            className="w-24 h-20 rounded-xl object-cover border border-emerald-300"
                          />
                          <div>
                            <p className="text-sm font-bold text-emerald-700">
                              Foto terupload
                            </p>
                            <p className="text-xs text-emerald-600">
                              Klik untuk ganti foto
                            </p>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="w-16 h-16 bg-amber-200 rounded-xl flex items-center justify-center flex-shrink-0">
                            <Upload className="w-7 h-7 text-amber-600" />
                          </div>
                          <div>
                            <p className="text-sm font-bold text-amber-800">
                              {uploading ? "Mengupload..." : "Upload Foto Bukti Verifikasi"}
                            </p>
                            <p className="text-xs text-amber-600">
                              Foto yang diambil saat verifikasi lapangan
                            </p>
                          </div>
                        </>
                      )}

                      <input
                        type="file"
                        accept="image/*"
                        className="hidden"
                        disabled={uploading}
                        onChange={(e) =>
                          e.target.files?.[0] && handleUploadBukti(e.target.files[0])
                        }
                      />
                    </label>
                  </div>

                  <div>
                    <label className="text-xs font-semibold mb-1 block">
                      Catatan Validator <span className="text-red-500">*</span>
                      <span className="text-muted-foreground font-normal ml-1">
                        (hasil pengamatan kondisi makanan dan distribusi)
                      </span>
                    </label>

                    <textarea
                      rows={3}
                      placeholder="Contoh: Menu sesuai laporan, kondisi makanan baik, jumlah omprengan sesuai."
                      value={catatan}
                      onChange={(e) => setCatatan(e.target.value)}
                      className="w-full rounded-xl border border-input bg-background px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring"
                    />
                  </div>

                  <div className="flex gap-3 flex-wrap items-center">
                    <Button
                      size="sm"
                      className="rounded-full bg-emerald-600 hover:bg-emerald-700 px-5"
                      disabled={uploading || savingId === item.id}
                      onClick={() => handleValidasi(item, "Sesuai")}
                    >
                      <CheckCircle className="w-4 h-4 mr-1" />
                      Sesuai
                    </Button>

                    <Button
                      size="sm"
                      className="rounded-full bg-red-500 hover:bg-red-600 px-5"
                      disabled={uploading || savingId === item.id}
                      onClick={() => handleValidasi(item, "Tidak Sesuai")}
                    >
                      <XCircle className="w-4 h-4 mr-1" />
                      Tidak Sesuai
                    </Button>

                    <Button
                      size="sm"
                      variant="ghost"
                      className="rounded-full"
                      onClick={() => {
                        setSelected(null);
                        setFotoBukti("");
                        setCatatan("");
                      }}
                    >
                      Batal
                    </Button>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
