'use client';

import * as ActionIcons from './Icons';

import { useActionState } from 'react';
import { rotateWebhookSecret, saveWebhook, type SecretState } from '@/app/actions';
import { AlertIcon, CheckCircleIcon, Spinner } from './Icons';

function Secret({ secret }: { secret: string }) {
  return (
    <div className="space-y-2 rounded-lg border border-brass/40 bg-brass-soft/40 p-3 text-sm">
      <p className="font-semibold">Copy your signing secret now — it won’t be shown again.</p>
      <code className="num block select-all break-all rounded bg-surface px-2 py-1.5 font-mono text-xs">{secret}</code>
      <button type="button" className="btn btn-quiet btn-xs" onClick={() => navigator.clipboard?.writeText(secret)}>
        <ActionIcons.CopyIcon />Copy
      </button>
    </div>
  );
}

function Notes({ state }: { state: SecretState }) {
  return (
    <>
      {state.error && (
        <p role="alert" className="flex items-start gap-2 text-sm text-danger">
          <AlertIcon className="mt-0.5 h-4 w-4" /> {state.error}
        </p>
      )}
      {state.done && state.message && (
        <p role="status" className="flex items-start gap-2 text-sm text-ledger">
          <CheckCircleIcon className="mt-0.5 h-4 w-4" /> {state.message}
        </p>
      )}
      {state.secret && <Secret secret={state.secret} />}
    </>
  );
}

export function WebhookUrlForm({ current }: { current: string | null }) {
  const [state, action, pending] = useActionState<SecretState, FormData>(saveWebhook, {});
  return (
    <form action={action} className="space-y-3 p-5 text-sm">
      <label className="block">
        <span className="field-label"><ActionIcons.GlobeIcon />Webhook URL</span>
        <input name="webhookUrl" type="url" maxLength={500} defaultValue={current ?? ''} placeholder="https://crm.example.com/hooks/justice-choice" className="field" />
        <span className="mt-1 block text-xs text-muted">HTTPS only, on a public host. Leave empty and save to stop webhook delivery (enquiries still appear here).</span>
      </label>
      <Notes state={state} />
      <button disabled={pending} className="btn btn-primary btn-sm">
        {pending ? (
          <>
            <Spinner className="h-3.5 w-3.5" /> Checking…
          </>
        ) : (
          'Save webhook'
        )}
      </button>
    </form>
  );
}

export function RotateSecretForm({ hasSecret }: { hasSecret: boolean }) {
  const [state, action, pending] = useActionState<SecretState>(rotateWebhookSecret, {});
  return (
    <form action={action} className="space-y-3 p-5 text-sm">
      <p className="text-ink-2">{hasSecret ? 'A signing secret is set. Rotate it if it may have leaked; update your receiver straight away.' : 'No signing secret yet — one is created when you save a webhook URL.'}</p>
      <Notes state={state} />
      <button disabled={pending} className="btn btn-quiet btn-sm" onClick={(e) => !window.confirm('Create a new secret? The current one stops working immediately.') && e.preventDefault()}>
        {pending ? <Spinner className="h-3.5 w-3.5" /> : null} Rotate signing secret
      </button>
    </form>
  );
}
