import { useEffect, useMemo, useState } from "react";
import {
  UtensilsCrossed,
  Baby,
  HeartPulse,
  Wallet,
  Salad,
  RefreshCw,
  AlertCircle,
  PackageSearch,
  Users,
} from "lucide-react";

const MENU_API = "http://openplate.my.id/api/menu-harian/detail.php";

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

const getToday = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const kategoriList = ["Semua", "Siswa", "Ibu Hamil", "Ibu Menyusui"];

const kategoriStyle = {
  Siswa: "bg-blue-600 text-white",
  "Ibu Hamil": "bg-pink-600 text-white",
  "Ibu Menyusui": "bg-purple-600 text-white",
};

const getDotColor = (index) => {
  const colors = [
    "bg-yellow-400",
    "bg-orange-400",
    "bg-emerald-400",
    "bg-red-400",
    "bg-blue-400",
    "bg-purple-400",
    "bg-amber-400",
  ];

  return colors[index % colors.length];
};

const normalizeKategori = (kategori) => {
  if (!kategori || kategori === "Reguler") return "Siswa";
  return kategori;
};

const getMenuIcon = (kategori) => {
  const text = String(kategori || "").toLowerCase();

  if (text.includes("hamil")) return Baby;
  if (text.includes("menyusui")) return HeartPulse;

  return Users;
};

const getImageUrl = (menu) => {
  return (
    menu?.foto_makanan_url ||
    menu?.foto_menu_url ||
    menu?.gambar_url ||
    menu?.foto_bahan_url ||
    ""
  );
};

const getDanaPerOmprengan = (menu) => {
  return Number(menu?.dana_per_omprengan) || Number(menu?.dana_per_porsi) || 0;
};

const hasGizi = (menu) => {
  return [
    "kalori",
    "protein",
    "karbohidrat",
    "lemak",
    "serat",
    "zat_besi",
    "kalsium",
    "vitamin",
    "catatan_gizi",
  ].some((key) => {
    const value = menu?.[key];
    return value !== null && value !== undefined && String(value).trim() !== "" && Number(value) !== 0;
  });
};

const getBahanName = (item) => {
  return item.nama_bahan || item.nama || item.label || item.nama_item || "Bahan";
};

const getBahanTotal = (item) => {
  const total = Number(item.total);
  const nominal = Number(item.nominal);
  const harga = Number(item.harga);
  const hargaSatuan = Number(item.harga_satuan);
  const jumlah = Number(item.jumlah || item.stok);

  if (total > 0) return total;
  if (nominal > 0) return nominal;
  if (harga > 0 && jumlah > 0) return harga * jumlah;
  if (hargaSatuan > 0 && jumlah > 0) return hargaSatuan * jumlah;
  if (harga > 0) return harga;
  if (hargaSatuan > 0) return hargaSatuan;

  return 0;
};

function FoodItem({ item, index }) {
  const nama = typeof item === "string" ? item : item.nama_item || item.nama || "-";

  return (
    <div className="flex items-center gap-3 rounded-xl bg-slate-50 px-4 py-3">
      <span className={`h-3 w-3 rounded-full ${getDotColor(index)}`} />
      <span className="text-sm font-semibold text-slate-800">{nama}</span>
    </div>
  );
}

function BahanItem({ item }) {
  const jumlah = Number(item.jumlah || item.stok) || 0;
  const satuan = item.satuan || "";
  const hargaSatuan = Number(item.harga_satuan || item.harga) || 0;
  const total = getBahanTotal(item);

  return (
    <div className="rounded-xl bg-slate-50 px-4 py-3">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="break-words text-sm font-semibold text-slate-700">
            {getBahanName(item)}
          </p>

          <p className="mt-0.5 text-xs text-slate-500">
            {jumlah > 0 ? `${jumlah.toLocaleString("id-ID")} ${satuan}` : satuan || "-"}
            {hargaSatuan > 0 ? ` × ${formatRp(hargaSatuan)}` : ""}
          </p>
        </div>

        <span className="whitespace-nowrap text-sm font-black text-slate-950">
          {formatRp(total)}
        </span>
      </div>
    </div>
  );
}

