"use client";

import { useEffect, useMemo, useState } from "react";
import { createRoleRequest, updateRolePermissionRequest } from "@/services/roles";
import { getWorkflowRequests } from "@/services/workflow";
import { useApiStore, useLocaleStore } from "@/store/uiStore";
import { usePermissions } from "@/hooks/usePermissions";
import { WorkflowRequestItem, WorkflowResourceType } from "@/types/api";
import RoleCreateForm from "@/components/role/RoleCreateForm";
import RolePermissionForm from "@/components/role/RolePermissionForm";
import { t } from "@/lib/locale";
import DataTable from "@/components/ui/Table";
import StatusBadge from "@/components/workflow/StatusBadge";
import PageHeader from "@/components/ui/PageHeader";
import EmptyState from "@/components/ui/EmptyState";

const RESOURCE_TYPE = WorkflowResourceType.ROLE_MANAGEMENT;

export default function RolesPage() {
  const [requests, setRequests] = useState<WorkflowRequestItem[]>([]);
  const [loading, setLoading] = useState(false);
  const addToast = useApiStore((s) => s.addToast);
  const locale = useLocaleStore((s) => s.locale);
  const permissions = usePermissions();
  const permissionCatalog = useMemo(
    () =>
      Array.from(
        new Set([
          ...permissions.permissions,
          "USER_MANAGE",
          "WORKFLOW_APPROVE",
          "ROLE_MANAGE",
          "USER_ROLE_ADMIN"
        ])
      ).sort(),
    [permissions.permissions]
  );

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

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

  const handleCreate = async (values: { code: string; name: string; permissionCodes: string[] }) => {
    try {
      await createRoleRequest(values);
      addToast(t("roleCreateCreated", locale), "success");
      load();
    } catch (error) {
      addToast((error as { message?: string })?.message || t("createFailed", locale), "error");
    }
  };

  const handleUpdate = async (values: { code: string; permissionCodes: string[] }) => {
    try {
      await updateRolePermissionRequest(values);
      addToast(t("rolePermissionUpdated", locale), "success");
      load();
    } catch (error) {
      addToast((error as { message?: string })?.message || t("updateFailed", locale), "error");
    }
  };

  return (
    <main className="vstack gap-4">
      <PageHeader
        title={t("roles", locale)}
        breadcrumb={[
          { label: t("dashboard", locale), href: "/dashboard" },
          { label: t("roles", locale), href: "/dashboard/roles" }
        ]}
      />
      <section className="card page-card">
        <div className="card-header fw-bold">{t("createRoleRequest", locale)}</div>
        <div className="card-body">
          <RoleCreateForm
            disabled={!(permissions.canManageRoles || permissions.isAdminOrManager)}
            onSubmit={handleCreate}
          />
        </div>
      </section>

      <section className="card page-card">
        <div className="card-header fw-bold">{t("updateRolePermissions", locale)}</div>
        <div className="card-body">
          <RolePermissionForm
            disabled={!(permissions.canManageRoles || permissions.isAdminOrManager)}
            permissionCatalog={permissionCatalog}
            onSubmit={handleUpdate}
          />
        </div>
      </section>

      <section className="card page-card">
        <div className="card-header fw-bold">{t("recentRoleRequests", locale)}</div>
        <div className="card-body">
          {requests.length === 0 && !loading && (
            <EmptyState
              title={t("noRoleRequests", locale)}
              description={t("noData", locale)}
            />
          )}
          <DataTable
            loading={loading}
            noDataText={t("noRoleRequests", locale)}
            columns={[
              { key: "id", header: "Request Id" },
              { key: "resourceId", header: "Role Code" },
              { key: "makerUsername", header: "Maker" },
              {
                key: "status",
                header: "Status",
                render: (row) => <StatusBadge status={row.status} />
              },
              { key: "createdAt", header: "Created" },
              { key: "payload", header: "Payload", render: (row) => <code>{row.payload}</code> }
            ]}
            data={requests}
          />
        </div>
      </section>
    </main>
  );
}
