'use client';

import { useState, type FormEvent } from 'react';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/button';
import type { Locale } from '@/i18n/config';

const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const phoneRe = /^[+0-9][0-9 .()-]{5,}$/;

export function ContactForm({ locale }: { locale: Locale }) {
  const t = useTranslations('contactForm');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [errors, setErrors] = useState<Record<string, string>>({});

  function validate(form: FormData) {
    const errs: Record<string, string> = {};
    const fullName = String(form.get('fullName') ?? '').trim();
    const email = String(form.get('email') ?? '').trim();
    const phone = String(form.get('phone') ?? '').trim();
    const message = String(form.get('message') ?? '').trim();
    if (fullName.length < 2) errs.fullName = t('nameTooShort');
    if (!emailRe.test(email)) errs.email = t('invalidEmail');
    if (phone && !phoneRe.test(phone)) errs.phone = t('invalidPhone');
    if (message.length === 0) errs.message = t('messageRequired');
    if (message.length > 3000) errs.message = t('messageTooLong');
    return errs;
  }

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = new FormData(e.currentTarget);
    const errs = validate(form);
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setStatus('loading');
    await new Promise((r) => setTimeout(r, 600));
    setStatus('success');
    e.currentTarget.reset();
  }

  if (status === 'success') {
    return <p className="rounded-xl bg-volt-500/10 p-4 text-volt-600">{t('success')}</p>;
  }

  return (
    <form onSubmit={handleSubmit} noValidate className="space-y-4">
      <Field name="fullName" label={t('fullName')} required error={errors.fullName} />
      <div className="grid gap-4 sm:grid-cols-2">
        <Field name="email" label={t('email')} type="email" required error={errors.email} />
        <Field name="phone" label={t('phone')} type="tel" error={errors.phone} />
      </div>
      <Field name="subject" label={t('subject')} />
      <FieldTextarea name="message" label={t('message')} required error={errors.message} />
      {status === 'error' && <p className="text-sm text-copper-600">{t('error')}</p>}
      <Button type="submit" disabled={status === 'loading'}>
        {t('submit')}
      </Button>
    </form>
  );
}

function Field({
  name,
  label,
  type = 'text',
  required,
  error
}: {
  name: string;
  label: string;
  type?: string;
  required?: boolean;
  error?: string;
}) {
  return (
    <div>
      <label htmlFor={name} className="mb-1 block text-sm font-medium">
        {label}
        {required && (
          <span className="text-copper-600" aria-hidden="true">
            {' '}
            *
          </span>
        )}
      </label>
      <input
        id={name}
        name={name}
        type={type}
        required={required}
        aria-required={required}
        aria-invalid={Boolean(error)}
        className="w-full rounded-xl border border-graphite-800/20 bg-white px-4 py-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-volt-500"
      />
      {error && <p className="mt-1 text-xs text-copper-600">{error}</p>}
    </div>
  );
}

function FieldTextarea({
  name,
  label,
  required,
  error
}: {
  name: string;
  label: string;
  required?: boolean;
  error?: string;
}) {
  return (
    <div>
      <label htmlFor={name} className="mb-1 block text-sm font-medium">
        {label}
        {required && (
          <span className="text-copper-600" aria-hidden="true">
            {' '}
            *
          </span>
        )}
      </label>
      <textarea
        id={name}
        name={name}
        rows={5}
        required={required}
        aria-required={required}
        aria-invalid={Boolean(error)}
        className="w-full rounded-xl border border-graphite-800/20 bg-white px-4 py-3 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-volt-500"
      />
      {error && <p className="mt-1 text-xs text-copper-600">{error}</p>}
    </div>
  );
}