import { useNavigate } from 'react-router-dom';
import { useForm, FieldError } from 'react-hook-form';
import { ValidationError } from './ValidationError';

type Contact = {
  name: string;
  email: string;
  reason: string;
  notes: string;
};

export function ContactPage() {
  const fieldStyle = 'flex flex-col mb-2';
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<Contact>({
    mode: 'onBlur',
    reValidateMode: 'onBlur',
  });
  const navigate = useNavigate();
  function onSubmit(contact: Contact) {
    console.log('Submitted details:', contact);
    navigate(`/thank-you/${contact.name}`);
  }
  function getEditorStyle(fieldError: FieldError | undefined) {
    return fieldError ? 'border-red-500' : '';
  }

  return (
    <div className="flex flex-col py-10 max-w-md mx-auto">
      <h2 className="text-3xl font-bold underline mb-3">Skontaktuj się z nami</h2>
      <p className="mb-3">
        Jeśli podasz szczegóły, odezwiemy się do Ciebie tak szybko, jak to możliwe.
      </p>
      <form noValidate onSubmit={handleSubmit(onSubmit)}>
        <div className={fieldStyle}>
          <label htmlFor="name">Imię</label>
          <input
            type="text"
            id="name"
            {...register('name', {
              required: 'Musisz podać swoje imię',
            })}
            className={getEditorStyle(errors.name)}
          />
          <ValidationError fieldError={errors.name} />
        </div>
        <div className={fieldStyle}>
          <label htmlFor="email">Adres e-mail</label>
          <input
            type="email"
            id="email"
            {...register('email', {
              required: 'Musisz podac swój adres e-mail',
              pattern: {
                value: /\S+@\S+\.\S+/,
                message: 'Wprowadź poprawidłowy format emaila',
              },
            })}
            className={getEditorStyle(errors.email)}
          />
          <ValidationError fieldError={errors.email} />
        </div>
        <div className={fieldStyle}>
          <label htmlFor="reason">Powód kontaktu</label>
          <select
            id="reason"
            {...register('reason', {
              required: 'Musisz podać powód kontaktu',
            })}
            className={getEditorStyle(errors.reason)}
          >
            <option value=""></option>
            <option value="Support">Wsparcie</option>
            <option value="Feedback">Opienie</option>
            <option value="Other">Inne</option>
          </select>
          <ValidationError fieldError={errors.reason} />
        </div>
        <div className={fieldStyle}>
          <label htmlFor="notes">Dodatkowe informacje</label>
          <textarea id="notes" {...register('notes')} />
        </div>
        <div>
          <button type="submit" className="mt-2 h-10 px-6 font-semibold bg-black text-white">
            Submit
          </button>
        </div>
      </form>
    </div>
  );
}
