"use client";

import { useEffect, useState } from "react";
import { getAudit } from "@/services/audit";
import { usePermissions } from "@/hooks/usePermissions";
import { useApiStore } from "@/store/uiStore";
import { useLocaleStore } from "@/store/uiStore";
import DataTable from "@/components/ui/Table";
import PageHeader from "@/components/ui/PageHeader";
import EmptyState from "@/components/ui/EmptyState";
import Spinner from "@/components/ui/Spinner";
import { AuditItem } from "@/types/api";
import { t } from "@/lib/locale";

export default function AuditPage() {
  const permissions = usePermissions();
  const addToast = useApiStore((s) => s.addToast);
  const locale = useLocaleStore((s) => s.locale);
  const [items, setItems] = useState<AuditItem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const load = async () => {
      if (!permissions.isAdmin) {
        setLoading(false);
        return;
      }
      setLoading(true);
      try {
        const data = await getAudit(50);
        setItems(data);
      } catch (error) {
        addToast((error as { message?: string })?.message || t("loadFailed", locale), "error");
      } finally {
        setLoading(false);
      }
    };
    load();
  }, [permissions.isAdmin, addToast, locale]);

  if (!permissions.isAdmin) {
    return (
      <div className="alert alert-warning">
        {t("forbidden", locale)}
      </div>
    );
  }

  return (
    <main className="vstack gap-3">
      <PageHeader
        title={t("audit", locale)}
        breadcrumb={[
          { label: t("dashboard", locale), href: "/dashboard" },
          { label: t("audit", locale), href: "/dashboard/audit" }
        ]}
      />
      {loading && <Spinner label={t("loading", locale)} />}
      {!loading && items.length === 0 ? (
        <EmptyState
          title={t("noData", locale)}
          description={t("noData", locale)}
        />
      ) : (
        <div className="card page-card">
          <div className="card-body">
            <DataTable
              columns={[
                { key: "id", header: "Id" },
                { key: "actor", header: "Actor" },
                { key: "action", header: "Action" },
                { key: "resourceType", header: "Resource Type" },
                { key: "resourceId", header: "Resource Id" },
                { key: "outcome", header: "Outcome" },
                { key: "correlationId", header: "Correlation" },
                { key: "createdAt", header: "Created" }
              ]}
              data={items}
            />
          </div>
        </div>
      )}
    </main>
  );
}