function NutritionCard({ menu }) {
  if (!hasGizi(menu)) return null;

  const gizi = [
    ["Kalori", `${Number(menu.kalori || 0).toLocaleString("id-ID")} kkal`],
    ["Protein", `${Number(menu.protein || 0).toLocaleString("id-ID")} g`],
    ["Karbohidrat", `${Number(menu.karbohidrat || 0).toLocaleString("id-ID")} g`],
    ["Lemak", `${Number(menu.lemak || 0).toLocaleString("id-ID")} g`],
    ["Serat", `${Number(menu.serat || 0).toLocaleString("id-ID")} g`],
    ["Zat Besi", `${Number(menu.zat_besi || 0).toLocaleString("id-ID")} mg`],
    ["Kalsium", `${Number(menu.kalsium || 0).toLocaleString("id-ID")} mg`],
    ["Vitamin", menu.vitamin || "-"],
  ];

  return (
    <div className="mt-5 rounded-2xl border border-emerald-100 bg-emerald-50 px-4 py-4">
      <div className="mb-3 flex items-center gap-2">
        <Salad className="h-4 w-4 text-emerald-700" />
        <p className="text-sm font-black text-emerald-800">
          Informasi Gizi per Porsi
        </p>
      </div>

      <div className="grid grid-cols-2 gap-3 text-sm">
        {gizi.map(([label, value]) => (
          <div key={label} className="rounded-xl bg-white/70 px-3 py-2">
            <p className="text-xs text-slate-500">{label}</p>
            <p className="font-black text-slate-900">{value}</p>
          </div>
        ))}
      </div>

      {menu.catatan_gizi && (
        <p className="mt-3 rounded-xl bg-white/80 px-3 py-2 text-xs font-medium text-emerald-800">
          {menu.catatan_gizi}
        </p>
      )}
    </div>
  );
}

