"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import Link from "next/link";
import {
  Plus,
  Eye,
  Users,
  Search,
  Sparkles,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import Image from "next/image";
import { Select3D } from "../components/Select3D";

import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

/* =====================================================
TYPES
===================================================== */
type User = {
  id: number;
  google_id: string | null;
  name: string;
  email: string;
  avatar: string | null;
  role: "ADMIN" | "CHECKER" | "SUPERVISOR" | "OPERATOR";
  is_active: boolean;
  created_at: string;
  last_login_at: string | null;
};

export default function UsersPage() {
  const { data: session, status } = useSession();
  const currentUser = session?.user as any;
  const router = useRouter();

  const [data, setData] = useState<User[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const [search, setSearch] = useState("");
  const [role, setRole] = useState("ALL");

  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);

  const fetchData = async () => {
    setLoading(true);

    const res = await fetch(
      `/api/users?search=${search}&role=${role}&page=${page}&limit=${limit}`
    );

    const json = await res.json();

    setData(json.users || []);
    setTotal(json.total || 0);
    setLoading(false);
  };

  useEffect(() => {
      // 1. tunggu session selesai load
    if (status === "loading") return;

    if (!session) {
      router.replace("/login");
      return;
    }

    //   // 3. kalau bukan admin → kick
    // if (currentUser?.role && currentUser.role !== "ADMIN") {
    //   router.replace("/users");
    //   return;
    // }
    const allowedRoles = ["ADMIN"];

    if (!allowedRoles.includes(currentUser?.role)) {
      router.replace("/");
      return;
    }

    fetchData();
  }, [search, role, page, limit, status, currentUser,session]);

  const totalPage = Math.ceil(total / limit);
  // optional safety (biar tidak flash UI)
  if (!session) return null;

  return (
    <div className="space-y-6 p-4">
      {/* =====================================================
      HEADER
      ===================================================== */}
      <motion.div
        initial={{ opacity: 0, y: 24, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        className="relative rounded-[34px] overflow-hidden"
      >
        {/* background layers */}
        <div className="absolute inset-0 bg-linear-to-br from-green-400 via-emerald-300 to-lime-300" />
        <div className="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/diamond-upholstery.png')] opacity-[0.06]" />
        <div className="absolute inset-0 bg-white/20 backdrop-blur-3xl" />

        {/* glows */}
        <div className="absolute -top-24 -left-12 w-72 h-72 bg-green-500/35 blur-[130px]" />
        <div className="absolute bottom-0 right-0 w-80 h-80 bg-lime-400/30 blur-[150px]" />

        {/* depth */}
        <div className="absolute inset-0 translate-y-5 bg-black/10 blur-3xl scale-[0.97]" />

        <div className="relative z-10 p-6 md:p-7 rounded-[34px] border border-white/40 bg-white/45 backdrop-blur-3xl shadow-[0_30px_90px_rgba(0,0,0,0.18)]">
          <div className="flex flex-col xl:flex-row xl:items-center xl:justify-between gap-5">
            {/* title */}
            <div>
              <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/65 border border-white/60 shadow text-xs font-semibold text-green-800 mb-3">
                <Sparkles className="w-3.5 h-3.5" />
                Agriculture Control Panel
              </div>

              <h1 className="text-3xl md:text-4xl font-black text-green-950 tracking-tight flex items-center gap-3">
                <Users className="w-8 h-8" />
                User Management
              </h1>

              <p className="text-sm text-green-900/70 mt-2">
                Total user terdaftar:{" "}
                <b>{new Intl.NumberFormat("id-ID").format(total)}</b>
              </p>
            </div>

            {/* filters */}
            <div className="flex flex-wrap gap-3 items-center">
              <Input
                value={search}
                onChange={(v: string) => {
                  setPage(1);
                  setSearch(v);
                }}
                placeholder="Cari user..."
              />

              <Select3D
                value={role}
                onChange={(v) => {
                  setPage(1);
                  setRole(v);
                }}
                options={[
                  { label: "Semua Role", value: "ALL" },
                  { label: "ADMIN", value: "ADMIN" },
                  { label: "CHECKER", value: "CHECKER" },
                  { label: "SUPERVISOR", value: "SUPERVISOR" },
                  { label: "OPERATOR", value: "OPERATOR" },
                ]}
                placeholder="Role"
              />

              <Select3D
                value={limit}
                onChange={(v) => {
                  setPage(1);
                  setLimit(Number(v));
                }}
                options={[
                  { label: "10 Rows", value: 10 },
                  { label: "20 Rows", value: 20 },
                  { label: "50 Rows", value: 50 },
                  { label: "100 Rows", value: 100 },
                ]}
                placeholder="Limit"
              />

              {/* <Link
                href="/users/tambah"
                className="group relative px-5 py-3 rounded-2xl text-sm font-bold text-white overflow-hidden shadow-[0_18px_35px_rgba(34,197,94,0.35)] hover:scale-105 active:scale-95 transition"
              >
                <span className="absolute inset-0 bg-linear-to-r from-green-600 via-emerald-500 to-lime-500" />
                <span className="absolute inset-0 opacity-0 group-hover:opacity-100 transition bg-white/10" />
                <span className="relative flex items-center gap-2">
                  <Plus size={16} />
                  Tambah User
                </span>
              </Link> */}
            </div>
          </div>
        </div>
      </motion.div>

      {/* =====================================================
      TABLE
      ===================================================== */}
      {loading ? (
        <div className="rounded-3xl bg-white/70 border border-white shadow-xl p-8 text-green-700 animate-pulse">
          🌿 Loading users...
        </div>
      ) : (
        <UsersTable data={data} page={page} limit={limit} />
      )}

      {/* =====================================================
      PAGINATION
      ===================================================== */}
      <div className="rounded-3xl border border-white/50 bg-white/70 backdrop-blur-2xl shadow-xl p-4 flex items-center justify-between">
        <button
          disabled={page === 1}
          onClick={() => setPage(page - 1)}
          className="px-4 py-2 rounded-2xl bg-white shadow hover:scale-105 active:scale-95 transition disabled:opacity-40 flex items-center gap-2"
        >
          <ChevronLeft size={16} />
          Prev
        </button>

        <div className="text-sm font-semibold text-green-900">
          Page {page} / {totalPage || 1}
        </div>

        <button
          disabled={page >= totalPage}
          onClick={() => setPage(page + 1)}
          className="px-4 py-2 rounded-2xl bg-white shadow hover:scale-105 active:scale-95 transition disabled:opacity-40 flex items-center gap-2"
        >
          Next
          <ChevronRight size={16} />
        </button>
      </div>
    </div>
  );
}

/* =====================================================
TABLE
===================================================== */
function UsersTable({
  data,
  page,
  limit,
}: {
  data: User[];
  page: number;
  limit: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 18 }}
      animate={{ opacity: 1, y: 0 }}
      className="relative rounded-[30px] p-px bg-linear-to-br from-white/70 to-green-100/40"
    >
      {/* shadow depth */}
      <div className="absolute inset-0 translate-y-5 bg-green-300/20 blur-3xl rounded-[30px]" />

      <div className="relative rounded-[30px] overflow-hidden border border-white/50 bg-white/82 backdrop-blur-3xl shadow-[0_30px_80px_rgba(0,0,0,0.12)]">
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-275">
            <thead className="bg-linear-to-r from-green-50 via-emerald-50 to-lime-50 text-gray-600">
              <tr>
                <th className="p-4 text-left">No</th>
                <th className="p-4 text-left">User</th>
                <th className="p-4 text-left">Email</th>
                <th className="p-4 text-center">Role</th>
                <th className="p-4 text-center">Status</th>
                <th className="p-4 text-center">Last Login</th>
                <th className="p-4 text-center">Action</th>
              </tr>
            </thead>

            <tbody>
              {data.length === 0 ? (
                <tr>
                  <td colSpan={7} className="p-10 text-center text-gray-400">
                    Tidak ada data user
                  </td>
                </tr>
              ) : (
                data.map((user, i) => {
                  const no = (page - 1) * limit + i + 1;

                  return (
                    <tr
                      key={user.id}
                      className="border-t border-green-50 hover:bg-green-50/60 transition"
                    >
                      <td className="p-4 font-semibold text-gray-500">{no}</td>

                      <td className="p-4">
                        <div className="flex items-center gap-3">
                          <div className="relative">
                            <div className="absolute inset-0 rounded-full bg-green-400/25 blur-xl scale-125" />

                            <Image
                              src={
                                user.avatar || "/images/default-user.png"
                              }
                              alt={user.name}
                              width={44}
                              height={44}
                              className="relative rounded-2xl object-cover border border-white shadow-lg"
                            />
                          </div>

                          <div>
                            <div className="font-bold text-green-950">
                              {user.name}
                            </div>
                            <div className="text-xs text-gray-500">
                              ID #{user.id}
                            </div>
                          </div>
                        </div>
                      </td>

                      <td className="p-4 text-gray-700">{user.email}</td>

                      <td className="p-4 text-center">
                        <RoleBadge role={user.role} />
                      </td>

                      <td className="p-4 text-center">
                        <span
                          className={`px-3 py-1 rounded-full text-xs font-bold shadow-sm ${
                            user.is_active
                              ? "bg-green-100 text-green-700"
                              : "bg-red-100 text-red-700"
                          }`}
                        >
                          {user.is_active ? "Active" : "Inactive"}
                        </span>
                      </td>

                      <td className="p-4 text-center text-xs text-gray-500">
                        {user.last_login_at
                          // ? new Date(user.last_login_at).toLocaleString("id-ID")
                          ? new Date(user.last_login_at).toLocaleString("id-ID", {timeZone: "Asia/Jakarta",})
                          : "-"}
                      </td>

                      <td className="p-4 text-center">
                        <Link
                          href={`/users/${user.id}`}
                          className="inline-flex items-center gap-2 px-4 py-2 rounded-2xl bg-white border border-green-200 shadow hover:shadow-lg hover:-translate-y-0.5 transition text-xs font-semibold text-green-800"
                        >
                          <Eye size={14} />
                          Detail
                        </Link>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </motion.div>
  );
}

/* =====================================================
ROLE BADGE
===================================================== */
function RoleBadge({ role }: { role: string }) {
  const colors: any = {
    ADMIN:
      "bg-linear-to-r from-red-100 to-rose-100 text-red-700 border border-red-200",
    CHECKER:
      "bg-linear-to-r from-blue-100 to-cyan-100 text-blue-700 border border-blue-200",
    SUPERVISOR:
      "bg-linear-to-r from-purple-100 to-fuchsia-100 text-purple-700 border border-purple-200",
    OPERATOR:
      "bg-linear-to-r from-green-100 to-emerald-100 text-green-700 border border-green-200",
  };

  return (
    <span
      className={`px-3 py-1 rounded-full text-xs font-bold shadow-sm ${colors[role]}`}
    >
      {role}
    </span>
  );
}

/* =====================================================
INPUT 3D
===================================================== */
function Input({ value, onChange, placeholder }: any) {
  return (
    <div className="relative group">
      <div className="absolute inset-0 translate-y-1 rounded-2xl bg-green-300/20 blur-lg" />

      <div className="relative flex items-center gap-2 px-4 py-3 rounded-2xl bg-white/80 border border-white shadow-lg">
        <Search className="w-4 h-4 text-green-600" />

        <input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          className="bg-transparent outline-none text-sm w-44 placeholder:text-gray-400"
        />
      </div>
    </div>
  );
}