'use client';

import * as FieldIcons from './Icons';

import { useState } from 'react';
import { AlertIcon, CheckCircleIcon, MailIcon, Spinner } from './Icons';

/** "This is me" form. Submitting emails a confirmation link; nothing is granted until staff approve. */
export function ClaimForm({ slug, name }: { slug: string; name: string }) {
  const [state, setState] = useState<'idle' | 'sending' | 'done' | 'error'>('idle');
  const [msg, setMsg] = useState('');

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    setState('sending');
    const res = await fetch('/api/v1/claims/', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({
        lawyerSlug: slug,
        name: String(fd.get('name') ?? '').trim(),
        email: String(fd.get('email') ?? '').trim(),
        phone: String(fd.get('phone') ?? '').trim(),
        licenseNumber: String(fd.get('licenseNumber') ?? '').trim(),
        message: String(fd.get('message') ?? '').trim(),
        consent: fd.get('consent') === 'on',
        website: fd.get('website') || undefined,
      }),
    }).catch(() => null);
    const data = await res?.json().catch(() => null);
    if (res?.ok) {
      setState('done');
      setMsg(data?.message ?? 'Check your email to continue.');
    } else {
      setState('error');
      const issue = Array.isArray(data?.issues) && data.issues[0]?.message;
      setMsg(res?.status === 429 ? 'Too many attempts from this connection. Try again in an hour.' : (issue || data?.message || (res ? 'The claim was not sent. Check the details and try again.' : 'The connection failed. Try again.')));
    }
  }

  if (state === 'done')
    return (
      <div role="status" className="card fade-up space-y-3 p-6">
        <p className="flex items-center gap-2 font-semibold text-ledger">
          <CheckCircleIcon className="h-5 w-5" /> Almost done — check your inbox
        </p>
        <p className="text-sm leading-relaxed text-ink-2">{msg}</p>
        <p className="flex items-start gap-2 text-xs text-muted">
          <MailIcon className="mt-0.5 h-3.5 w-3.5" /> On the confirmation page you can upload proof such as your bar card to speed up the review.
        </p>
      </div>
    );

  return (
    <form onSubmit={onSubmit} className="card space-y-4 p-6">
      <div className="grid gap-4 sm:grid-cols-2">
        <label className="block">
          <span className="field-label"><FieldIcons.UserIcon />Your full name</span>
          <input name="name" required minLength={2} maxLength={150} autoComplete="name" defaultValue={name} className="field" />
        </label>
        <label className="block">
          <span className="field-label"><FieldIcons.MailIcon />Work email</span>
          <input name="email" type="email" required maxLength={255} autoComplete="email" className="field" />
          <span className="mt-1 block text-xs text-muted">Your firm address (not Gmail/Outlook) is the fastest way to be verified.</span>
        </label>
        <label className="block">
          <span className="field-label">
            Phone <span className="font-normal text-muted">(optional)</span>
          </span>
          <input name="phone" type="tel" maxLength={60} autoComplete="tel" className="field" />
        </label>
        <label className="block">
          <span className="field-label">
            Licence / bar number <span className="font-normal text-muted">(recommended)</span>
          </span>
          <input name="licenseNumber" maxLength={100} className="field" />
        </label>
      </div>
      <label className="block">
        <span className="field-label">
          Anything our team should know? <span className="font-normal text-muted">(optional)</span>
        </span>
        <textarea name="message" rows={3} maxLength={2000} className="field" />
      </label>
      <label className="flex items-start gap-2.5 text-sm text-ink-2">
        <input name="consent" type="checkbox" required className="mt-1" />
        <span>
          I am <strong>{name}</strong>, or authorised to manage this profile, and I understand that false claims are rejected and may be reported to the licensing body.
        </span>
      </label>
      <input name="website" tabIndex={-1} autoComplete="off" className="hidden" aria-hidden />
      {state === 'error' && (
        <p role="alert" className="flex items-start gap-2 text-sm text-danger">
          <AlertIcon className="mt-0.5 h-4 w-4" />
          {msg}
        </p>
      )}
      <button className="btn btn-primary" disabled={state === 'sending'}>
        {state === 'sending' ? (
          <>
            <Spinner /> Sending…
          </>
        ) : (
          'Claim this profile'
        )}
      </button>
    </form>
  );
}
