"use client";

import { useEffect, useMemo, useState } from "react";
import { createUserRequest, updateUserRolesRequest } from "@/services/users";
import { getWorkflowRequests } from "@/services/workflow";
import { useApiStore } from "@/store/uiStore";
import { useLocaleStore } from "@/store/uiStore";
import { usePermissions } from "@/hooks/usePermissions";
import UserCreateForm from "@/components/user/UserCreateForm";
import UserRoleUpdateForm from "@/components/user/RoleUpdateForm";
import DataTable from "@/components/ui/Table";
import PageHeader from "@/components/ui/PageHeader";
import EmptyState from "@/components/ui/EmptyState";
import { WorkflowRequestItem, WorkflowResourceType } from "@/types/api";
import { t } from "@/lib/locale";
import StatusBadge from "@/components/workflow/StatusBadge";

const RESOURCE_TYPE = WorkflowResourceType.USER_MANAGEMENT;

export default function UsersPage() {
  const [requests, setRequests] = useState<WorkflowRequestItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const { canManageUsers, isAdminOrManager } = usePermissions();
  const addToast = useApiStore((s) => s.addToast);
  const locale = useLocaleStore((s) => s.locale);
  const authMode =
    process.env.NEXT_PUBLIC_AUTH_MODE?.toLowerCase?.() === "ldap" ? "LDAP" : "LOCAL";

  const loadRequests = async () => {
    setIsLoading(true);
    try {
      const data = await getWorkflowRequests({ resourceType: RESOURCE_TYPE, limit: 100 });
      setRequests(data);
    } catch (error: unknown) {
      addToast((error as { message?: string })?.message || t("loadFailed", locale), "error");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadRequests();
  }, []);

  const rows = useMemo(
    () =>
      requests.map((item) => ({
        ...item,
        actionLabel: item.status === "PENDING" ? t("pending", locale) : t("done", locale)
      })),
    [requests, locale]
  );

  const onCreate = async (payload: {
    username: string;
    password?: string;
    ldapDn?: string;
    enabled?: boolean;
    roleCodes: string[];
  }) => {
    try {
      await createUserRequest(payload);
      addToast(t("userRequestCreated", locale), "success");
      loadRequests();
    } catch (error) {
      addToast((error as { message?: string })?.message || t("createFailed", locale), "error");
    }
  };

  const onUpdateRoles = async (payload: { username: string; roleCodes: string[] }) => {
    try {
      await updateUserRolesRequest(payload);
      addToast(t("userRoleRequestCreated", locale), "success");
      loadRequests();
    } catch (error) {
      addToast((error as { message?: string })?.message || t("updateFailed", locale), "error");
    }
  };

  return (
    <main className="vstack gap-4">
      <PageHeader
        title={t("users", locale)}
        description={`${t("ldapModeIndicator", locale)}: ${authMode}`}
        breadcrumb={[
          { label: t("dashboard", locale), href: "/dashboard" },
          { label: t("users", locale), href: "/dashboard/users" }
        ]}
      />

      <section className="row g-4">
        <div className="col-12 col-lg-6">
          <div className="card page-card">
            <div className="card-header fw-bold">{t("createUserRequest", locale)}</div>
            <div className="card-body">
              <UserCreateForm
                disabled={!(canManageUsers || isAdminOrManager)}
                onSubmit={onCreate}
                authMode={authMode}
              />
            </div>
          </div>
        </div>
        <div className="col-12 col-lg-6">
          <div className="card page-card">
            <div className="card-header fw-bold">{t("updateUserRolesRequest", locale)}</div>
            <div className="card-body">
              <UserRoleUpdateForm disabled={!(canManageUsers || isAdminOrManager)} onSubmit={onUpdateRoles} />
            </div>
          </div>
        </div>
      </section>

      <section className="card page-card">
        <div className="card-header fw-bold">{t("recentRequests", locale)}</div>
        <div className="card-body">
          {requests.length === 0 && !isLoading && (
            <EmptyState
              title={t("noUserRequests", locale)}
              description={t("noData", locale)}
            />
          )}
          <DataTable
            columns={[
              { key: "id", header: "Request ID" },
              { key: "resourceId", header: "Username" },
              { key: "makerUsername", header: "Maker" },
              {
                key: "status",
                header: "Status",
                render: (item) => <StatusBadge status={item.status} />
              },
              { key: "createdAt", header: "Created" },
              { key: "updatedAt", header: "Updated" },
              { key: "actionLabel", header: "State" }
            ]}
            data={rows}
            loading={isLoading}
            noDataText={t("noUserRequests", locale)}
          />
        </div>
      </section>
    </main>
  );
}
