"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import Loading from "./components/Loading";
import {
  Boxes,
  Warehouse,
  AlertTriangle,
  ArrowLeftRight,
  Truck,
  CheckCircle,
  Clock,
  ShieldCheck,
} from "lucide-react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

/* ================= TYPES ================= */
type DashboardData = any;

/* ================= FORMAT ================= */
import { formatNumber } from "./components/formatNumber";

/* ================= PAGE ================= */
export default function HomePage() {
  const [data, setData] = useState<DashboardData | null>(null);
  // const { data: session } = useSession();
  const router = useRouter();

useEffect(() => {
  fetch("/api/dashboard", {
    cache: "no-store",
  })
    .then((res) => res.json())
    .then((data) => {
      console.log("DATA:", data);
      setData(data);
    });
}, []);

  if (!data) return <Loading pageName="Dashboard" />;

  return (
    <div className="min-h-screen bg-linear-to-b from-green-50 via-emerald-50 to-lime-50">
      <div className="max-w-7xl mx-auto space-y-8 p-4 md:p-8">

        {/* ================= HERO ================= */}
        <motion.div
          initial={{ opacity: 0, y: -25, scale: 0.98 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          className="relative overflow-hidden rounded-3xl shadow-2xl"
        >
          <div className="absolute inset-0 bg-linear-to-br from-green-300 via-emerald-200 to-lime-300" />
          <div className="absolute inset-0 opacity-10 bg-[url('https://www.transparenttextures.com/patterns/soil.png')]" />
          <div className="absolute inset-0 bg-white/20 backdrop-blur-2xl" />

          <div className="relative p-5 md:p-10">
            <h1 className="text-2xl md:text-5xl font-bold text-green-950">
              🌾 Agriculture Control Tower
            </h1>
            <p className="text-green-900/70 text-sm md:text-base mt-2">
              Real-time inventory, warehouse & logistics monitoring system
            </p>
          </div>
        </motion.div>

        {/* ================= SUMMARY ================= */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">

          <Card title="Total Item" value={formatNumber(data?.summary?.total_items)} icon={Boxes} />
          <Card title="Gudang" value={formatNumber(data.summary.total_locations)} icon={Warehouse} />
          <Card title="Total Stock" value={formatNumber(data.summary.total_stock)} icon={ArrowLeftRight} />
          <Card title="Low Stock" value={formatNumber(data.summary.low_stock)} icon={AlertTriangle} danger />

        </div>

        {/* ================= STO ================= */}
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3 md:gap-4">
          <Sto title="Draft" value={data.sto.draft} icon={Clock} />
          <Sto title="Checked" value={data.sto.checked} icon={ShieldCheck} />
          <Sto title="Approved" value={data.sto.approved} icon={CheckCircle} />
          <Sto title="Transit" value={data.sto.in_transit} icon={Truck} />
          <Sto title="Done" value={data.sto.completed} icon={CheckCircle} />
        </div>

        {/* ================= GRID ================= */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

          <Box title="Stock per Gudang">
            {data.inventory_by_location.map((l: any, i: number) => (
              <Row key={i} label={l.location} value={formatNumber(l.qty)} />
            ))}
          </Box>

          <Box title="Barang Hampir Habis">
            {data.low_stock_items.map((i: any, idx: number) => (
              <Row key={idx} label={i.name} value={formatNumber(i.qty)} danger />
            ))}
          </Box>

        </div>

        {/* ================= MOVEMENT ================= */}
        <Box title="Recent Movement">
          <div className="space-y-3">
            {data.recent_movements.map((m: any) => (
              <motion.div
                key={m.id}
                whileHover={{ y: -2, scale: 1.01 }}
                className="flex justify-between items-center p-4 rounded-2xl
                bg-white/70 border border-white/50 shadow-md"
              >
                <div className="min-w-0">
                  <p className="font-medium text-green-950 text-sm md:text-base truncate">
                    {m.item}
                  </p>
                  <p className="text-xs text-green-700/60 truncate">
                    {m.location}
                  </p>
                </div>

                <span
                  className={`font-semibold text-sm md:text-base whitespace-nowrap ml-4 ${
                    m.type.includes("OUT") ? "text-red-500" : "text-green-600"
                  }`}
                >
                  {m.type} {formatNumber(m.qty)}
                </span>
              </motion.div>
            ))}
          </div>
        </Box>

      </div>
    </div>
  );
}

/* ================= CARD ================= */
function Card({ title, value, icon: Icon, danger }: any) {
  return (
    <motion.div whileHover={{ y: -4, scale: 1.02 }} className="relative">

      <div className="absolute inset-0 translate-y-2 scale-95 bg-green-300/30 blur-2xl rounded-3xl" />

      <div className="relative p-4 md:p-5 rounded-3xl
        bg-linear-to-br from-green-100 via-emerald-50 to-lime-100
        border border-white/60 shadow-xl">

        <div className="flex justify-between items-center gap-3">

          {/* TEXT SAFE AREA */}
          <div className="min-w-0 flex-1">
            <p className="text-xs md:text-sm text-green-700/60 truncate">
              {title}
            </p>

            {/* 🔥 FIX OVERFLOW HERE */}
            <p className={`font-bold text-green-900 leading-tight
              text-[clamp(1.2rem,2.5vw,2rem)] wrap-break-word`}>
              {value}
            </p>
          </div>

          <div className="shrink-0 p-2 md:p-3 rounded-2xl bg-white/70 border border-white/60 shadow-inner">
            <Icon className="w-5 h-5 text-green-700" />
          </div>

        </div>

      </div>
    </motion.div>
  );
}

/* ================= STO ================= */
function Sto({ title, value, icon: Icon }: any) {
  return (
    <div className="relative">
      <div className="absolute inset-0 bg-green-400/10 blur-2xl rounded-2xl" />

      <div className="relative p-3 md:p-4 rounded-2xl
        bg-linear-to-br from-green-600 via-emerald-500 to-lime-400
        text-white shadow-lg">

        <div className="flex justify-between items-center gap-2">
          <div className="min-w-0">
            <p className="text-xs opacity-80 truncate">{title}</p>
            <p className="text-lg md:text-xl font-bold wrap-break-word">
              {value}
            </p>
          </div>
          <Icon className="w-5 h-5 opacity-90 shrink-0" />
        </div>

      </div>
    </div>
  );
}

/* ================= BOX ================= */
function Box({ title, children }: any) {
  return (
    <div className="relative">

      <div className="absolute inset-0 translate-y-3 scale-95 bg-green-200/40 blur-3xl rounded-3xl" />

      <div className="relative p-4 md:p-6 rounded-3xl
        bg-linear-to-br from-green-100 via-emerald-50 to-lime-100
        border border-white/60 shadow-xl">

        <h3 className="font-semibold text-green-900 mb-3">
          {title}
        </h3>

        <div className="space-y-2">
          {children}
        </div>

      </div>
    </div>
  );
}

/* ================= ROW ================= */
function Row({ label, value, danger }: any) {
  return (
    <div className="flex justify-between items-center p-3 rounded-xl
      bg-white/70 border border-white/50 shadow-sm">

      <span className="text-green-900/80 text-sm truncate pr-3">
        {label}
      </span>

      <span className={`font-semibold text-sm whitespace-nowrap ${
        danger ? "text-red-500" : "text-green-700"
      }`}>
        {value}
      </span>

    </div>
  );
}