"use client";

import { useEffect, useState } from "react";
import { motion, useReducedMotion } from "framer-motion";
import type { Product } from "@/data/types";
import { Reveal } from "@/components/motion/Reveal";
import { useToast } from "@/context/toast-context";
import { easeSoft } from "@/lib/motion";

export default function AdminInventoryPage() {
  const [list, setList] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();
  const reduceMotion = useReducedMotion();

  useEffect(() => {
    void fetch("/api/admin/products", { credentials: "include" })
      .then((res) => res.json())
      .then((data: { products?: Product[] }) => setList(data.products ?? []))
      .finally(() => setLoading(false));
  }, []);

  const updateStock = async (id: string, stock: number) => {
    setList((current) =>
      current.map((item) => (item.id === id ? { ...item, stock } : item)),
    );
    const res = await fetch(`/api/admin/products/${id}`, {
      method: "PATCH",
      credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ stock }),
    });
    if (!res.ok) {
      toast("Could not update stock", "error");
      return;
    }
    toast("Stock updated");
  };

  return (
    <div>
      <Reveal>
        <h1 className="text-2xl font-semibold tracking-tight text-foreground">
          Inventory
        </h1>
        <p className="mt-2 text-sm text-muted">
          Adjust stock levels in MariaDB. Items under 25 are flagged low.
        </p>
      </Reveal>

      <div className="mt-6 space-y-3">
        {loading ? (
          <motion.p
            initial={reduceMotion ? false : { opacity: 0 }}
            animate={{ opacity: 1 }}
            className="rounded-2xl border border-dashed border-border px-4 py-10 text-center text-sm text-muted"
          >
            Loading inventory…
          </motion.p>
        ) : list.length === 0 ? (
          <motion.p
            initial={reduceMotion ? false : { opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4, ease: easeSoft }}
            className="rounded-2xl border border-dashed border-border px-4 py-10 text-center text-sm text-muted"
          >
            No products in inventory yet.
          </motion.p>
        ) : (
          list.map((product, index) => (
            <motion.div
              key={product.id}
              initial={
                reduceMotion
                  ? false
                  : { opacity: 0, y: 22, filter: "blur(4px)", scale: 0.985 }
              }
              whileInView={{
                opacity: 1,
                y: 0,
                filter: "blur(0px)",
                scale: 1,
              }}
              viewport={{
                once: false,
                amount: 0.35,
                margin: "-48px 0px -48px 0px",
              }}
              transition={{
                duration: 0.55,
                delay: reduceMotion ? 0 : Math.min((index % 8) * 0.03, 0.21),
                ease: easeSoft,
              }}
              whileHover={
                reduceMotion
                  ? undefined
                  : { y: -2, transition: { duration: 0.28, ease: easeSoft } }
              }
              className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-border bg-card p-4 shadow-sm transition-colors"
            >
              <div className="min-w-0">
                <p className="font-medium text-foreground">{product.name}</p>
                <p className="text-sm text-muted">{product.category}</p>
              </div>
              <div className="flex items-center gap-3">
                {product.stock < 25 ? (
                  <motion.span
                    initial={reduceMotion ? false : { opacity: 0, scale: 0.9 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ duration: 0.35, ease: easeSoft }}
                    className="rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-1 text-xs text-amber-700 dark:text-amber-300"
                  >
                    Low
                  </motion.span>
                ) : null}
                <input
                  type="number"
                  min={0}
                  value={product.stock}
                  onChange={(event) => {
                    void updateStock(product.id, Number(event.target.value));
                  }}
                  className="h-10 w-24 rounded-full border border-border bg-background px-3 text-sm text-foreground outline-none transition-colors focus:border-emerald-500/50"
                />
              </div>
            </motion.div>
          ))
        )}
      </div>
    </div>
  );
}
