'use client';

import { useState } from 'react';
import type { StoreDomain, StoreSite } from '@alqove/api-client';
import { firstError, useDomainMutations } from './use-store-site';
import { ErrorText, inputCls, Panel, PrimaryButton, SecondaryButton } from './ui';

export function DomainsPanel({ storeId, site }: { storeId: string; site: StoreSite }) {
  const domains = site.domains ?? [];
  const { addDomain, verifyDomain, makePrimary, removeDomain } = useDomainMutations(storeId);
  const [hostname, setHostname] = useState('');

  const error =
    firstError(addDomain.error) ??
    firstError(makePrimary.error) ??
    firstError(removeDomain.error);

  return (
    <div className="space-y-6">
      <Panel
        title="Your own domain"
        description="Point a domain you already own at this site. Visitors stay on your address — Alqove serves the pages behind it."
      >
        <div className="flex flex-wrap items-end gap-3">
          <label className="flex flex-1 flex-col gap-1 text-sm">
            <span className="text-xs uppercase tracking-wide text-ink/60">Domain</span>
            <input
              className={inputCls}
              placeholder="shop.example.com"
              value={hostname}
              onChange={(e) => setHostname(e.target.value)}
            />
          </label>
          <PrimaryButton
            onClick={() => {
              if (!hostname.trim()) return;
              addDomain.mutate(hostname.trim(), { onSuccess: () => setHostname('') });
            }}
            disabled={addDomain.isPending}
          >
            {addDomain.isPending ? 'Adding…' : 'Add domain'}
          </PrimaryButton>
        </div>
        <ErrorText>{error}</ErrorText>

        {domains.length === 0 && (
          <p className="mt-4 text-sm text-ink/60">
            No custom domain yet — your site is live at the Alqove address above.
          </p>
        )}

        <div className="mt-4 space-y-4">
          {domains.map((domain) => (
            <DomainRow
              key={domain.id}
              domain={domain}
              busy={verifyDomain.isPending || makePrimary.isPending || removeDomain.isPending}
              // A 422 from verify means "still not pointing here", which is a
              // normal state, not an error worth a red banner.
              lastVerifyFailed={
                verifyDomain.variables === domain.id && verifyDomain.isError
              }
              onVerify={() => domain.id && verifyDomain.mutate(domain.id)}
              onMakePrimary={() => domain.id && makePrimary.mutate(domain.id)}
              onRemove={() => {
                if (domain.id && confirm(`Disconnect ${domain.hostname}?`)) {
                  removeDomain.mutate(domain.id);
                }
              }}
            />
          ))}
        </div>
      </Panel>
    </div>
  );
}

function DomainRow({
  domain,
  busy,
  lastVerifyFailed,
  onVerify,
  onMakePrimary,
  onRemove,
}: {
  domain: StoreDomain;
  busy: boolean;
  lastVerifyFailed: boolean;
  onVerify: () => void;
  onMakePrimary: () => void;
  onRemove: () => void;
}) {
  const verified = domain.is_verified ?? false;
  const txt = domain.dns_instructions?.txt;
  const cname = domain.dns_instructions?.cname;

  return (
    <div className="rounded border border-forest/20 p-4">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          <p className="text-sm font-semibold text-ink">
            {domain.hostname}
            {domain.is_primary && (
              <span className="ml-2 rounded bg-bone px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-ink/60">
                Primary
              </span>
            )}
          </p>
          <p className={`text-xs ${verified ? 'text-forest' : 'text-ink/60'}`}>
            {verified ? 'Verified and live' : 'Waiting on DNS'}
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {!verified && (
            <SecondaryButton onClick={onVerify} disabled={busy}>
              Check DNS
            </SecondaryButton>
          )}
          {verified && !domain.is_primary && (
            <SecondaryButton onClick={onMakePrimary} disabled={busy}>
              Make primary
            </SecondaryButton>
          )}
          <button
            type="button"
            onClick={onRemove}
            disabled={busy}
            className="rounded px-2 py-1.5 text-sm text-terracotta hover:underline disabled:opacity-50"
          >
            Disconnect
          </button>
        </div>
      </div>

      {!verified && (
        <div className="mt-4 space-y-3">
          <p className="text-sm text-ink/70">
            Add these two records at your DNS provider, then use <strong>Check DNS</strong>. Changes
            can take up to an hour to propagate.
          </p>
          <DnsRecord
            type="TXT"
            name={txt?.name}
            value={txt?.value}
            note="Proves you own the domain."
          />
          <DnsRecord
            type="CNAME"
            name={cname?.name}
            value={cname?.value}
            note="Routes visitors to your site."
          />
          {(lastVerifyFailed || domain.last_check_error) && (
            <p className="text-sm text-terracotta">
              {domain.last_check_error ?? 'The records were not found yet.'}
            </p>
          )}
        </div>
      )}
    </div>
  );
}

function DnsRecord({
  type,
  name,
  value,
  note,
}: {
  type: string;
  name?: string;
  value?: string;
  note: string;
}) {
  if (!name || !value) return null;

  return (
    <div className="rounded bg-bone/60 p-3 text-xs">
      <p className="font-semibold uppercase tracking-wide text-ink/60">{type}</p>
      <dl className="mt-1 grid gap-1 sm:grid-cols-[4rem_1fr]">
        <dt className="text-ink/60">Name</dt>
        <dd className="break-all font-mono">{name}</dd>
        <dt className="text-ink/60">Value</dt>
        <dd className="break-all font-mono">{value}</dd>
      </dl>
      <p className="mt-1 text-ink/50">{note}</p>
    </div>
  );
}
