'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Users } from 'lucide-react';

import {
  useAdminUsers,
  useSuspendUser,
  useActivateUser,
  useUpdateUserRole,
} from '@/hooks/useAdmin';
import { Pagination } from '@/components/ui/pagination';
import { User } from '@/types';
import { SearchBar } from '@/components/ui/search-bar';
import { StatusFilter } from './components/StatusFilter';
import { SuspendDialog } from './components/SuspendDialog';
import { AssignRoleDialog } from './components/AssignRoleDialog';
import { UserRow } from './components/UserRow';

import Image from 'next/image';
export default function AdminUsersPage() {
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  // State untuk Suspend Modal
  const [suspendTarget, setSuspendTarget] = useState<User | null>(null);

  // State untuk Assign Role Modal
  const [assignRoleTarget, setAssignRoleTarget] = useState<{
    user: User;
    role: 'agen' | 'user';
  } | null>(null);

  const suspendMutation = useSuspendUser();
  const activateMutation = useActivateUser();
  const updateRoleMutation = useUpdateUserRole();

  const { data, isLoading } = useAdminUsers({
    page,
    per_page: 10,
    search: search || undefined,
    status: statusFilter || undefined,
  });

  const users = data?.data ?? [];
  const meta = data?.meta;

  const handleSearchChange = (val: string) => {
    setSearch(val);
    setPage(1);
  };

  const handleStatusFilter = (val: string) => {
    setStatusFilter(val);
    setPage(1);
  };

  const handleActivate = (id: string) => {
    activateMutation.mutate(id);
  };

  const handleSuspendConfirm = (reason: string) => {
    if (!suspendTarget) return;
    suspendMutation.mutate(
      { id: suspendTarget.id, reason },
      { onSuccess: () => setSuspendTarget(null) }
    );
  };

  const handleAssignRoleClick = (user: User, role: 'agen' | 'user') => {
    setAssignRoleTarget({ user, role });
  };

  const handleAssignRoleConfirm = () => {
    if (!assignRoleTarget) return;
    updateRoleMutation.mutate(
      { id: assignRoleTarget.user.id, role: assignRoleTarget.role },
      { onSuccess: () => setAssignRoleTarget(null) }
    );
  };

  const isUpdating =
    suspendMutation.isPending ||
    activateMutation.isPending ||
    updateRoleMutation.isPending;

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex items-end justify-between gap-4 flex-wrap relative"
      >
        <div>
          <h2 className="text-3xl font-black text-gray-900 tracking-tight leading-none mb-2">
            Manajemen <span className="text-yellow-600">Pengguna</span>
          </h2>
          <p className="text-sm font-medium text-gray-500">
            Kelola semua akun dan hak akses pengguna di sistem.
          </p>
        </div>
        {/* Mascot decoration */}
        <div className="absolute right-10 -top-8 w-24 md:w-32 opacity-20 pointer-events-none hidden sm:block z-0">
          <Image
            src="/mascots/capt-yodi-chill-pose.avif"
            alt="Captain Yodi Mascot"
            className="w-full h-auto object-contain"
            width={500}
            height={500}
          />
        </div>
      </motion.div>

      <motion.div
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.05 }}
        className="flex flex-col sm:flex-row gap-3"
      >
        <SearchBar value={search} onChange={handleSearchChange} />
        <StatusFilter value={statusFilter} onChange={handleStatusFilter} />
      </motion.div>

      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
        className="relative bg-white/60 backdrop-blur-xl border border-gray-200 rounded-2xl shadow-sm overflow-hidden"
      >
        <div className="flex items-center justify-between px-6 py-5 border-b border-gray-200 bg-white/40">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-yellow-50 rounded-lg border border-yellow-200">
              <Users className="w-4 h-4 text-yellow-600" />
            </div>
            <span className="text-xs font-bold text-gray-400 tracking-wide">
              {isLoading
                ? 'Memuat data...'
                : `${meta?.total ?? 0} Pengguna Ditemukan`}
            </span>
          </div>
          {meta && (
            <span className="text-[10px] font-bold text-gray-500 uppercase tracking-widest px-3 py-1 rounded-full bg-white/60 border border-gray-200 shadow-sm">
              Halaman {meta.current_page} / {meta.last_page}
            </span>
          )}
        </div>

        {isLoading && (
          <div className="divide-y divide-gray-100">
            {Array.from({ length: 5 }).map((_, i) => (
              <div
                key={i}
                className="flex items-center gap-4 px-6 py-5 animate-pulse"
              >
                <div className="w-10 h-10 rounded-full bg-gray-200 shrink-0" />
                <div className="flex-1 space-y-2">
                  <div className="h-3 rounded bg-gray-200 w-1/3" />
                  <div className="h-2 rounded bg-gray-200 w-1/4" />
                </div>
                <div className="h-6 rounded-md bg-gray-200 w-16" />
                <div className="h-6 rounded-md bg-gray-200 w-14" />
                <div className="h-6 rounded-full bg-gray-200 w-20" />
                <div className="h-4 rounded bg-gray-200 w-16" />
                <div className="w-8 h-8 rounded-lg bg-gray-200" />
              </div>
            ))}
          </div>
        )}

        {!isLoading && (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200 bg-white/20">
                  {[
                    'Pengguna',
                    'Tipe',
                    'Role',
                    'Status',
                    'Terdaftar',
                    'Aksi',
                  ].map((h) => (
                    <th
                      key={h}
                      className="text-left px-6 py-4 text-[10px] font-bold text-gray-500 uppercase tracking-widest whitespace-nowrap"
                    >
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {users.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-24 text-center">
                      <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-50 border border-gray-200 mb-4 shadow-sm">
                        <Users className="w-8 h-8 text-gray-400" />
                      </div>
                      <p className="text-sm font-bold text-gray-500 tracking-wide">
                        {search
                          ? 'Pencarian tidak menemukan hasil'
                          : 'Belum ada data pengguna'}
                      </p>
                    </td>
                  </tr>
                ) : (
                  users.map((user, i) => (
                    <UserRow
                      key={user.id}
                      user={user}
                      index={i}
                      onActivate={handleActivate}
                      onSuspendClick={setSuspendTarget}
                      onAssignRole={handleAssignRoleClick}
                      isUpdating={isUpdating}
                    />
                  ))
                )}
              </tbody>
            </table>
          </div>
        )}

        {meta && meta.last_page > 1 && (
          <div className="px-6 py-4 border-t border-gray-200 bg-white/20">
            <Pagination
              currentPage={meta.current_page}
              lastPage={meta.last_page}
              total={meta.total}
              perPage={meta.per_page}
              from={meta.from}
              to={meta.to}
              onPageChange={setPage}
            />
          </div>
        )}
      </motion.div>

      {/* Modal Suspend Dialog */}
      <AnimatePresence>
        {suspendTarget && (
          <SuspendDialog
            user={suspendTarget}
            onConfirm={handleSuspendConfirm}
            onCancel={() => setSuspendTarget(null)}
            isPending={suspendMutation.isPending}
          />
        )}
      </AnimatePresence>

      {/* Modal Assign Role Dialog */}
      <AnimatePresence>
        {assignRoleTarget && (
          <AssignRoleDialog
            user={assignRoleTarget.user}
            targetRole={assignRoleTarget.role}
            onConfirm={handleAssignRoleConfirm}
            onCancel={() => setAssignRoleTarget(null)}
            isPending={updateRoleMutation.isPending}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
