import React, { useState } from 'react';
import { Head, router, usePage } from '@inertiajs/react';
import AdminLayout from '@/components/layouts/admin-layout';
import PopupCreateUser from '@/components/admin/users/popupCreateUser';
import PopupDetailUser from '@/components/admin/users/popupDetailUser';
import SuccessAlert, { FailedAlert } from '@/components/micro/alert';
import { HiPlus, HiUsers, HiSearch, HiFilter, HiRefresh, HiEye, HiCheckCircle, HiXCircle } from 'react-icons/hi';

interface UserItem {
  id_user: string;
  username: string;
  role: string;
  departments?: string[] | null;
  departments_head?: string[] | null;
  is_active: boolean;
  last_login: string | null;
  created_at: string;
}

interface PaginationProps<T> {
  data: T[];
  current_page: number;
  last_page: number;
  total: number;
  from: number;
  to: number;
  links: Array<{ url: string | null; label: string; active: boolean }>;
}

interface PageProps {
  users?: PaginationProps<UserItem>;
  filters?: { search?: string; role?: string; department?: string };
}

const DEPARTMENTS_LIST = ['Kepegawaian', 'Keuangan', 'Warehouse', 'Supplier', 'Operasional'];

export default function UsersManagement() {
  const pageProps = usePage<any>().props as PageProps;
  
  // Safe Fallback
  const users = pageProps?.users || { data: [], current_page: 1, last_page: 1, total: 0, from: 0, to: 0, links: [] };
  const filters = pageProps?.filters || {};

  // Modal State
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [selectedUser, setSelectedUser] = useState<UserItem | null>(null);

  // Toast / Alert State
  const [isSuccessAlert, setIsSuccessAlert] = useState(false);
  const [successMsg, setSuccessMsg] = useState('');
  const [isErrorAlert, setIsErrorAlert] = useState(false);
  const [errorMsg, setErrorMsg] = useState('');

  // Local Filter State
  const [search, setSearch] = useState(filters.search || '');
  const [role, setRole] = useState(filters.role || '');
  const [department, setDepartment] = useState(filters.department || '');

  const handleFilter = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    router.get(
      '/admin/users',
      { search, role, department },
      { preserveState: true, replace: true }
    );
  };

  const handleReset = () => {
    setSearch('');
    setRole('');
    setDepartment('');
    router.get('/admin/users', {}, { preserveState: true, replace: true });
  };

  const triggerSuccess = (msg: string) => {
    setSuccessMsg(msg);
    setIsSuccessAlert(true);
  };

  const triggerError = (msg?: string) => {
    setErrorMsg(msg || 'Terjadi kesalahan saat memproses data.');
    setIsErrorAlert(true);
  };

  return (
    <div className="space-y-4">
      <Head>
        <title>Kelola Pengguna</title>
        <meta name="description" content="Kelola seluruh pengguna dan akun sistem." />
      </Head>

      {/* Header Action Banner */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 p-6 bg-gray-900 border border-gray-800 rounded-xs shadow-xs">
        <div className="flex items-center gap-3">
          <div className="p-3 bg-blue-600/10 text-blue-400 rounded-xl border border-blue-500/20">
            <HiUsers className="w-6 h-6" />
          </div>
          <div>
            <h1 className="text-xl font-bold text-gray-100">Manajemen Pengguna</h1>
            <p className="text-xs text-gray-400">Kelola daftar akun staf, hak akses role, dan akses modul departemen.</p>
          </div>
        </div>

        <button
          type="button"
          onClick={() => setIsCreateOpen(true)}
          className="flex items-center justify-center gap-2 px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs rounded-xl shadow-xs transition duration-200 cursor-pointer"
        >
          <HiPlus className="w-4 h-4" />
          <span>Tambah User Baru</span>
        </button>
      </div>

      {/* Filter Bar */}
      <div className="p-5 bg-gray-900 border border-gray-800 rounded-xs space-y-4 shadow-xs">
        <form onSubmit={handleFilter} className="grid grid-cols-1 sm:grid-cols-3 gap-3">
          {/* Search Input */}
          <div className="relative">
            <HiSearch className="w-4 h-4 absolute left-3.5 top-3 text-gray-500" />
            <input
              type="text"
              placeholder="Cari username..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-9 pr-4 py-2 bg-gray-950 border border-gray-800 rounded-xl text-xs text-gray-200 placeholder-gray-500 focus:border-gray-700 focus:outline-none transition"
            />
          </div>

          {/* Role Filter */}
          <select
            value={role}
            onChange={(e) => setRole(e.target.value)}
            className="w-full px-3 py-2 bg-gray-950 border border-gray-800 rounded-xl text-xs text-gray-300 focus:border-gray-700 focus:outline-none transition cursor-pointer"
          >
            <option value="">Semua Role</option>
            <option value="admin">Admin</option>
            <option value="user">User / Staf</option>
            <option value="unknown">Belum terverifikasi</option>
          </select>

          {/* Department Filter */}
          <select
            value={department}
            onChange={(e) => setDepartment(e.target.value)}
            className="w-full px-3 py-2 bg-gray-950 border border-gray-800 rounded-xl text-xs text-gray-300 focus:border-gray-700 focus:outline-none transition cursor-pointer"
          >
            <option value="">Semua Departemen</option>
            {DEPARTMENTS_LIST.map((dept) => (
              <option key={dept} value={dept}>{dept}</option>
            ))}
          </select>
        </form>

        <div className="flex items-center justify-between pt-2 border-t border-gray-800/60">
          <p className="text-xs text-gray-400">
            Total Pengguna: <span className="font-bold text-gray-200">{users?.total || 0}</span>
          </p>

          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={handleReset}
              className="px-3 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 font-semibold text-xs rounded-xs flex items-center gap-1.5 transition cursor-pointer"
            >
              <HiRefresh className="w-3.5 h-3.5" />
              <span>Reset</span>
            </button>

            <button
              type="button"
              onClick={() => handleFilter()}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs rounded-xs flex items-center gap-1.5 transition cursor-pointer shadow-xs"
            >
              <HiFilter className="w-3.5 h-3.5" />
              <span>Terapkan Filter</span>
            </button>
          </div>
        </div>
      </div>

      {/* User Data Table */}
      <div className="bg-gray-900 border border-gray-800 rounded-xs overflow-hidden shadow-xs">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="bg-gray-950/80 text-gray-400 uppercase font-semibold border-b border-gray-800">
              <tr>
                <th className="px-4 py-3.5">Username</th>
                <th className="px-4 py-3.5">Role</th>
                <th className="px-4 py-3.5">Akses Departemen</th>
                <th className="px-4 py-3.5">Status</th>
                <th className="px-4 py-3.5 text-center">Aksi</th>
              </tr>
            </thead>

            <tbody className="divide-y divide-gray-800/60 text-gray-300">
              {users?.data && users.data.length > 0 ? (
                users.data.map((user) => (
                  <tr key={user.id_user} className="hover:bg-gray-800/40 transition duration-150">
                    <td className="px-4 py-3 font-bold text-gray-200 whitespace-nowrap">
                      {user.username}
                    </td>

                    <td className="px-4 py-3 whitespace-nowrap">
                      <span className={`px-2.5 py-1 rounded-md text-[10px] font-bold uppercase border ${
                        user.role === 'admin' 
                          ? 'bg-purple-500/10 text-purple-400 border-purple-500/20' 
                          : user.role === 'user'
                          ? 'bg-blue-500/10 text-blue-400 border-blue-500/20'
                          : 'bg-gray-500/10 text-gray-400 border-gray-500/20'
                      }`}>
                        {user.role || 'Unknown'}
                      </span>
                    </td>

                    <td className="px-4 py-3">
                      <div className="flex flex-wrap gap-1 max-w-xs">
                        {Array.isArray(user.departments) && user.departments.length > 0 ? (
                          user.departments.map((dept, idx) => {
                            const isHead = Array.isArray(user.departments_head) && user.departments_head.includes(dept);

                            return (
                              <span
                                key={idx}
                                className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-semibold border transition-all ${
                                  isHead
                                    ? 'bg-amber-500/15 text-amber-300 border-amber-500/40 shadow-xs'
                                    : 'bg-gray-800 text-gray-300 border-gray-700/60'
                                }`}
                              >
                                <span>{dept}</span>
                              </span>
                            );
                          })
                        ) : (
                          <span className="text-gray-500 italic text-[11px]">- Tidak Ada -</span>
                        )}
                      </div>
                    </td>

                    <td className="px-4 py-3 whitespace-nowrap">
                      {user.is_active ? (
                        <span className="inline-flex items-center gap-1 text-emerald-400 font-semibold text-[11px]">
                          <HiCheckCircle className="w-4 h-4" />
                          <span>Aktif</span>
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-rose-400 font-semibold text-[11px]">
                          <HiXCircle className="w-4 h-4" />
                          <span>Non-Aktif</span>
                        </span>
                      )}
                    </td>

                    <td className="px-4 py-3 whitespace-nowrap text-center">
                      <button
                        type="button"
                        onClick={() => setSelectedUser(user)}
                        className="px-3 py-1.5 bg-gray-800 hover:bg-gray-700 text-blue-400 font-semibold rounded-lg transition inline-flex items-center gap-1.5 cursor-pointer"
                      >
                        <HiEye className="w-3.5 h-3.5" />
                        <span>Detail & Edit</span>
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={5} className="px-4 py-8 text-center text-gray-500 italic">
                    Tidak ada pengguna yang sesuai dengan filter.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination Links */}
        {users?.last_page > 1 && (
          <div className="p-4 border-t border-gray-800 flex items-center justify-between bg-gray-950/60">
            <p className="text-xs text-gray-400">
              Halaman <span className="font-bold text-gray-200">{users.current_page}</span> dari <span className="font-bold text-gray-200">{users.last_page}</span>
            </p>

            <div className="flex items-center gap-1">
              {users.links?.map((link, idx) => (
                <button
                  key={idx}
                  disabled={!link.url}
                  onClick={() => link.url && router.get(link.url, {}, { preserveState: true })}
                  dangerouslySetInnerHTML={{ __html: link.label }}
                  className={`px-3 py-1.5 text-xs font-semibold rounded-xl transition cursor-pointer ${
                    link.active 
                      ? 'bg-blue-600 text-white' 
                      : 'bg-gray-800/80 text-gray-300 hover:bg-gray-700 disabled:opacity-40 disabled:cursor-not-allowed'
                  }`}
                />
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Popup Tambah User */}
      <PopupCreateUser
        isOpen={isCreateOpen}
        onClose={() => setIsCreateOpen(false)}
        success={triggerSuccess}
      />

      {/* Popup Detail & Edit User */}
      {selectedUser && (
        <PopupDetailUser
          user={selectedUser}
          onClose={() => setSelectedUser(null)}
          success={triggerSuccess}
          error={triggerError}
        />
      )}

      {/* Alert / Notification Toast */}
      {isSuccessAlert && (
        <SuccessAlert
          title="Berhasil!"
          desc={successMsg}
          duration={3000}
          onClose={() => setIsSuccessAlert(false)}
        />
      )}

      {isErrorAlert && (
        <FailedAlert
          title="Gagal Memproses!"
          desc={errorMsg}
          duration={3000}
          onClose={() => setIsErrorAlert(false)}
        />
      )}
    </div>
  );
}

UsersManagement.layout = (page: React.ReactNode) => (
  <AdminLayout pageName="Manajemen Pengguna">
    {page}
  </AdminLayout>
);