"use client";

import type { Domain } from "@domainops/shared-types";
import { Button, Modal } from "antd";
import { useEffect, useState } from "react";
import { GscTxtSection } from "@/components/features/GscTxtSection";

/**
 * Quick popup off the Domain Inventory list for adding a domain's Google
 * Search Console TXT record - the same GscTxtSection the domain's SEO tab
 * uses.
 */
export function GscQuickModal({
  open,
  domain,
  onClose,
  onSaved,
}: {
  open: boolean;
  domain: Domain | null;
  onClose: () => void;
  onSaved: (domain: Domain) => void;
}) {
  const [current, setCurrent] = useState<Domain | null>(domain);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    if (open) setCurrent(domain);
    // Reset only when the modal opens for a (possibly different) domain.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, domain?.id]);

  return (
    <Modal
      title={domain ? `Search Console - ${domain.fqdn}` : "Search Console"}
      open={open}
      onCancel={onClose}
      footer={<Button onClick={onClose}>Close</Button>}
      destroyOnHidden
      className="dms_gsc_quick_modal"
    >
      {current && (
        <GscTxtSection
          domain={current}
          onUpdated={(updated) => {
            setCurrent(updated);
            onSaved(updated);
          }}
        />
      )}
    </Modal>
  );
}
