import React, { useMemo, useState } from 'react';
import Icon from '../../shared/components/icon';

type ContactValues = {
  firstName: string;
  lastName: string;
  dateOfBirth: string;
  nationality: string;
  email: string;
  phone: string;
  message: string;
  street: string;
  houseNumber: string;
  box: string;
  postalCode: string;
  city: string;
  country: string;
  // traveler 1
  bookingType1: 'leisure' | 'business' | '';
  gender1: 'female' | 'male' | 'other' | '';

  // traveler 2
  bookingType2: 'leisure' | 'business' | '';
  gender2: 'female' | 'male' | 'other' | '';
};

type ContactErrors = Partial<Record<keyof ContactValues, string>>;
// const [touched, setTouched] = useState<Partial<Record<keyof ContactValues, boolean>>>({});

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const phoneRegex = /^[+()\-.\s0-9]{8,20}$/;

// Small helper: checks YYYY-MM-DD parses to a real date
const isValidISODate = (value: string) => {
  if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
  const d = new Date(value);
  return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === value;
};

// You can expand this list later (or load from API)
const nationalityOptions = [
  { value: '', label: 'Selecteer nationaliteit' },
  { value: 'BE', label: 'Belgisch' },
  { value: 'NL', label: 'Nederlands' },
  { value: 'FR', label: 'Frans' },
  { value: 'DE', label: 'Duits' },
  { value: 'UK', label: 'Brits' },
  { value: 'US', label: 'Amerikaans' }
];

const countryOptions = [
  { value: '', label: 'Selecteer land' },
  { value: 'BE', label: 'België' },
  { value: 'NL', label: 'Nederland' },
  { value: 'FR', label: 'Frankrijk' },
  { value: 'DE', label: 'Duitsland' },
  { value: 'LU', label: 'Luxemburg' },
  { value: 'UK', label: 'Verenigd Koninkrijk' }
];

