"use client";

import type { Domain } from "@domainops/shared-types";
import { App, Button, Input, Popconfirm, Tag, Typography } from "antd";
import { ExportOutlined } from "@ant-design/icons";
import { useState } from "react";
import { recordGscToken, verifyGsc } from "@/lib/api/seo";
import { ApiError } from "@/lib/api/client";
import { searchConsoleUrl } from "@/lib/utils/searchConsole";
import { titleCase } from "@/lib/utils/text";

const GSC_COLORS: Record<Domain["gsc_state"], string> = {
  not_started: "default",
  pending: "gold",
  verified: "green",
};

/**
 * Search Console ownership via a DNS TXT record. The value comes from
 * Google Search Console itself (Add property > Domain > TXT) and is pasted
 * in here - this app records it and adds the TXT record (to Cloudflare when
 * the domain has a zone), it never generates a verification value.
 */
export function GscTxtSection({ domain, onUpdated }: { domain: Domain; onUpdated: (domain: Domain) => void }) {
  const { message } = App.useApp();
  const [token, setToken] = useState("");
  const [isBusy, setIsBusy] = useState(false);
  const isVerified = domain.gsc_state === "verified";
  const hasRecord = domain.gsc_state === "pending" && !!domain.gsc_verification_token;

  async function handleAddRecord() {
    setIsBusy(true);
    try {
      const updated = await recordGscToken(domain.id, token || domain.gsc_verification_token || "");
      setToken("");
      onUpdated(updated);
      if (updated.dns_added) message.success("TXT record added to Cloudflare DNS.");
      else message.warning(updated.dns_message ?? "Saved, but the TXT record was not added to DNS.");
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't save that TXT value.");
    } finally {
      setIsBusy(false);
    }
  }

  async function handleVerify() {
    setIsBusy(true);
    try {
      const updated = await verifyGsc(domain.id);
      onUpdated(updated);
      message[updated.gsc_state === "verified" ? "success" : "info"](
        updated.gsc_state === "verified" ? "Verified." : "Not verified yet - the TXT record may still be propagating.",
      );
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't check verification.");
    } finally {
      setIsBusy(false);
    }
  }

  return (
    <div className="flex flex-col gap-2 dms_gsc_txt_section">
      <div className="flex items-center gap-2">
        <span className="font-medium">Search Console</span>
        <Tag color={GSC_COLORS[domain.gsc_state]}>{titleCase(domain.gsc_state.replace("_", " "))}</Tag>
        <Button
          size="small"
          icon={<ExportOutlined />}
          href={searchConsoleUrl(domain.fqdn, !!domain.parent_domain_id)}
          target="_blank"
          rel="noopener noreferrer"
          className="dms_gsc_open_btn"
        >
          Open in Search Console
        </Button>
      </div>

      {isVerified && (
        <div
          className="rounded px-3 py-2 dms_gsc_txt_current"
          style={{ background: "rgba(22, 163, 106, 0.12)", border: "1px solid rgba(22, 163, 106, 0.45)" }}
        >
          <Typography.Text type="success" strong>
            Ownership is verified
          </Typography.Text>
          <div className="text-xs mt-1" style={{ opacity: 0.8 }}>
            Current TXT value on {domain.fqdn}:
          </div>
          <div className="font-mono break-all mt-1 dms_gsc_txt_current_value" style={{ color: "#16a36a" }}>
            {domain.gsc_verification_token ?? "No TXT value on file"}
          </div>
        </div>
      )}

      {!isVerified && hasRecord && (
        <div className="text-xs text-gray-500">
          Saved TXT value for {domain.fqdn}:
          <div className="font-mono bg-black/20 rounded px-2 py-1 mt-1 break-all">{domain.gsc_verification_token}</div>
        </div>
      )}

      <Input
        value={token}
        onChange={(e) => setToken(e.target.value)}
        placeholder="google-site-verification=..."
        className="dms_gsc_txt_input"
      />
      <Typography.Text type="secondary" className="text-xs">
        {isVerified ? "To use a different Search Console property, paste its new TXT value. " : "Paste the TXT value from Google Search Console. "}
        {domain.cf_zone_id ? "It is added to this domain's Cloudflare DNS." : "No Cloudflare zone - add the record wherever this domain's DNS lives."}
      </Typography.Text>
      <div className="flex gap-2 flex-wrap">
        {isVerified ? (
          <Popconfirm
            title="Replace the verified record?"
            description="The status goes back to Pending until the new record is verified."
            okText="Replace"
            disabled={!token}
            onConfirm={handleAddRecord}
          >
            <Button size="small" type="primary" loading={isBusy} disabled={!token} className="dms_gsc_txt_add_btn">
              Replace with a new TXT record
            </Button>
          </Popconfirm>
        ) : (
          <>
            <Button
              size="small"
              type="primary"
              onClick={handleAddRecord}
              loading={isBusy}
              disabled={!token && !hasRecord}
              className="dms_gsc_txt_add_btn"
            >
              {hasRecord && !token ? "Re-add TXT record" : "Add TXT record"}
            </Button>
            {hasRecord && (
              <Button size="small" onClick={handleVerify} loading={isBusy} className="dms_gsc_txt_verify_btn">
                Check verification
              </Button>
            )}
          </>
        )}
      </div>
    </div>
  );
}
