"use client";

import { useEffect, useMemo, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  ArrowLeft,
  ClipboardCheck,
  Warehouse,
  Boxes,
  AlertTriangle,
  CheckCircle2,
  XCircle,
} from "lucide-react";
import { useSession } from "next-auth/react";
import { formatNumber } from "@/app/components/formatNumber";

export default function StockOpnameReviewPage() {
  const { id } = useParams();
  const router = useRouter();
  const [submitting, setSubmitting] = useState(false);
  async function handleToChecked() {
    try {
      setSubmitting(true);

      const res = await fetch(`/api/stock-opname/${id}/to-checked`, {
        method: "POST",
      });

      const json = await res.json();
      if (!res.ok) {
        alert(json.message || "Gagal proses ke CHECKED");
        return;
      }

      await fetchData();
      alert("Berhasil dipindahkan ke CHECKED");
    } finally {
      setSubmitting(false);
    }
  }

  const { data: session, status } = useSession();
  const currentUser = session?.user as any;

  const [loading, setLoading] = useState(true);
  const [datas, setData] = useState<any>(null);
  // const [isAdmin, setIsAdmin] = useState(false);

  /* =========================
     FETCH DATA
  ========================= */
  async function fetchData() {
    try {
      setLoading(true);

      const res = await fetch(`/api/stock-opname/${id}/review`, {
        cache: "no-store",
      });

      const json = await res.json();
      // console.log("Jsonnya: ", json);
      setData(json.data);
    } finally {
      setLoading(false);
    }
  }

  const isAdmin = useMemo(() => {
    return currentUser?.role === "ADMIN";
  }, [currentUser]);

  useEffect(() => {
    if (status === "loading") return;

    if (status === "unauthenticated") {
      router.replace("/login");
      return;
    }

    const allowedRoles = ["ADMIN", "OPERATOR", "SUPERVISOR"];

    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/");
      return;
    }

    if (id) fetchData();
  }, [id, status, currentUser?.role]);

  /* =========================
     GROUP BY BIN
  ========================= */
  const grouped = useMemo(() => {
    if (!datas?.items) return {};

    const map: any = {};

    datas.items.forEach((item: any) => {
      const key = item.bin_name || "NO_BIN";
      if (!map[key]) map[key] = [];
      map[key].push(item);
    });

    return map;
  }, [datas]);

  /* =========================
     LOADING
  ========================= */
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-linear-to-br from-emerald-50 via-white to-lime-50">
        <div className="px-10 py-6 rounded-3xl bg-white shadow-2xl border border-emerald-100 text-emerald-700 font-black animate-pulse">
          🌿 Loading review data...
        </div>
      </div>
    );
  }

  if (!datas) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-linear-to-br from-emerald-50 via-white to-lime-50">
        <div className="text-center p-10 bg-white rounded-3xl shadow-2xl border border-emerald-100">
          <p className="text-2xl font-black text-emerald-900">
            Data tidak ditemukan
          </p>

          <button
            onClick={() => router.back()}
            className="mt-6 px-6 py-3 bg-emerald-600 text-white rounded-2xl font-bold shadow-lg hover:scale-105 transition"
          >
            Back
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-linear-to-br from-emerald-50 via-white to-lime-50 p-6 space-y-8">

      {/* BACK BUTTON */}
      <button
        onClick={() => router.back()}
        className="flex items-center gap-2 px-5 py-3 bg-white/70 backdrop-blur-xl rounded-2xl border shadow-lg font-bold text-emerald-700 hover:-translate-y-1 hover:shadow-xl transition"
      >
        <ArrowLeft size={18} />
        Back
      </button>

      {/* HERO */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="
          relative overflow-hidden
          rounded-[28px] sm:rounded-[36px] md:rounded-[42px] xl:rounded-[48px]
          border border-emerald-100/80
          shadow-[0_25px_70px_rgba(16,185,129,0.22)]
        "
      >
        {/* BACKGROUND */}
        <div className="absolute inset-0 bg-linear-to-br from-emerald-500 via-lime-400 to-green-300" />

        {/* GLASS */}
        <div className="absolute inset-0 bg-white/20 backdrop-blur-3xl" />

        {/* LIGHT EFFECT */}
        <div className="absolute inset-0 opacity-20 bg-[radial-gradient(circle_at_25%_20%,white,transparent_45%)]" />
        <div className="absolute -top-12 -left-10 w-44 h-44 bg-white/30 rounded-full blur-3xl" />
        <div className="absolute bottom-0 right-0 w-56 h-56 bg-lime-200/30 rounded-full blur-3xl" />

        {/* CONTENT */}
        <div className="relative p-5 sm:p-7 md:p-10 xl:p-14">

          <div
            className="
              flex flex-col xl:flex-row
              xl:items-center xl:justify-between
              gap-6 xl:gap-10
            "
          >

            {/* LEFT SIDE */}
            <div className="flex-1 min-w-0 space-y-5">

              {/* BADGE */}
              <div
                className="
                  inline-flex max-w-full items-center gap-2
                  px-4 py-2 rounded-full
                  bg-white/75 border border-white/70
                  shadow-lg backdrop-blur-md
                  text-xs sm:text-sm font-bold text-emerald-800
                "
              >
                <ClipboardCheck size={16} className="shrink-0" />
                <span className="truncate">
                  Review Stock Opname
                </span>
              </div>

              {/* TITLE */}
              <h1
                className="
                  text-2xl sm:text-4xl md:text-5xl xl:text-6xl
                  font-black text-emerald-950
                  leading-tight tracking-tight
                  drop-shadow-[0_3px_12px_rgba(0,0,0,0.14)]
                  break-words
                  [overflow-wrap:anywhere]
                "
              >
                {datas.opname_number}
              </h1>

              {/* DESC */}
              <p
                className="
                  text-emerald-950/75
                  text-sm sm:text-base md:text-lg
                  leading-relaxed
                  max-w-2xl
                "
              >
                Bandingkan stok sistem dengan hasil hitung fisik
                untuk memastikan data inventory akurat sebelum proses berikutnya.
              </p>

            </div>

            {/* RIGHT SIDE */}
            <div
              className="
                w-full xl:w-auto
                flex flex-col sm:flex-row xl:flex-col
                gap-4 xl:min-w-72.5
              "
            >

              {/* STATUS CARD */}
              <div
                className="
                  flex-1 xl:flex-none
                  rounded-[26px]
                  bg-white/65 backdrop-blur-xl
                  border border-white/80
                  px-5 py-4
                  shadow-[0_15px_40px_rgba(0,0,0,0.12)]
                "
              >
                <div className="text-xs font-bold uppercase tracking-wide text-emerald-700/80">
                  Status
                </div>

                <div className="mt-2 text-lg sm:text-xl font-black text-emerald-950 wrap-break-word">
                  {datas.status === "REVIEW" && "Sedang Review"}
                  {datas.status === "CHECKED" && "Sudah Dicek"}
                  {datas.status === "APPROVED" && "Disetujui"}
                  {datas.status === "CANCELLED" && "Cancel"}
                  {datas.status === "POSTED" && "Sudah Diposting"}
                  {datas.status === "COUNTING" && "Sedang Hitung"}
                </div>
              </div>

              {/* BUTTON */}
          <div className="relative w-full sm:flex-1 xl:w-full xl:flex-none group">
              <button
                onClick={handleToChecked}
                disabled={
                  submitting ||
                  datas.status !== "REVIEW" ||
                  !isAdmin
                }
                className={`
                  w-full
                  px-5 py-4 rounded-[22px]
                  font-black text-sm sm:text-base
                  shadow-[0_18px_35px_rgba(16,185,129,0.25)]
                  transition-all duration-300
                  flex items-center justify-center gap-2
                  ${
                    datas.status !== "REVIEW" || !isAdmin
                      ? "bg-slate-200 text-slate-400 cursor-not-allowed shadow-none"
                      : "bg-linear-to-r from-emerald-500 to-lime-500 text-white hover:scale-[1.02] active:scale-95"
                  }
                `}
              >
                {submitting ? (
                  "Memproses..."
                ) : (
                  <>✔ Review Selesai → Checked</>
                )}
              </button>

              {/* TOOLTIP HOVER (ONLY WHEN DISABLED) */}
              {!isAdmin && (
                <div
                  className="
                    absolute left-1/2 -translate-x-1/2 -top-12
                    hidden group-hover:block
                    bg-black/80 text-white text-xs font-bold
                    px-3 py-2 rounded-lg
                    whitespace-nowrap
                    shadow-lg
                  "
                >
                  Hanya Admin yang Bisa merubah Ini
                </div>
              )}
            </div>


            </div>

          </div>
        </div>
      </motion.div>


      {/* SUMMARY */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-5 md:gap-6">

        <Card
          icon={
            <div
              className="
                h-11 w-11 sm:h-12 sm:w-12
                rounded-2xl
                bg-linear-to-br from-emerald-400 to-green-500
                text-white
                flex items-center justify-center
                shadow-[0_12px_28px_rgba(16,185,129,0.28)]
              "
            >
              <Warehouse size={18} />
            </div>
          }
          label="Gudang"
          value={datas.warehouse_name}
        />

        <Card
          icon={
            <div
              className="
                h-11 w-11 sm:h-12 sm:w-12
                rounded-2xl
                bg-linear-to-br from-lime-400 to-emerald-500
                text-white
                flex items-center justify-center
                shadow-[0_12px_28px_rgba(132,204,22,0.28)]
              "
            >
              <Boxes size={18} />
            </div>
          }
          label="Total Item"
          value={formatNumber(datas.total_items)}
        />

        <Card
          icon={
            <div
              className="
                h-11 w-11 sm:h-12 sm:w-12
                rounded-2xl
                bg-linear-to-br from-amber-400 to-red-500
                text-white
                flex items-center justify-center
                shadow-[0_12px_28px_rgba(239,68,68,0.25)]
              "
            >
              <AlertTriangle size={18} />
            </div>
          }
          label="Item Selisih"
          value={formatNumber(datas.variance_items)}
          danger
        />

      </div>

      {/* GROUP LIST */}
        <div className="space-y-5 sm:space-y-6 md:space-y-7">

          {Object.entries(grouped).map(([binName, items]: any) => (
            <motion.div
              key={binName}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="
                  relative overflow-hidden
                  rounded-[26px] sm:rounded-4xl xl:rounded-[36px]

                  bg-linear-to-br
                  from-emerald-400
                  via-emerald-300
                  to-lime-400

                  border border-white/20
                  shadow-[0_20px_60px_rgba(16,185,129,0.28)]

                  p-4 sm:p-5 md:p-6

                  hover:scale-[1.01]
                  hover:shadow-[0_30px_80px_rgba(16,185,129,0.38)]

                  transition-all duration-300
                "
            >
              {/* BACKGROUND EFFECT */}
              <div className="absolute -top-10 -right-10 w-36 h-36 bg-emerald-100/50 rounded-full blur-3xl" />
              <div className="absolute bottom-0 left-0 w-32 h-32 bg-lime-100/40 rounded-full blur-3xl" />

              <div className="relative">

                {/* BIN HEADER */}
                <div
                  className="
                    flex flex-col sm:flex-row sm:items-center sm:justify-between
                    gap-3 mb-5 sm:mb-6
                  "
                >
                  <div className="flex items-center gap-3 min-w-0">

                    <div
                      className="
                        h-11 w-11 rounded-2xl
                        bg-linear-to-br from-emerald-400 to-lime-500
                        text-white
                        flex items-center justify-center
                        shadow-lg shrink-0
                      "
                    >
                      <Boxes size={18} />
                    </div>

                    <div className="min-w-0">
                      <h2
                        className="
                          font-black text-emerald-950
                          text-base sm:text-lg md:text-xl
                          truncate sm:whitespace-normal
                          wrap-break-word
                        "
                      >
                        <span className="font-semibold">Area:</span> {binName}
                      </h2>

                      <div className="text-xs sm:text-sm text-slate-500 font-bold">
                        {formatNumber(items.length)} item
                      </div>
                    </div>

                  </div>
                </div>

                {/* ITEMS */}
                <div className="space-y-4 sm:space-y-5">

                  {items.map((item: any) => {
                    const variance =
                      item.counted_qty -
                      item.system_qty;

                    return (
                      <motion.button
                        whileTap={{ scale: 0.98 }}
                        whileHover={{ y: -4 }}
                        key={item.id}
                        onClick={() =>
                          router.push(
                            `/stock-opname/${id}/items/${item.id}/logs`
                          )
                        }
                        className="
                          w-full text-left
                          rounded-3xl sm:rounded-[28px]
                          bg-white/90 backdrop-blur-xl
                          border border-emerald-100
                          p-4 sm:p-5
                          shadow-[0_12px_30px_rgba(0,0,0,0.08)]
                          hover:shadow-xl
                          transition
                          flex flex-col lg:flex-row lg:items-center lg:justify-between
                          gap-4
                        "
                      >
                        {/* LEFT */}
                        <div className="min-w-0 flex-1">

                          <div
                            className="
                              font-black text-emerald-950
                              text-base sm:text-lg
                              leading-snug
                              break-words
                              [overflow-wrap:anywhere]
                            "
                          >
                            {item.item_name}
                          </div>

                          <div className="text-xs sm:text-sm text-slate-500 mt-1 break-all">
                            SKU: {item.sku}
                          </div>

                          <div
                            className="
                              mt-3 inline-flex items-center gap-2
                              text-xs font-bold text-emerald-700
                              bg-emerald-50 border border-emerald-100
                              px-3 py-1.5 rounded-full
                            "
                          >
                            Klik lihat detail
                          </div>

                        </div>

                        {/* RIGHT */}
                        <div
                          className="
                            grid grid-cols-4 gap-2 sm:gap-3
                            w-full lg:w-auto
                            lg:min-w-[320px]
                          "
                        >

                          {/* SYSTEM */}
                          <div className="rounded-2xl bg-slate-50 border border-slate-100 p-2 text-center">
                            <div className="text-[10px] sm:text-xs text-slate-500">
                              Sistem
                            </div>

                            <div className="font-black text-sm sm:text-base text-emerald-900 mt-1">
                              {formatNumber(item.system_qty)}
                            </div>
                          </div>

                          {/* COUNTED */}
                          <div className="rounded-2xl bg-emerald-50 border border-emerald-100 p-2 text-center">
                            <div className="text-[10px] sm:text-xs text-slate-500">
                              Hitung
                            </div>

                            <div className="font-black text-sm sm:text-base text-emerald-700 mt-1">
                              {formatNumber(item.counted_qty)}
                            </div>
                          </div>

                          {/* VARIANCE */}
                          <div className="rounded-2xl bg-white border border-slate-100 p-2 text-center">
                            <div className="text-[10px] sm:text-xs text-slate-500">
                              Selisih
                            </div>

                            <div
                              className={`font-black text-sm sm:text-base mt-1 ${
                                variance === 0
                                  ? "text-emerald-600"
                                  : variance > 0
                                  ? "text-blue-600"
                                  : "text-red-500"
                              }`}
                            >
                              {formatNumber(variance)}
                            </div>
                          </div>

                          {/* STATUS */}
                          <div className="rounded-2xl bg-white border border-slate-100 p-2 flex items-center justify-center">
                            {variance === 0 ? (
                              <CheckCircle2 className="text-emerald-600" size={18} />
                            ) : (
                              <XCircle className="text-red-500" size={18} />
                            )}
                          </div>

                        </div>
                      </motion.button>
                    );
                  })}

                </div>
              </div>
            </motion.div>
          ))}

        </div>
    </div>
  );
}

/* =========================
   CARD COMPONENT (3D SOFT AGRI)
========================= */
function Card({ icon, label, value, danger }: any) {
  return (
    <div className="relative rounded-3xl bg-white/70 backdrop-blur-xl border border-emerald-100 p-6 shadow-lg hover:shadow-2xl hover:-translate-y-1 transition overflow-hidden">

      <div className="absolute inset-0 bg-linear-to-br from-white/40 to-emerald-50/30 opacity-60" />

      <div className="relative flex items-center gap-2 text-emerald-700 font-bold text-sm">
        {icon}
        {label}
      </div>

      <div
        className={`relative text-3xl font-black mt-4 ${
          danger ? "text-red-500" : "text-emerald-900"
        }`}
      >
        {value}
      </div>

    </div>
  );
}