"use client";

import type { AuditLogEntry } from "@domainops/shared-types";
import { App, Card, DatePicker, Table, Tag } from "antd";
import type { Dayjs } from "dayjs";
import type { ColumnsType } from "antd/es/table";
import { useCallback, useEffect, useState } from "react";
import { listDomainActivity } from "@/lib/api/domains";
import { ApiError } from "@/lib/api/client";
import { auditDetails } from "@/lib/utils/auditDetails";
import { ActorLabel } from "@/components/features/ActorLabel";
import { PAGE_SIZE_OPTIONS } from "@/lib/hooks/useServerPagination";

const columns: ColumnsType<AuditLogEntry> = [
  { title: "Date", dataIndex: "created_at", render: (v: string) => new Date(v).toLocaleString() },
  { title: "Action", dataIndex: "action", render: (v: string) => <span className="font-mono">{v}</span> },
  { title: "Details", render: (_, entry) => auditDetails(entry) || "—" },
  { title: "Actor", render: (_, entry) => <ActorLabel actor={entry.actor} /> },
  {
    title: "Result",
    dataIndex: "result",
    render: (v: string) => <Tag color={v === "success" ? "green" : "red"}>{v}</Tag>,
  },
];

/**
 * Every module already logs through AuditLogger - this is just that same
 * audit_log table, filtered to this one domain (see
 * DomainController::activity()), not a new logging path.
 */
export function ActivityPanel({ domainId }: { domainId: number }) {
  const { message } = App.useApp();
  const [entries, setEntries] = useState<AuditLogEntry[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [range, setRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      const result = await listDomainActivity(domainId, page, {
        date_from: range?.[0]?.format("YYYY-MM-DD"),
        date_to: range?.[1]?.format("YYYY-MM-DD"),
      });
      setEntries(result.data);
      setTotal(result.meta.total);
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't load this domain's activity.");
    } finally {
      setIsLoading(false);
    }
  }, [domainId, page, range, message]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    void load();
  }, [load]);

  return (
    <Card
      title="Activity"
      extra={
        <DatePicker.RangePicker
          allowClear
          format="DD/MM/YYYY"
          onChange={(value) => {
            setPage(1);
            setRange(value);
          }}
          className="dms_domain_activity_date_range"
        />
      }
      className="dms_domain_activity_panel_card"
    >
      <Table<AuditLogEntry>
        rowKey="id"
        columns={columns}
        dataSource={entries}
        loading={isLoading}
        pagination={{
          current: page,
          total,
          pageSize: 25,
          onChange: setPage,
          showSizeChanger: true,
          pageSizeOptions: PAGE_SIZE_OPTIONS,
          showTotal: (count) => `${count} entries`,
        }}
        className="dms_domain_activity_table"
      />
    </Card>
  );
}
