'use client';

import { useState, type FormEvent } from 'react';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useCartStore } from '@/lib/cart-store';
import type { Locale } from '@/i18n/config';

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

export function QuoteForm({ locale }: { locale: Locale }) {
  const t = useTranslations('quoteForm');
  const tCart = useTranslations('cart');
  const { items, removeItem, clear } = useCartStore();
  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') ?? '');
    if (fullName.length < 2) errs.fullName = t('nameTooShort');
    if (!emailRe.test(email)) errs.email = t('invalidEmail');
    if (!phoneRe.test(phone)) errs.phone = t('invalidPhone');
    if (message.length > 2000) 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');
    clear();
  }

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

  return (
    <div className="grid gap-10 lg:grid-cols-[1fr_320px]">
      <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" required error={errors.phone} />
        </div>
        <Field name="city" label={t('city')} />
        <FieldTextarea
          name="message"
          label={t('message')}
          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>

      <aside className="h-fit rounded-2xl border border-graphite-800/10 bg-white p-5">
        <h2 className="font-display text-base font-semibold">{tCart('title')}</h2>
        {items.length === 0 ? (
          <p className="mt-3 text-sm text-graphite-900/50">{tCart('empty')}</p>
        ) : (
          <ul className="mt-3 space-y-3">
            {items.map((item) => (
              <li key={item.productId} className="flex items-center gap-3 text-sm">
                <div className="relative h-12 w-12 flex-shrink-0 overflow-hidden rounded-md bg-graphite-900/5">
                  {item.image && (
                    <Image src={item.image} alt={item.name} fill className="object-cover" sizes="48px" />
                  )}
                </div>
                <span className="flex-1">
                  {item.name} × {item.quantity}
                </span>
                <button
                  type="button"
                  onClick={() => removeItem(item.productId)}
                  className="text-graphite-900/40 hover:text-copper-600"
                  aria-label={tCart('remove')}
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </li>
            ))}
          </ul>
        )}
      </aside>
    </div>
  );
}

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={4}
        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>
  );
}