"use client";

import type { Domain } from "@domainops/shared-types";
import { App, Button, Switch, Table, Tooltip } from "antd";
import { EditOutlined, InboxOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import Link from "next/link";
import { useEffect, useState } from "react";
import { toggleRobots } from "@/lib/api/seo";
import { ApiError } from "@/lib/api/client";
import { confirmRobotsChange } from "@/lib/utils/robotsConfirm";
import { DomainStatusTag } from "@/components/features/DomainStatusTag";

/**
 * The nested row under a parent domain on the All Domains list - a
 * subdomain is a first-class Domain row (see Domain::subdomains() on the
 * backend), just always rendered under its parent instead of as its own
 * top-level row. Reuses the same robots-toggle/edit/archive actions the
 * parent list itself offers.
 */
export function SubdomainsTable({
  subdomains,
  onEdit,
  onArchive,
}: {
  subdomains: Domain[];
  onEdit: (domain: Domain) => void;
  onArchive: (domain: Domain) => void;
}) {
  const { message, modal } = App.useApp();
  const [togglingId, setTogglingId] = useState<number | null>(null);
  const [rows, setRows] = useState(subdomains);

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

  async function handleToggleRobots(domain: Domain, index: boolean) {
    setTogglingId(domain.id);
    try {
      const updated = await toggleRobots(domain.id, index);
      setRows((current) => current.map((d) => (d.id === updated.id ? updated : d)));
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't change that domain's robots state.");
    } finally {
      setTogglingId(null);
    }
  }

  const columns: ColumnsType<Domain> = [
    {
      title: "Subdomain",
      dataIndex: "fqdn",
      render: (fqdn: string, domain) => (
        <Link href={`/domains/${domain.id}`} className="font-mono">
          {fqdn}
        </Link>
      ),
    },
    {
      title: "Robots",
      dataIndex: "robots_state",
      render: (value: Domain["robots_state"], domain) => (
        <Tooltip title={value === "index" ? "Set to noindex" : "Set to index"}>
          <Switch
            size="small"
            checked={value === "index"}
            loading={togglingId === domain.id}
            onChange={(checked) => confirmRobotsChange(modal, domain.fqdn, checked, () => handleToggleRobots(domain, checked))}
            className="dms_subdomains_robots_toggle"
          />
        </Tooltip>
      ),
    },
    {
      title: "Status",
      dataIndex: "status",
      render: (value: Domain["status"]) => <DomainStatusTag status={value} />,
    },
    {
      title: "Actions",
      render: (_, domain) => (
        <div className="flex gap-2">
          <Tooltip title="Edit">
            <Button size="small" icon={<EditOutlined />} onClick={() => onEdit(domain)} className="dms_subdomains_edit_btn" />
          </Tooltip>
          <Tooltip title="Archive">
            <Button size="small" icon={<InboxOutlined />} onClick={() => onArchive(domain)} className="dms_subdomains_archive_btn" />
          </Tooltip>
        </div>
      ),
    },
  ];

  return (
    <Table<Domain>
      rowKey="id"
      columns={columns}
      dataSource={rows}
      pagination={false}
      size="small"
      className="dms_subdomains_table"
    />
  );
}
