"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { useRouter } from "next/navigation";
import { Save, ArrowLeft } from "lucide-react";
import Link from "next/link";
import { useSession } from "next-auth/react";
import Loading from "../../components/Loading";

export default function CreateCategoryPage() {
  const { data: session, status } = useSession();
  const router = useRouter();

  const currentUser = session?.user as any;

  const [form, setForm] = useState({
    name: "",
    description: "",
    is_active: true,
  });

  const [loading, setLoading] = useState(false);

  const allowedRoles = ["ADMIN"];

  // ===============================
  // FIX: GUARD SAFE REDIRECT
  // ===============================
  const isLoading = status === "loading";
  const isAuthenticated = status === "authenticated";
  const isUnauthorized = status === "unauthenticated";

  const isNotAdmin =
    isAuthenticated &&
    currentUser &&
    !allowedRoles.includes(currentUser.role);

  useEffect(() => {
    if (isUnauthorized || isNotAdmin) {
      router.replace("/categories");
    }
  }, [isUnauthorized, isNotAdmin, router]);

  // ===============================
  // FIX: BLOCK RENDER ONLY (NO UI CHANGE)
  // ===============================
  if (isLoading) return <Loading />;

  if (isUnauthorized || isNotAdmin) {
    return null;
  }

  // ===============================
  // HANDLE SUBMIT (TIDAK DIUBAH FLOW)
  // ===============================
  const handleSubmit = async () => {
    if (!form.name) {
      alert("Nama kategori wajib diisi");
      return;
    }

    setLoading(true);

    const res = await fetch("/api/categories", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(form),
    });

    const json = await res.json();

    setLoading(false);

    if (!res.ok) {
      alert(json.message || "Gagal");
      return;
    }

    router.push("/categories");
  };

  // ===============================
  // UI (TIDAK DIUBAH SAMA SEKALI)
  // ===============================
  return (
    <div className="p-4 space-y-6">

      {/* HEADER */}
      <motion.div
        initial={{ opacity: 0, y: 30 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative rounded-[28px] overflow-hidden"
      >
        <div className="absolute inset-0 bg-linear-to-br from-green-300 via-emerald-200 to-lime-200" />
        <div className="absolute inset-0 bg-white/30 backdrop-blur-2xl" />

        <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]">

          <div className="flex justify-between items-center">

            <div>
              <h1 className="text-3xl font-bold text-green-900">
                🌱 Tambah Kategori
              </h1>
              <p className="text-sm text-green-800/70">
                Buat kategori baru untuk item
              </p>
            </div>

            <Link
              href="/categories"
              className="flex items-center gap-2 px-4 py-2 rounded-xl
              bg-white/80 border border-green-200
              shadow hover:scale-105 transition"
            >
              <ArrowLeft size={16} />
              Kembali
            </Link>

          </div>
        </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 bg-white/85 backdrop-blur-2xl
        border border-white/40 rounded-3xl p-6
        shadow-[0_20px_60px_rgba(0,0,0,0.15)] space-y-5">

          {/* NAME */}
          <Input
            label="Nama Kategori"
            value={form.name}
            onChange={(v: string) =>
              setForm({ ...form, name: v })
            }
          />

          {/* DESCRIPTION */}
          <Textarea
            label="Deskripsi"
            value={form.description}
            onChange={(v: string) =>
              setForm({ ...form, description: v })
            }
          />

          {/* STATUS */}
          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              checked={form.is_active}
              onChange={(e) =>
                setForm({ ...form, is_active: e.target.checked })
              }
              className="w-4 h-4"
            />
            <span className="text-sm text-green-800">
              Aktifkan kategori
            </span>
          </div>

          {/* ACTION */}
          <div className="flex justify-end">
            <button
              onClick={handleSubmit}
              disabled={loading}
              className="flex items-center gap-2 px-5 py-2.5 rounded-xl
              bg-linear-to-r from-green-600 to-emerald-500
              text-white text-sm font-semibold
              shadow-lg hover:scale-105 active:scale-95 transition
              disabled:opacity-50"
            >
              <Save size={16} />
              {loading ? "Menyimpan..." : "Simpan"}
            </button>
          </div>

        </div>
      </motion.div>

    </div>
  );
}

/* ================= INPUT ================= */
function Input({ label, value, onChange }: any) {
  return (
    <div className="space-y-1">
      <label className="text-sm font-medium text-green-900">
        {label}
      </label>

      <div className="relative">
        <div className="absolute inset-0 translate-y-1 bg-green-300/20 blur-lg rounded-xl" />

        <input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="relative w-full px-4 py-2 rounded-xl
          bg-white/80 backdrop-blur-xl
          border border-green-200
          text-sm shadow-md
          focus:ring-2 focus:ring-green-400 outline-none"
        />
      </div>
    </div>
  );
}

/* ================= TEXTAREA ================= */
function Textarea({ label, value, onChange }: any) {
  return (
    <div className="space-y-1">
      <label className="text-sm font-medium text-green-900">
        {label}
      </label>

      <div className="relative">
        <div className="absolute inset-0 translate-y-1 bg-green-300/20 blur-lg rounded-xl" />

        <textarea
          value={value}
          onChange={(e) => onChange(e.target.value)}
          rows={4}
          className="relative w-full px-4 py-2 rounded-xl
          bg-white/80 backdrop-blur-xl
          border border-green-200
          text-sm shadow-md
          focus:ring-2 focus:ring-green-400 outline-none"
        />
      </div>
    </div>
  );
}