// components/DnsSettingsModal.tsx
"use client";

import { useState } from "react";
import { X, Copy, Check, ShieldCheck, Loader2, AlertCircle, CheckCircle2 } from "lucide-react";

interface DnsRecords {
  mxRecords: { type: string; host: string; value: string; priority: number }[];
  txtRecord: { type: string; host: string; value: string };
}

interface DnsSettingsModalProps {
  domainId: string;
  domainName: string;
  status: "PENDING" | "ACTIVE";
  dnsRecords: DnsRecords;
  onClose: () => void;
  onVerified: () => void;
}

function CopyableRow({ label, value }: { label: string; value: string }) {
  const [copied, setCopied] = useState(false);

  async function handleCopy() {
    await navigator.clipboard.writeText(value);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  }

  return (
    <div className="flex items-center justify-between gap-2 bg-slate-800 rounded-lg px-3 py-2">
      <div className="min-w-0">
        <p className="text-[10px] uppercase tracking-wide text-slate-500">{label}</p>
        <p className="text-sm text-slate-200 font-mono truncate">{value}</p>
      </div>
      <button
        onClick={handleCopy}
        className="shrink-0 text-slate-400 hover:text-white transition-colors"
        aria-label={`Copy ${label}`}
      >
        {copied ? <Check className="w-4 h-4 text-emerald-400" /> : <Copy className="w-4 h-4" />}
      </button>
    </div>
  );
}

export default function DnsSettingsModal({
  domainId,
  domainName,
  status,
  dnsRecords,
  onClose,
  onVerified,
}: DnsSettingsModalProps) {
  const [isVerifying, setIsVerifying] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<{ isFullyVerified: boolean } | null>(null);

  async function handleVerify() {
    setIsVerifying(true);
    setError(null);
    setResult(null);
    try {
      const res = await fetch(`/api/domains/${domainId}/verify`, { method: "POST" });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Verification failed");
        setIsVerifying(false);
        return;
      }
      setResult(data.dnsResult);
      if (data.dnsResult.isFullyVerified) {
        onVerified();
      }
    } catch {
      setError("Something went wrong while verifying.");
    } finally {
      setIsVerifying(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4">
      <div className="w-full max-w-lg bg-slate-900 border border-slate-800 rounded-2xl shadow-xl max-h-[85vh] overflow-y-auto">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-800 sticky top-0 bg-slate-900">
          <div>
            <h2 className="text-sm font-semibold text-white">DNS Settings</h2>
            <p className="text-xs text-slate-500 mt-0.5">{domainName}</p>
          </div>
          <button onClick={onClose} className="text-slate-500 hover:text-white transition-colors">
            <X className="w-4 h-4" />
          </button>
        </div>

        <div className="p-5 space-y-5">
          <div
            className={`flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-medium ${
              status === "ACTIVE"
                ? "bg-emerald-950/40 text-emerald-400 border border-emerald-900"
                : "bg-amber-950/40 text-amber-400 border border-amber-900"
            }`}
          >
            <ShieldCheck className="w-4 h-4" />
            {status === "ACTIVE" ? "Domain is verified and active" : "Domain is pending verification"}
          </div>

          <div>
            <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wide mb-2">
              MX Records
            </h3>
            <div className="space-y-2">
              {dnsRecords.mxRecords.map((mx, i) => (
                <div key={i} className="grid grid-cols-3 gap-2">
                  <CopyableRow label="Host" value={mx.host} />
                  <CopyableRow label={`Value (priority ${mx.priority})`} value={mx.value} />
                  <CopyableRow label="Type" value={mx.type} />
                </div>
              ))}
            </div>
          </div>

          <div>
            <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-wide mb-2">
              TXT Record (ownership verification)
            </h3>
            <div className="grid grid-cols-2 gap-2">
              <CopyableRow label="Host" value={dnsRecords.txtRecord.host} />
              <CopyableRow label="Value" value={dnsRecords.txtRecord.value} />
            </div>
          </div>

          {error && (
            <div className="flex items-center gap-2 text-sm text-red-400 bg-red-950/40 border border-red-900 rounded-lg px-3 py-2">
              <AlertCircle className="w-4 h-4 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          {result && !result.isFullyVerified && (
            <div className="flex items-center gap-2 text-sm text-amber-400 bg-amber-950/40 border border-amber-900 rounded-lg px-3 py-2">
              <AlertCircle className="w-4 h-4 shrink-0" />
              <span>Records not fully propagated yet. DNS changes can take up to 24-48 hours.</span>
            </div>
          )}

          {result?.isFullyVerified && (
            <div className="flex items-center gap-2 text-sm text-emerald-400 bg-emerald-950/40 border border-emerald-900 rounded-lg px-3 py-2">
              <CheckCircle2 className="w-4 h-4 shrink-0" />
              <span>Domain successfully verified!</span>
            </div>
          )}

          <div className="flex justify-end gap-2 pt-2">
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-slate-300 hover:text-white transition-colors"
            >
              Close
            </button>
            <button
              onClick={handleVerify}
              disabled={isVerifying || status === "ACTIVE"}
              className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-indigo-600 hover:bg-indigo-500 disabled:bg-indigo-900 disabled:text-slate-500 disabled:cursor-not-allowed text-white rounded-lg transition-colors"
            >
              {isVerifying && <Loader2 className="w-4 h-4 animate-spin" />}
              {status === "ACTIVE" ? "Already Verified" : "Check DNS Now"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