const PersonalContactForm: React.FC = () => {
  const [values, setValues] = useState<ContactValues>({
    firstName: '',
    lastName: '',
    dateOfBirth: '',
    nationality: '',
    email: '',
    phone: '',
    message: '',
    street: '',
    houseNumber: '',
    box: '',
    postalCode: '',
    city: '',
    country: '',
    bookingType1: '',
    gender1: '',
    bookingType2: '',
    gender2: ''
  });

  const [touched, setTouched] = useState<Partial<Record<keyof ContactValues, boolean>>>({});
  const [errors, setErrors] = useState<ContactErrors>({});
  const [submitted, setSubmitted] = useState(false);
  const [isNationalityOpen, setIsNationalityOpen] = useState(false);
  const [isCountryOpen, setIsCountryOpen] = useState(false);

  const postalCodeRegex = /^[0-9A-Za-z\s-]{3,10}$/;

  const validate = (v: ContactValues): ContactErrors => {
    const e: ContactErrors = {};

    if (!v.firstName.trim()) e.firstName = 'Voornaam is verplicht.';
    if (!v.lastName.trim()) e.lastName = 'Achternaam is verplicht.';

    if (!v.dateOfBirth.trim()) e.dateOfBirth = 'Geboortedatum is verplicht.';
    else if (!isValidISODate(v.dateOfBirth.trim())) e.dateOfBirth = 'Vul een geldige geboortedatum in.';

    if (!v.nationality.trim()) e.nationality = 'Nationaliteit is verplicht.';

    if (!v.email.trim()) e.email = 'Email is verplicht.';
    else if (!emailRegex.test(v.email.trim())) e.email = 'Vul een geldig e-mailadres in.';

    if (v.phone.trim() && !phoneRegex.test(v.phone.trim())) {
      e.phone = 'Vul een geldig telefoonnummer in.';
    }

    if (!v.message.trim()) e.message = 'Bericht is verplicht.';
    else if (v.message.trim().length < 10) e.message = 'Bericht moet minstens 10 tekens zijn.';

    if (!v.street.trim()) e.street = 'Straat is verplicht.';
    if (!v.houseNumber.trim()) e.houseNumber = 'Nummer is verplicht.';

    if (!v.postalCode.trim()) e.postalCode = 'Postcode is verplicht.';
    else if (!postalCodeRegex.test(v.postalCode.trim())) e.postalCode = 'Vul een geldige postcode in.';

    if (!v.city.trim()) e.city = 'Woonplaats is verplicht.';
    if (!v.country.trim()) e.country = 'Land is verplicht.';

    if (!v.gender1) e.gender1 = 'Geslacht is verplicht.';
    if (!v.gender2) e.gender2 = 'Geslacht is verplicht.';

    if (!v.bookingType1) e.bookingType1 = 'Type boeking is verplicht.';
    if (!v.bookingType2) e.bookingType2 = 'Type boeking is verplicht.';

    return e;
  };

  const currentErrors = useMemo(() => validate(values), [values]);

  const setField = <K extends keyof ContactValues>(key: K, val: ContactValues[K]) => {
    setValues((p) => ({ ...p, [key]: val }));
    if (submitted || touched[key]) {
      setErrors(validate({ ...values, [key]: val } as ContactValues));
    }
  };

  const onBlur = (key: keyof ContactValues) => {
    setTouched((p) => ({ ...p, [key]: true }));
    setErrors(validate(values));
  };

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitted(true);

    const eMap = validate(values);
    setErrors(eMap);

    if (Object.keys(eMap).length > 0) return;

    console.log('Contact form submit:', values);

    setValues({
      firstName: '',
      lastName: '',
      dateOfBirth: '',
      nationality: '',
      email: '',
      phone: '',
      message: '',
      street: '',
      houseNumber: '',
      box: '',
      postalCode: '',
      city: '',
      country: '',
      bookingType1: '',
      gender1: '',
      bookingType2: '',
      gender2: ''
    });
    setTouched({});
    setErrors({});
    setSubmitted(false);
  };

  const showError = (key: keyof ContactValues) => {
    const shouldShow = submitted || touched[key];
    return shouldShow ? errors[key] : undefined;
  };

  return (
    <div className="content content--background">
      <div className="content__container content__container--medium">
        <div className="content__title__row">
          <h2 className="content__title">Persoonlijke informatie</h2>
        </div>

        <form className="contact" noValidate onSubmit={onSubmit}>
          <div className="contact__card contact__card--headbooker">
            <div className="contact__title">
              <Icon name="ui-info-circle" width={24} height={24} />
              <h4>Gaat de hoofdboeker mee op reis?</h4>
            </div>

            <div className="contact__form">
              <div className="radiobutton-group">
                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input type="radio" name="headBooker" value="yes" className="radiobutton__input" defaultChecked={true} />
                    <span>Ja</span>
                  </label>
                </div>

                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input type="radio" name="headBooker" value="no" className="radiobutton__input" />
                    <span>Nee</span>
                  </label>
                </div>
              </div>
            </div>
          </div>
          <div className="contact__card">
            <div className="contact__title">
              <Icon name="ui-user" width={24} height={24} />
              <h4>Reiziger 1</h4>
              <span>volwassenen, hoofdboeker</span>
            </div>

            <div
              className="contact__radio"
              role="group"
              aria-labelledby="bookingType-label"
              aria-invalid={!!showError('bookingType1')}
              aria-describedby="bookingType-error">
              <span id="bookingType-label">Type boeking{/** add * if required */}</span>

              <div className="radiobutton-group">
                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="bookingType1"
                      value="leisure"
                      className="radiobutton__input"
                      checked={values.bookingType1 === 'leisure'}
                      onChange={() => setField('bookingType1', 'leisure')}
                      onBlur={() => onBlur('bookingType1')}
                    />
                    <span>Plezier</span>
                  </label>
                </div>

                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="bookingType1"
                      value="business"
                      className="radiobutton__input"
                      checked={values.bookingType1 === 'business'}
                      onChange={() => setField('bookingType1', 'business')}
                      onBlur={() => onBlur('bookingType1')}
                    />
                    <span>Zakelijk</span>
                  </label>
                </div>
              </div>

              {showError('bookingType1') && (
                <span className="contact__radio--error" id="bookingType-error">
                  {showError('bookingType1')}
                </span>
              )}
            </div>

            <div className="contact__radio" role="group" aria-labelledby="gender-label" aria-invalid={!!showError('gender1')} aria-describedby="gender-error">
              <span id="gender-label">Geslacht*</span>

              <div className="radiobutton-group">
                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="gender1"
                      value="female"
                      className="radiobutton__input"
                      checked={values.gender1 === 'female'}
                      onChange={() => setField('gender1', 'female')}
                      onBlur={() => onBlur('gender1')}
                    />
                    <span>Vrouw</span>
                  </label>
                </div>

                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="gender1"
                      value="male"
                      className="radiobutton__input"
                      checked={values.gender1 === 'male'}
                      onChange={() => setField('gender1', 'male')}
                      onBlur={() => onBlur('gender1')}
                    />
                    <span>Man</span>
                  </label>
                </div>

                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="gender1"
                      value="other"
                      className="radiobutton__input"
                      checked={values.gender1 === 'other'}
                      onChange={() => setField('gender1', 'other')}
                      onBlur={() => onBlur('gender1')}
                    />
                    <span>Anders</span>
                  </label>
                </div>
              </div>

              {showError('gender1') && (
                <span className="contact__radio--error" id="gender-error">
                  {showError('gender1')}
                </span>
              )}
            </div>

            <div className="contact__form">
              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Voornaam*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Enter your name"
                  aria-label="Enter your name"
                  value={values.firstName}
                  onChange={(e) => setField('firstName', e.target.value)}
                  onBlur={() => onBlur('firstName')}
                  aria-invalid={!!showError('firstName')}
                  aria-describedby="firstName-error"
                />
                {showError('firstName') && (
                  <span className="contact__error" id="firstName-error">
                    {showError('firstName')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Achternaam*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Enter your last name"
                  aria-label="Enter your last name"
                  value={values.lastName}
                  onChange={(e) => setField('lastName', e.target.value)}
                  onBlur={() => onBlur('lastName')}
                  aria-invalid={!!showError('lastName')}
                  aria-describedby="lastName-error"
                />
                {showError('lastName') && (
                  <span className="contact__error" id="lastName-error">
                    {showError('lastName')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Geboortedatum*</span>
                <input
                  type="date"
                  className="contact__input"
                  aria-label="Enter your date of birth"
                  value={values.dateOfBirth}
                  onChange={(e) => setField('dateOfBirth', e.target.value)}
                  onBlur={() => onBlur('dateOfBirth')}
                  aria-invalid={!!showError('dateOfBirth')}
                  aria-describedby="dateOfBirth-error"
                />
                {showError('dateOfBirth') && (
                  <span className="contact__error" id="dateOfBirth-error">
                    {showError('dateOfBirth')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Nationaliteit*</span>

                <div className={`contact__dropdown ${showError('nationality') ? 'contact__dropdown--error' : ''}`}>
                  <button
                    type="button"
                    className="contact__dropdown__trigger"
                    aria-haspopup="listbox"
                    aria-expanded={isNationalityOpen}
                    onClick={() => setIsNationalityOpen((o) => !o)}
                    onBlur={() => {
                      setIsNationalityOpen(false);
                      onBlur('nationality');
                    }}>
                    <span>{nationalityOptions.find((o) => o.value === values.nationality)?.label ?? 'Selecteer nationaliteit'}</span>

                    <Icon name="ui-chevron" width={16} height={16} />
                  </button>

                  {isNationalityOpen && (
                    <ul className="contact__dropdown__menu" role="listbox">
                      {nationalityOptions.map((option) => (
                        <li key={option.value}>
                          <button
                            type="button"
                            className={`contact__dropdown__option ${values.nationality === option.value ? 'contact__dropdown__option--active' : ''}`}
                            role="option"
                            aria-selected={values.nationality === option.value}
                            onMouseDown={() => {
                              // onMouseDown prevents blur-before-click
                              setField('nationality', option.value);
                              setIsNationalityOpen(false);
                            }}>
                            {option.label}
                          </button>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>

                {showError('nationality') && (
                  <span className="contact__error" id="nationality-error">
                    {showError('nationality')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Email*</span>
                <input
                  type="email"
                  className="contact__input"
                  placeholder="Enter your email"
                  aria-label="Enter your email"
                  value={values.email}
                  onChange={(e) => setField('email', e.target.value)}
                  onBlur={() => onBlur('email')}
                  aria-invalid={!!showError('email')}
                  aria-describedby="email-error"
                />
                {showError('email') && (
                  <span className="contact__error" id="email-error">
                    {showError('email')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Telefoonnummer</span>
                <input
                  type="tel"
                  className="contact__input"
                  placeholder="Enter your phone number"
                  aria-label="Enter your phone number"
                  value={values.phone}
                  onChange={(e) => setField('phone', e.target.value)}
                  onBlur={() => onBlur('phone')}
                  aria-invalid={!!showError('phone')}
                  aria-describedby="phone-error"
                />
                {showError('phone') && (
                  <span className="contact__error" id="phone-error">
                    {showError('phone')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--2">
                <span className="contact__form__label">Straat*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Straatnaam"
                  aria-label="Straat"
                  value={values.street}
                  onChange={(e) => setField('street', e.target.value)}
                  onBlur={() => onBlur('street')}
                  aria-invalid={!!showError('street')}
                  aria-describedby="street-error"
                />
                {showError('street') && (
                  <span className="contact__error" id="street-error">
                    {showError('street')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--4">
                <span className="contact__form__label">Nummer*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Nr"
                  aria-label="Huisnummer"
                  value={values.houseNumber}
                  onChange={(e) => setField('houseNumber', e.target.value)}
                  onBlur={() => onBlur('houseNumber')}
                  aria-invalid={!!showError('houseNumber')}
                  aria-describedby="houseNumber-error"
                />
                {showError('houseNumber') && (
                  <span className="contact__error" id="houseNumber-error">
                    {showError('houseNumber')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--4">
                <span className="contact__form__label">Bus</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Bus"
                  aria-label="Bus"
                  value={values.box}
                  onChange={(e) => setField('box', e.target.value)}
                  onBlur={() => onBlur('box')}
                  aria-invalid={!!showError('box')}
                  aria-describedby="box-error"
                />
                {showError('box') && (
                  <span className="contact__error" id="box-error">
                    {showError('box')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Postcode*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Postcode"
                  aria-label="Postcode"
                  value={values.postalCode}
                  onChange={(e) => setField('postalCode', e.target.value)}
                  onBlur={() => onBlur('postalCode')}
                  aria-invalid={!!showError('postalCode')}
                  aria-describedby="postalCode-error"
                />
                {showError('postalCode') && (
                  <span className="contact__error" id="postalCode-error">
                    {showError('postalCode')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Woonplaats*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Woonplaats"
                  aria-label="Woonplaats"
                  value={values.city}
                  onChange={(e) => setField('city', e.target.value)}
                  onBlur={() => onBlur('city')}
                  aria-invalid={!!showError('city')}
                  aria-describedby="city-error"
                />
                {showError('city') && (
                  <span className="contact__error" id="city-error">
                    {showError('city')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--3">
                <span className="contact__form__label">Land*</span>

                <div className={`contact__dropdown ${showError('country') ? 'contact__dropdown--error' : ''}`}>
                  <button
                    type="button"
                    className="contact__dropdown__trigger"
                    aria-haspopup="listbox"
                    aria-expanded={isCountryOpen}
                    aria-describedby="country-error"
                    onClick={() => setIsCountryOpen((o) => !o)}
                    onBlur={() => {
                      setIsCountryOpen(false);
                      onBlur('country');
                    }}>
                    <span>{countryOptions.find((o) => o.value === values.country)?.label ?? 'Selecteer land'}</span>
                    <Icon name="ui-chevron" width={16} height={16} />
                  </button>

                  {isCountryOpen && (
                    <ul className="contact__dropdown__menu" role="listbox">
                      {countryOptions.map((option) => (
                        <li key={option.value}>
                          <button
                            type="button"
                            className={`contact__dropdown__option ${values.country === option.value ? 'contact__dropdown__option--active' : ''}`}
                            role="option"
                            aria-selected={values.country === option.value}
                            onMouseDown={() => {
                              // Prevent blur-before-click
                              setField('country', option.value);
                              setIsCountryOpen(false);
                            }}>
                            {option.label}
                          </button>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>

                {showError('country') && (
                  <span className="contact__error" id="country-error">
                    {showError('country')}
                  </span>
                )}
              </label>
            </div>
          </div>

          <div className="contact__card">
            <div className="contact__title">
              <Icon name="ui-user" width={24} height={24} />
              <h4>Reiziger 2</h4>
              <span>volwassenen</span>
            </div>

            <div className="contact__radio" role="group" aria-labelledby="gender-label" aria-invalid={!!showError('gender1')} aria-describedby="gender-error">
              <span id="gender-label">Geslacht*</span>

              <div className="radiobutton-group">
                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="gender2"
                      value="female"
                      className="radiobutton__input"
                      checked={values.gender2 === 'female'}
                      onChange={() => setField('gender2', 'female')}
                      onBlur={() => onBlur('gender2')}
                    />
                    <span>Vrouw</span>
                  </label>
                </div>

                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="gender2"
                      value="male"
                      className="radiobutton__input"
                      checked={values.gender2 === 'male'}
                      onChange={() => setField('gender2', 'male')}
                      onBlur={() => onBlur('gender2')}
                    />
                    <span>Man</span>
                  </label>
                </div>

                <div className="radiobutton">
                  <label className="radiobutton__label">
                    <input
                      type="radio"
                      name="gender2"
                      value="other"
                      className="radiobutton__input"
                      checked={values.gender2 === 'other'}
                      onChange={() => setField('gender2', 'other')}
                      onBlur={() => onBlur('gender2')}
                    />
                    <span>Anders</span>
                  </label>
                </div>
              </div>

              {showError('gender2') && (
                <span className="contact__radio--error" id="gender-error">
                  {showError('gender2')}
                </span>
              )}
            </div>

            <div className="contact__form">
              <label className="contact__form__group contact__form__group--2">
                <span className="contact__form__label">Voornaam*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Enter your name"
                  aria-label="Enter your name"
                  value={values.firstName}
                  onChange={(e) => setField('firstName', e.target.value)}
                  onBlur={() => onBlur('firstName')}
                  aria-invalid={!!showError('firstName')}
                  aria-describedby="firstName-error"
                />
                {showError('firstName') && (
                  <span className="contact__error" id="firstName-error">
                    {showError('firstName')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--2">
                <span className="contact__form__label">Achternaam*</span>
                <input
                  type="text"
                  className="contact__input"
                  placeholder="Enter your last name"
                  aria-label="Enter your last name"
                  value={values.lastName}
                  onChange={(e) => setField('lastName', e.target.value)}
                  onBlur={() => onBlur('lastName')}
                  aria-invalid={!!showError('lastName')}
                  aria-describedby="lastName-error"
                />
                {showError('lastName') && (
                  <span className="contact__error" id="lastName-error">
                    {showError('lastName')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--2">
                <span className="contact__form__label">Geboortedatum*</span>
                <input
                  type="date"
                  className="contact__input"
                  aria-label="Enter your date of birth"
                  value={values.dateOfBirth}
                  onChange={(e) => setField('dateOfBirth', e.target.value)}
                  onBlur={() => onBlur('dateOfBirth')}
                  aria-invalid={!!showError('dateOfBirth')}
                  aria-describedby="dateOfBirth-error"
                />
                {showError('dateOfBirth') && (
                  <span className="contact__error" id="dateOfBirth-error">
                    {showError('dateOfBirth')}
                  </span>
                )}
              </label>

              <label className="contact__form__group contact__form__group--2">
                <span className="contact__form__label">Nationaliteit*</span>

                <div className={`contact__dropdown ${showError('nationality') ? 'contact__dropdown--error' : ''}`}>
                  <button
                    type="button"
                    className="contact__dropdown__trigger"
                    aria-haspopup="listbox"
                    aria-expanded={isNationalityOpen}
                    onClick={() => setIsNationalityOpen((o) => !o)}
                    onBlur={() => {
                      setIsNationalityOpen(false);
                      onBlur('nationality');
                    }}>
                    <span>{nationalityOptions.find((o) => o.value === values.nationality)?.label ?? 'Selecteer nationaliteit'}</span>

                    <Icon name="ui-chevron" width={16} height={16} />
                  </button>

                  {isNationalityOpen && (
                    <ul className="contact__dropdown__menu" role="listbox">
                      {nationalityOptions.map((option) => (
                        <li key={option.value}>
                          <button
                            type="button"
                            className={`contact__dropdown__option ${values.nationality === option.value ? 'contact__dropdown__option--active' : ''}`}
                            role="option"
                            aria-selected={values.nationality === option.value}
                            onMouseDown={() => {
                              // onMouseDown prevents blur-before-click
                              setField('nationality', option.value);
                              setIsNationalityOpen(false);
                            }}>
                            {option.label}
                          </button>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>

                {showError('nationality') && (
                  <span className="contact__error" id="nationality-error">
                    {showError('nationality')}
                  </span>
                )}
              </label>
            </div>
          </div>

          <div className="contact__form__actions">
            <button type="submit" className="cta cta--primary">
              Send message
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default PersonalContactForm;