function MenuCard({ menu }) {
  const kategori = normalizeKategori(menu.kategori);
  const Icon = getMenuIcon(kategori);
  const items = Array.isArray(menu.items)
    ? menu.items
    : Array.isArray(menu.menu_items)
    ? menu.menu_items
    : [];

  const imageUrl = getImageUrl(menu);
  const dana = getDanaPerOmprengan(menu);

  return (
    <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
      <div className="relative h-72 overflow-hidden bg-slate-100">
        {imageUrl ? (
          <img
            src={imageUrl}
            alt={menu.nama_menu || "Foto makanan MBG"}
            className="h-full w-full object-contain bg-slate-100"
          />
        ) : (
          <div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-blue-100 via-sky-50 to-emerald-50">
            <UtensilsCrossed className="h-14 w-14 text-blue-500/70" />
          </div>
        )}

        <div className="absolute inset-0 bg-gradient-to-t from-black/45 to-transparent" />

        <span
          className={`absolute bottom-4 left-4 rounded-xl px-4 py-1.5 text-sm font-bold shadow-lg ${
            kategoriStyle[kategori] || "bg-blue-600 text-white"
          }`}
        >
          {kategori}
        </span>
      </div>

      <div className="p-6">
        <div className="mb-1 flex items-center gap-2">
          <Icon className="h-5 w-5 text-blue-600" />
          <h3 className="text-xl font-black text-slate-950">
            {menu.nama_menu || `Menu ${kategori}`}
          </h3>
        </div>

        {menu.deskripsi && (
          <p className="mb-4 text-sm text-slate-500">{menu.deskripsi}</p>
        )}

        {items.length === 0 ? (
          <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50 px-4 py-6 text-center text-sm text-slate-500">
            Belum ada item makanan pada menu ini.
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            {items.map((item, index) => (
              <FoodItem
                key={`${typeof item === "string" ? item : item.id || item.nama_item || item.nama}-${index}`}
                item={item}
                index={index}
              />
            ))}
          </div>
        )}

        <NutritionCard menu={menu} />

        <div className="mt-5 grid gap-3 sm:grid-cols-2">
          <div className="rounded-2xl border border-blue-100 bg-blue-50 px-4 py-4">
            <p className="text-sm text-slate-600">
              Dana per porsi / omprengan:
            </p>
            <p className="mt-1 text-lg font-black text-blue-700">
              {formatRp(dana)}
            </p>
          </div>

          <div className="rounded-2xl border border-emerald-100 bg-emerald-50 px-4 py-4">
            <p className="text-sm text-slate-600">Jumlah omprengan:</p>
            <p className="mt-1 text-lg font-black text-emerald-700">
              {Number(menu.jumlah_omprengan || 0).toLocaleString("id-ID")}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function MenuMakananHarian({ sppgId, tanggal }) {
  const [data, setData] = useState({
    menu_utama: null,
    menu_khusus: [],
    rincian_bahan: [],
  });

  const [activeKategori, setActiveKategori] = useState("Semua");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const selectedTanggal = useMemo(() => tanggal || getToday(), [tanggal]);

  const loadMenu = async () => {
    if (!sppgId) {
      setLoading(false);
      setError("ID SPPG tidak tersedia.");
      return;
    }

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

      const url = `${MENU_API}?sppg_id=${sppgId}&tanggal=${selectedTanggal}`;
      const res = await fetch(url);

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

      const result = await res.json();

      if (!result.success) {
        setData({
          menu_utama: null,
          menu_khusus: [],
          rincian_bahan: [],
        });

        setError(result.message || "Data menu harian belum tersedia.");
        return;
      }

      setData({
        menu_utama: result.data?.menu_utama || null,
        menu_khusus: Array.isArray(result.data?.menu_khusus)
          ? result.data.menu_khusus
          : [],
        rincian_bahan: Array.isArray(result.data?.rincian_bahan)
          ? result.data.rincian_bahan
          : Array.isArray(result.data?.bahan)
          ? result.data.bahan
          : Array.isArray(result.data?.bahan_makanan)
          ? result.data.bahan_makanan
          : [],
      });
    } catch (err) {
      console.error("Gagal mengambil menu makanan harian:", err);
      setError("Gagal mengambil data menu harian dari server.");

      setData({
        menu_utama: null,
        menu_khusus: [],
        rincian_bahan: [],
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadMenu();
  }, [sppgId, selectedTanggal]);

  const semuaMenu = useMemo(() => {
    const list = [];

    if (data.menu_utama) {
      list.push({
        ...data.menu_utama,
        kategori: normalizeKategori(data.menu_utama.kategori),
      });
    }

    data.menu_khusus.forEach((menu) => {
      list.push({
        ...menu,
        kategori: normalizeKategori(menu.kategori),
      });
    });

    return list;
  }, [data.menu_utama, data.menu_khusus]);

  const menuTampil = useMemo(() => {
    if (activeKategori === "Semua") return semuaMenu;

    return semuaMenu.filter(
      (menu) => normalizeKategori(menu.kategori) === activeKategori
    );
  }, [semuaMenu, activeKategori]);

  const totalBahan = data.rincian_bahan.reduce(
    (total, item) => total + getBahanTotal(item),
    0
  );

  const totalDanaMenu = menuTampil.reduce((total, menu) => {
    const danaTotal = Number(menu.dana_total || 0);
    const dana = getDanaPerOmprengan(menu);
    const jumlah = Number(menu.jumlah_omprengan || 0);

    if (danaTotal > 0) {
      return total + danaTotal;
    }

    if (jumlah > 0 && dana > 0) {
      return total + dana * jumlah;
    }

    if (dana > 0) {
      return total + dana;
    }

    return total;
  }, 0);

  const hasData = semuaMenu.length > 0 || data.rincian_bahan.length > 0;

  return (
    <div className="mb-8 space-y-6 print:hidden">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <div className="inline-flex items-center gap-2 rounded-full bg-blue-50 px-3 py-1 text-xs font-bold text-blue-700">
            <UtensilsCrossed className="h-3.5 w-3.5" />
            Menu & Dana Makanan
          </div>

          <h2 className="mt-3 text-2xl font-black text-slate-950">
            Menu Harian Siswa, Ibu Hamil, dan Ibu Menyusui
          </h2>

          <p className="mt-1 text-sm text-slate-500">
            Output menu berdasarkan kategori penerima yang diinput oleh SPPG.
          </p>
        </div>

        <button
          type="button"
          onClick={loadMenu}
          className="inline-flex w-fit items-center gap-2 rounded-xl border border-blue-100 bg-white px-3 py-2 text-xs font-bold text-blue-700 shadow-sm transition hover:bg-blue-50"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
          Refresh
        </button>
      </div>

      <div className="flex flex-wrap gap-2">
        {kategoriList.map((kategori) => (
          <button
            key={kategori}
            type="button"
            onClick={() => setActiveKategori(kategori)}
            className={`rounded-full px-4 py-2 text-xs font-black transition ${
              activeKategori === kategori
                ? "bg-blue-700 text-white shadow"
                : "bg-white text-slate-600 border border-slate-200 hover:bg-blue-50"
            }`}
          >
            {kategori}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="rounded-2xl border border-slate-200 bg-white p-8 text-center text-sm text-slate-500 shadow-sm">
          Mengambil data menu harian dari database...
        </div>
      ) : error && !hasData ? (
        <div className="rounded-2xl border border-amber-200 bg-amber-50 p-5 text-sm text-amber-700">
          <div className="flex items-start gap-3">
            <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0" />
            <div>
              <p className="font-bold">Data menu belum tersedia</p>
              <p className="mt-1">
                {error} Tambahkan laporan SPPG agar bagian ini tampil.
              </p>
            </div>
          </div>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-6 xl:grid-cols-2 items-start">
          <div className="space-y-6">
            {menuTampil.length === 0 ? (
              <div className="rounded-2xl border border-dashed border-slate-200 bg-white p-8 text-center text-sm text-slate-500 shadow-sm">
                Belum ada menu untuk kategori {activeKategori}.
              </div>
            ) : (
              menuTampil.map((menu) => (
                <MenuCard
                  key={menu.id || `${menu.kategori}-${menu.nama_menu}`}
                  menu={menu}
                />
              ))
            )}
          </div>

          <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
            <div className="mb-5 flex items-center gap-2">
              <PackageSearch className="h-5 w-5 text-blue-600" />
              <h3 className="text-xl font-black text-slate-950">
                Rincian Bahan Makanan
              </h3>
            </div>

            {data.rincian_bahan.length === 0 ? (
              <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50 px-4 py-6 text-center text-sm text-slate-500">
                Rincian bahan belum tersedia.
              </div>
            ) : (
              <div className="grid grid-cols-1 gap-3">
                {data.rincian_bahan.map((item, index) => (
                  <BahanItem
                    key={item.id || `${getBahanName(item)}-${index}`}
                    item={item}
                  />
                ))}
              </div>
            )}

            <div className="mt-5 grid gap-3 sm:grid-cols-2">
              <div className="rounded-2xl border border-emerald-100 bg-emerald-50 px-4 py-4">
                <p className="text-sm text-slate-600">Total estimasi bahan:</p>
                <p className="mt-1 text-lg font-black text-emerald-700">
                  {formatRp(totalBahan)}
                </p>
              </div>

              <div className="rounded-2xl border border-blue-100 bg-blue-50 px-4 py-4">
                <p className="text-sm text-slate-600">
                  Total estimasi dana menu tampil:
                </p>
                <p className="mt-1 text-lg font-black text-blue-700">
                  {formatRp(totalDanaMenu || totalBahan)}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}