"use client";

import { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import { motion } from "framer-motion";
import Link from "next/link";
import { useSession } from "next-auth/react";
import Loading from "../../components/Loading";

/* ================= TYPES ================= */
type Category = {
  id: number;
  name: string;
  description: string;
  is_active: boolean;
};

export default function EditCategoryPage() {

  const params = useParams();

  const { data: session, status } = useSession();
  const router = useRouter();
  const currentUser = session?.user as any;

  const id = params.id;

  const [form, setForm] = useState({
    name: "",
    description: "",
    is_active: true,
  });

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  /* ================= LOAD DATA ================= */
  useEffect(() => {

    // 1. tunggu session selesai load
    if (status === "loading") return;

    // 2. kalau belum login
    if (status === "unauthenticated") {
      router.replace("/login");
      return;
    }
    const allowedRoles = ["ADMIN"];

    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/");
      return;
    }

    const fetchData = async () => {
      const res = await fetch(`/api/categories/${id}`);
      const json = await res.json();

      if (json.category) {
        setForm({
          name: json.category.name,
          description: json.category.description || "",
          is_active: json.category.is_active,
        });
      }

      setLoading(false);
    };

    fetchData();
  }, [id, status]);

  /* ================= SUBMIT ================= */
  const handleSubmit = async () => {
    setSaving(true);

    await fetch(`/api/categories/${id}`, {
      method: "PUT",
      body: JSON.stringify(form),
    });

    router.push("/categories");
  };

  if (loading) {
    return <Loading pageName="Categories"/>;
  }
  // optional safety (biar tidak flash UI)
  if (!session) return null;
  return (
    <div className="p-4 space-y-6">

      {/* ================= HEADER ================= */}
      <motion.div
        initial={{ opacity: 0, y: 30, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        className="relative rounded-[28px] overflow-hidden"
      >
        {/* BG */}
        <div className="absolute inset-0 bg-linear-to-br from-green-300 via-emerald-200 to-lime-200" />
        <div className="absolute inset-0 opacity-[0.08] bg-[url('https://www.transparenttextures.com/patterns/soil.png')]" />

        {/* GLOW */}
        <div className="absolute -top-20 -left-10 w-72 h-72 bg-green-400/30 blur-[120px]" />
        <div className="absolute bottom-0 right-0 w-72 h-72 bg-lime-300/30 blur-[140px]" />

        {/* GLASS */}
        <div className="absolute inset-0 bg-white/30 backdrop-blur-2xl" />

        {/* CARD */}
        <div className="relative z-10 p-6
        border border-white/40
        bg-white/60 backdrop-blur-2xl
        shadow-[0_25px_80px_rgba(0,0,0,0.25)]
        rounded-[28px]">

          <h1 className="text-3xl font-bold text-green-900">
            ✏️ Edit Category
          </h1>

          <p className="text-sm text-green-800/70">
            Update data kategori
          </p>
        </div>
      </motion.div>

      {/* ================= FORM ================= */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative rounded-3xl p-[1px]
        bg-gradient-to-br from-green-200/40 to-transparent"
      >
        <div className="absolute inset-0 translate-y-6 bg-green-300/20 blur-3xl rounded-3xl" />

        <div className="relative p-6 space-y-4
        rounded-3xl bg-white/85 backdrop-blur-2xl
        border border-white/40 shadow-xl">

          {/* NAME */}
          <div className="space-y-1">
            <label className="text-sm text-green-800 font-medium">
              Nama Kategori
            </label>
            <input
              value={form.name}
              onChange={(e) =>
                setForm({ ...form, name: e.target.value })
              }
              className="w-full px-4 py-2 rounded-xl
              bg-white/80 border border-green-200
              focus:ring-2 focus:ring-green-400 outline-none"
            />
          </div>

          {/* DESC */}
          <div className="space-y-1">
            <label className="text-sm text-green-800 font-medium">
              Deskripsi
            </label>
            <textarea
              value={form.description}
              onChange={(e) =>
                setForm({ ...form, description: e.target.value })
              }
              className="w-full px-4 py-2 rounded-xl
              bg-white/80 border border-green-200
              focus:ring-2 focus:ring-green-400 outline-none"
            />
          </div>

          {/* STATUS */}
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={form.is_active}
              onChange={(e) =>
                setForm({ ...form, is_active: e.target.checked })
              }
            />
            <span className="text-sm text-green-800">
              Aktif
            </span>
          </div>

          {/* ACTION */}
          <div className="flex gap-2 pt-4">

            <button
              onClick={handleSubmit}
              disabled={saving}
              className="px-4 py-2 rounded-xl
              bg-linear-to-r from-green-600 to-emerald-500
              text-white font-medium shadow-md
              hover:scale-105 active:scale-95 transition"
            >
              {saving ? "Menyimpan..." : "Simpan"}
            </button>

            <Link
              href="/categories"
              className="px-4 py-2 rounded-xl
              bg-gray-100 text-gray-600"
            >
              Batal
            </Link>

          </div>

        </div>
      </motion.div>
    </div>
  );
}