import { createFileRoute } from "@tanstack/react-router";
import { useState, useEffect } from "react";
import { useGetAudits } from "@/hooks/queries";
import type { Audits } from "@/types/audit";
import { AuditListTemplate } from "@/template/audit-list-template";
import { auditColumns } from "@/components/columns/audit-column";

export const Route = createFileRoute("/_auth/audits/")({
  head: () => ({ meta: [{ title: "Audit Logs" }] }),
  loader: async ({ context }) => {
    context.breadcrumbs = [{ title: "Audit logs", path: "#" }];
  },
  component: AuditsPage,
});

function AuditsPage() {
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize] = useState(20);
  const [username, setUsername] = useState<string | null>(null);
  const [action, setAction] = useState<string | null>(null);
  const [from, setFrom] = useState<string | null>(null);
  const [to, setTo] = useState<string | null>(null);
  const [selectedAudit, setSelectedAudit] = useState<Audits | null>(null);

  const { data, isLoading, refetch, isFetching } = useGetAudits(
    {
      pageNumber,
      pageSize,
      username,
      action,
      from,
      to,
    },
    true
  ) as any;

  const items: Audits[] = data?.items ?? [];
  const total: number = data?.totalCount ?? 0;
  const pageCount = Math.max(1, Math.ceil(total / pageSize));

  useEffect(() => {
    refetch();
  }, [pageNumber, pageSize]);

  const handleSearch = () => {
    setPageNumber(1);
    refetch();
  };

  const handleReset = () => {
    setUsername(null);
    setAction(null);
    setFrom(null);
    setTo(null);
    setPageNumber(1);
    refetch();
  };

  return (
    <AuditListTemplate
      // data
      items={items}
      total={total}
      columns={auditColumns}
      isLoading={isLoading}
      isFetching={isFetching}
      // pagination
      pageNumber={pageNumber}
      pageSize={pageSize}
      pageCount={pageCount}
      canPreviousPage={pageNumber > 1}
      canNextPage={pageNumber < pageCount}
      onPreviousPage={() => setPageNumber((p) => Math.max(1, p - 1))}
      onNextPage={() => setPageNumber((p) => Math.min(pageCount, p + 1))}
      // filter
      username={username}
      action={action}
      from={from}
      to={to}
      onUsernameChange={setUsername}
      onActionChange={setAction}
      onFromChange={setFrom}
      onToChange={setTo}
      onSearch={handleSearch}
      onReset={handleReset}
      // detail dialog
      selectedAudit={selectedAudit}
      onRowClick={setSelectedAudit}
      onDialogClose={() => setSelectedAudit(null)}
    />
  );
}
