"use client";

import { type ReactNode, useState, useEffect } from "react";
import {
  useUsers,
  useUserFilter,
  useCreateUser,
  useUpdateUser,
  useToggleUserStatus,
} from "@/hooks/use-users";
import { useRoles } from "@/hooks/use-roles";
import { useToast } from "@/providers/toast-provider";
import {
  PageHeader,
  PaperCard,
  Input,
  Select,
  LoadingState,
  ErrorState,
  EmptyState,
  Pagination,
} from "@/components/ui";
import { UserManagementTable } from "@/components/user-management-table";
import { UserFormModal, type UserFormData } from "@/components/user-form-modal";
import { t } from "@/lib/i18n";
import type { UserViewModel } from "@/types/view-models";

export default function UsersPage(): ReactNode {
  const { filter, setPage, setSearch, setStatus } = useUserFilter();
  const { data, loading, error } = useUsers(filter);
  const { data: roles } = useRoles();
  const { show } = useToast();
  const [createUser] = useCreateUser();
  const [updateUser] = useUpdateUser();
  const [toggleStatus] = useToggleUserStatus();
  const [modalOpen, setModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<UserViewModel | null>(null);
  const [searchInput, setSearchInput] = useState("");

  useEffect(() => {
    const timer = setTimeout(() => setSearch(searchInput), 300);
    return () => clearTimeout(timer);
  }, [searchInput, setSearch]);

  const handleCreate = () => {
    setEditingUser(null);
    setModalOpen(true);
  };

  const handleEdit = (user: UserViewModel) => {
    setEditingUser(user);
    setModalOpen(true);
  };

  const handleToggleStatus = async (user: UserViewModel) => {
    const newStatus = user.status === "active" ? "disabled" : "active";
    try {
      await toggleStatus(user.id, newStatus);
      show("success", "状态已更新");
      window.location.reload();
    } catch (err) {
      show(
        "error",
        "操作失败",
        err instanceof Error ? err.message : String(err),
      );
    }
  };

  const handleSubmit = async (formData: UserFormData) => {
    try {
      if (editingUser) {
        await updateUser(editingUser.id, {
          name: formData.name,
          email: formData.email,
          roleIds: formData.roleIds,
          dataScope: formData.dataScope,
        });
        show("success", "用户已更新");
      } else {
        await createUser({
          email: formData.email,
          name: formData.name,
          password: formData.password ?? "",
          roleIds: formData.roleIds,
          dataScope: formData.dataScope,
        });
        show("success", "用户已创建");
      }
      setModalOpen(false);
      window.location.reload();
    } catch (err) {
      show(
        "error",
        "操作失败",
        err instanceof Error ? err.message : String(err),
      );
    }
  };

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.users.title")}
        description="管理所有用户账号、角色分配与状态"
      />

      <PaperCard className="p-4 mb-4">
        <div className="flex gap-3 items-center">
          <Input
            type="search"
            placeholder={t("admin.common.search")}
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            style={{ width: 240 }}
          />
          <Select
            value={filter.status ?? "all"}
            onChange={(e) => setStatus(e.target.value)}
          >
            <option value="all">{t("admin.common.all")}</option>
            <option value="active">{t("admin.common.active")}</option>
            <option value="disabled">{t("admin.common.disabled")}</option>
            <option value="locked">{t("admin.common.locked")}</option>
          </Select>
        </div>
      </PaperCard>

      <PaperCard className="p-4">
        {loading && <LoadingState />}
        {error && <ErrorState message={error.message} />}
        {!loading && !error && data && (
          <>
            {data.items.length === 0 ? (
              <EmptyState message={t("admin.common.empty")} />
            ) : (
              <>
                <UserManagementTable
                  users={data.items}
                  onEdit={handleEdit}
                  onToggleStatus={handleToggleStatus}
                  onCreate={handleCreate}
                />
                <Pagination
                  page={data.page}
                  pageSize={data.pageSize}
                  total={data.total}
                  hasNext={data.hasNext}
                  onPageChange={setPage}
                />
              </>
            )}
          </>
        )}
      </PaperCard>

      <UserFormModal
        open={modalOpen}
        user={editingUser}
        roles={roles}
        onSubmit={handleSubmit}
        onCancel={() => setModalOpen(false)}
      />
    </div>
  );
}
