"use client";

import type { RedirectGraphNode, RedirectHistory } from "@domainops/shared-types";
import { App, Drawer, Table, Tag, Typography } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { getRedirectHistory } from "@/lib/api/redirects";
import { ApiError } from "@/lib/api/client";

interface HistoryRow {
  id: number;
  target_url: string;
  type: "301" | "302";
  valid_from: string;
  valid_to: string | null;
  source_fqdn?: string;
}

export function NodeHistoryDrawer({
  node,
  onClose,
}: {
  node: RedirectGraphNode | null;
  onClose: () => void;
}) {
  const { message } = App.useApp();
  const [history, setHistory] = useState<RedirectHistory | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (!node) return;

    async function load(nodeId: number) {
      setIsLoading(true);
      try {
        setHistory(await getRedirectHistory(nodeId));
      } catch (err) {
        message.error(err instanceof ApiError ? err.message : "Couldn't load redirect history.");
      } finally {
        setIsLoading(false);
      }
    }

    void load(node.id);
  }, [node, message]);

  const columns: ColumnsType<HistoryRow> = [
    { title: "Target", dataIndex: "target_url", render: (v: string) => <span className="font-mono text-xs">{v}</span> },
    { title: "Type", dataIndex: "type", render: (v: string) => <Tag>{v}</Tag> },
    {
      title: "From",
      dataIndex: "valid_from",
      render: (v: string) => new Date(v).toLocaleDateString(),
    },
    {
      title: "To",
      dataIndex: "valid_to",
      render: (v: string | null) => (v ? new Date(v).toLocaleDateString() : <Tag color="green">active</Tag>),
    },
  ];

  const outColumns = columns;
  const inColumns: ColumnsType<HistoryRow> = [
    {
      title: "From domain",
      dataIndex: "source_fqdn",
      render: (v: string) => <span className="font-mono text-xs">{v}</span>,
    },
    ...columns.slice(1),
  ];

  return (
    <Drawer
      title={node ? `Redirect history - ${node.fqdn}` : "Redirect history"}
      open={!!node}
      onClose={onClose}
      size={520}
      className="node-history-drawer dms_redirects_map_node_history_drawer"
    >
      <Typography.Title level={5}>Outgoing (this domain&apos;s own redirects)</Typography.Title>
      <Table<HistoryRow>
        rowKey="id"
        size="small"
        loading={isLoading}
        dataSource={history?.out.map((e) => ({ ...e }))}
        columns={outColumns}
        pagination={false}
        style={{ marginBottom: 24 }}
        className="dms_redirects_map_node_history_outgoing_table"
      />

      <Typography.Title level={5}>Incoming (redirects pointing at this domain)</Typography.Title>
      <Table<HistoryRow>
        rowKey="id"
        size="small"
        loading={isLoading}
        dataSource={history?.in.map((e) => ({ ...e, source_fqdn: e.source_domain?.fqdn ?? "—" }))}
        columns={inColumns}
        pagination={false}
        className="dms_redirects_map_node_history_incoming_table"
      />
    </Drawer>
  );
}
