'use client';

import * as FieldIcons from './Icons';

import { useState } from 'react';
import { AlertIcon, CheckCircleIcon, FlagIcon, Spinner } from './Icons';

export function ReportForm({ entityType, entityId, label = 'Report inaccurate information' }: { entityType: 'lawyer' | 'firm' | 'ranking'; entityId: number; label?: string }) {
  const [open, setOpen] = useState(false);
  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);
    const message = String(fd.get('message') ?? '').trim();
    const email = String(fd.get('email') ?? '').trim();
    if (message.length < 10) {
      setState('error');
      setMsg('Describe the problem in at least 10 characters.');
      return;
    }
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) {
      setState('error');
      setMsg('That email address does not look right. Leave it empty or correct it.');
      return;
    }
    setState('sending');
    const res = await fetch('/api/v1/corrections/', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({
        entityType,
        entityId,
        field: fd.get('field') || undefined,
        message,
        reporterEmail: email || undefined,
        isDispute: fd.get('dispute') === 'on',
        website: fd.get('website') || undefined,
      }),
    }).catch(() => null);
    const data = await res?.json().catch(() => null);
    if (res?.ok) {
      setState('done');
      setMsg(data?.message ?? 'Thank you — the data team will review your report.');
    } else {
      setState('error');
      setMsg(res?.status === 429 ? 'Too many reports from this connection. Try again later.' : res ? 'The report was not sent. Check the details and try again.' : 'The connection failed. Try again.');
    }
  }

  if (!open)
    return (
      <button type="button" onClick={() => setOpen(true)} className="inline-flex items-center gap-1.5 rounded-md text-sm font-medium text-ink-2 underline decoration-rule-strong underline-offset-4 transition-colors hover:text-danger hover:decoration-current">
        <FlagIcon className="h-4 w-4" />
        {label}
      </button>
    );
  if (state === 'done')
    return (
      <p role="status" className="fade-up flex items-start gap-2 rounded-lg border border-ledger/30 bg-ledger-tint px-3 py-2.5 text-sm text-ledger">
        <CheckCircleIcon className="mt-0.5 h-4 w-4" />
        {msg}
      </p>
    );
  return (
    <form onSubmit={onSubmit} noValidate className="card fade-up w-full max-w-xl space-y-4 p-5 text-left">
      <p className="flex items-center gap-2 font-semibold text-ink">
        <FlagIcon className="h-4 w-4 text-danger" /> {label}
      </p>
      <label className="block">
        <span className="field-label"><FieldIcons.FileTextIcon />What is wrong?</span>
        <select name="field" className="field">
          <option value="">General</option>
          <option value="contact">Contact details</option>
          <option value="practice_areas">Practice areas</option>
          <option value="license">Licence or credentials</option>
          <option value="ranking">Ranking</option>
          <option value="identity">This is not me / duplicate profile</option>
        </select>
      </label>
      <label className="block">
        <span className="field-label"><FieldIcons.FileTextIcon />Details</span>
        <textarea name="message" rows={3} required minLength={10} maxLength={2000} className="field" placeholder="What should it say instead, and where can we check it?" />
      </label>
      <label className="block">
        <span className="field-label">
          Your email <span className="font-normal text-muted">(optional, for follow-up)</span>
        </span>
        <input name="email" type="email" inputMode="email" autoComplete="email" className="field" />
      </label>
      <label className="flex items-center gap-2.5 text-sm text-ink-2">
        <input name="dispute" type="checkbox" /> I am this professional and dispute this information
      </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>
      )}
      <div className="flex flex-wrap gap-2">
        <button className="btn btn-primary btn-sm" disabled={state === 'sending'}>
          {state === 'sending' ? (
            <>
              <Spinner /> Sending…
            </>
          ) : (
            'Send report'
          )}
        </button>
        <button
          type="button"
          className="btn btn-quiet btn-sm"
          onClick={() => {
            setOpen(false);
            setState('idle');
          }}
        >
          Cancel
        </button>
      </div>
    </form>
  );
}
