import { Button, Link, Table, Badge } from "@tailor-platform/app-shell";
import { graphql, type FragmentOf, readFragment } from "@/graphql";
import { EmptyState } from "@/components/composed/empty-state";

const AuditEntryRowFragment = graphql(`
  fragment AuditEntryRow on AuditEntry {
    id
    operationType
    entityType
    entityId
    actorType
    actorId
    createdAt
  }
`);

export const AuditEntriesTableFragment = graphql(
  `
    fragment AuditEntriesTable on AuditEntryConnection {
      edges {
        node {
          ...AuditEntryRow
        }
      }
    }
  `,
  [AuditEntryRowFragment],
);

interface AuditEntryRowProps {
  entry: FragmentOf<typeof AuditEntryRowFragment>;
}

const AuditEntryRow = ({ entry: entryFragment }: AuditEntryRowProps) => {
  const entry = readFragment(AuditEntryRowFragment, entryFragment);
  return (
    <Table.Row>
      {/* eslint-disable-next-line react-x/purity -- parsing a fixed timestamp, not reading current time */}
      <Table.Cell>{entry.createdAt ? new Date(entry.createdAt).toLocaleString() : "-"}</Table.Cell>
      <Table.Cell>{entry.entityType}</Table.Cell>
      <Table.Cell>{entry.entityId}</Table.Cell>
      <Table.Cell>
        <Badge variant="default">{entry.operationType}</Badge>
      </Table.Cell>
      <Table.Cell>{entry.actorId}</Table.Cell>
      <Table.Cell>
        <Button variant="ghost" size="sm" render={<Link to={entry.id} />}>
          View
        </Button>
      </Table.Cell>
    </Table.Row>
  );
};

interface AuditEntriesTableProps {
  data: FragmentOf<typeof AuditEntriesTableFragment>;
}

export const AuditEntriesTable = ({ data }: AuditEntriesTableProps) => {
  const { edges } = readFragment(AuditEntriesTableFragment, data);

  if (edges.length === 0) {
    return (
      <EmptyState title="No audit entries" message="No audit entries have been recorded yet." />
    );
  }

  return (
    <Table.Root>
      <Table.Header>
        <Table.Row>
          <Table.Head>Timestamp</Table.Head>
          <Table.Head>Entity Type</Table.Head>
          <Table.Head>Entity ID</Table.Head>
          <Table.Head>Operation</Table.Head>
          <Table.Head>Actor</Table.Head>
          <Table.Head />
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {edges.map((edge) => (
          <AuditEntryRow
            key={readFragment(AuditEntryRowFragment, edge.node).id}
            entry={edge.node}
          />
        ))}
      </Table.Body>
    </Table.Root>
  );
};
