import { useState } from 'react';
import { IoIosArrowBack, IoIosBusiness, IoIosPeople } from 'react-icons/io';
import sharedStyles from '../../core/PageManager/pages.module.css';
import styles from './SpeechSignUp.module.css';
import { useLanguage } from '../../providers/language/LanguageContext';

interface SpeechSignUpProps {
  onBack: () => void;
  onSubmit: (data: MandateData) => void;
}

interface MandateData {
  id: string;
  mandate_general: {
    company_name: string;
    industry: string;
    contact_info: {
      email: string;
      phone: string;
      street: string;
      postal_code: string;
      city: string;
      country: string;
    };
    business_hours: string;
    timezone: string;
  };
  setup_contacts: boolean;
}

function SpeechSignUp({ onBack, onSubmit }: SpeechSignUpProps) {
  const { t } = useLanguage();
  
  const [formData, setFormData] = useState<MandateData>({
    id: crypto.randomUUID(),
    mandate_general: {
      company_name: '',
      industry: '',
      contact_info: {
        email: '',
        phone: '',
        street: '',
        postal_code: '',
        city: '',
        country: ''
      },
      business_hours: '9:00-17:00',
      timezone: 'Europe/Zurich'
    },
    setup_contacts: false
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [focusedFields, setFocusedFields] = useState<Set<string>>(new Set());

  const handleInputChange = (field: string, value: string) => {
    if (field.startsWith('contact_info.')) {
      const contactField = field.split('.')[1] as keyof typeof formData.mandate_general.contact_info;
      setFormData(prev => ({
        ...prev,
        mandate_general: {
          ...prev.mandate_general,
          contact_info: {
            ...prev.mandate_general.contact_info,
            [contactField]: value
          }
        }
      }));
    } else if (field.startsWith('mandate_general.')) {
      const generalField = field.split('.')[1] as keyof typeof formData.mandate_general;
      setFormData(prev => ({
        ...prev,
        mandate_general: {
          ...prev.mandate_general,
          [generalField]: value
        }
      }));
    } else {
      setFormData(prev => ({ ...prev, [field]: value }));
    }
    
    // Clear error when user starts typing
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const handleFocus = (field: string) => {
    setFocusedFields(prev => new Set(prev).add(field));
  };

  const handleBlur = (field: string) => {
    setFocusedFields(prev => {
      const newSet = new Set(prev);
      newSet.delete(field);
      return newSet;
    });
  };

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.mandate_general.company_name.trim()) newErrors['mandate_general.company_name'] = t('speech.signup.company_required');
    if (!formData.mandate_general.industry.trim()) newErrors['mandate_general.industry'] = t('speech.signup.industry_required');
    if (!formData.mandate_general.contact_info.email.trim()) {
      newErrors['contact_info.email'] = t('speech.signup.email_required');
    } else if (!/\S+@\S+\.\S+/.test(formData.mandate_general.contact_info.email)) {
      newErrors['contact_info.email'] = t('speech.signup.email_invalid');
    }
    if (!formData.mandate_general.contact_info.phone.trim()) newErrors['contact_info.phone'] = t('speech.signup.phone_required');
    if (!formData.mandate_general.contact_info.street.trim()) newErrors['contact_info.street'] = t('speech.signup.street_required');
    if (!formData.mandate_general.contact_info.postal_code.trim()) newErrors['contact_info.postal_code'] = t('speech.signup.postal_code_required');
    if (!formData.mandate_general.contact_info.city.trim()) newErrors['contact_info.city'] = t('speech.signup.city_required');
    if (!formData.mandate_general.contact_info.country.trim()) newErrors['contact_info.country'] = t('speech.signup.country_required');

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (validateForm()) {
      // Save to localStorage for session persistence
      try {
        localStorage.setItem('speechSignUpData', JSON.stringify(formData));
        localStorage.setItem('speechSignUpTimestamp', Date.now().toString());
        console.log('Sign-up data saved to localStorage:', formData);
        
        // Dispatch custom event to refresh sidebar
        window.dispatchEvent(new CustomEvent('speechSignUpChanged'));
      } catch (error) {
        console.error('Failed to save to localStorage:', error);
      }
      
      onSubmit(formData);
    }
  };

  const renderFloatingInput = (
    field: string,
    value: string,
    placeholder: string,
    type: string = 'text',
    icon?: React.ReactNode
  ) => {
    const isFocused = focusedFields.has(field);
    const hasValue = value.trim() !== '';
    const hasError = errors[field];

    return (
      <div className={styles.floatingLabelInput}>
        <input
          type={type}
          value={value}
          onChange={(e) => handleInputChange(field, e.target.value)}
          onFocus={() => handleFocus(field)}
          onBlur={() => handleBlur(field)}
          className={`${styles.input} ${hasError ? styles.inputError : ''}`}
          placeholder=""
        />
        <label className={
          isFocused || hasValue
            ? hasError
              ? styles.focusedLabel
              : styles.activeFocusedLabel
            : styles.floatingLabel
        }>
          {icon}
          {placeholder}
        </label>
        {hasError && <span className={styles.errorText}>{hasError}</span>}
      </div>
    );
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <button 
          className={styles.backButton}
          onClick={onBack}
          type="button"
        >
          <IoIosArrowBack className={styles.backIcon} />
          {t('speech.signup.back')}
        </button>
        <h1 className={styles.title}>{t('speech.signup.title')}</h1>
        <p className={styles.subtitle}>
          {t('speech.signup.subtitle')}
        </p>
      </div>

      <form onSubmit={handleSubmit} className={styles.form}>
        <div className={styles.section}>
          <h2 className={styles.sectionTitle}>
            <IoIosBusiness className={styles.sectionIcon} />
            {t('speech.signup.company_info')}
          </h2>
          
          <div className={styles.formGrid}>
            {renderFloatingInput(
              'mandate_general.company_name',
              formData.mandate_general.company_name,
              `${t('speech.signup.company_name')} *`
            )}

            {renderFloatingInput(
              'mandate_general.industry',
              formData.mandate_general.industry,
              `${t('speech.signup.industry')} *`
            )}

            {renderFloatingInput(
              'mandate_general.business_hours',
              formData.mandate_general.business_hours,
              `${t('speech.signup.business_hours')}`,
              'text',
              
            )}

            <div className={styles.floatingLabelInput}>
              <select
                value={formData.mandate_general.timezone}
                onChange={(e) => handleInputChange('mandate_general.timezone', e.target.value)}
                onFocus={() => handleFocus('mandate_general.timezone')}
                onBlur={() => handleBlur('mandate_general.timezone')}
                className={styles.input}
              >
                <option value="Europe/Zurich">Europe/Zurich</option>
                <option value="Europe/Berlin">Europe/Berlin</option>
                <option value="Europe/Paris">Europe/Paris</option>
                <option value="Europe/London">Europe/London</option>
                <option value="America/New_York">America/New_York</option>
              </select>
              <label className={
                focusedFields.has('mandate_general.timezone') || formData.mandate_general.timezone.trim() !== ''
                  ? styles.activeFocusedLabel
                  : styles.floatingLabel
              }>
                {t('speech.signup.timezone')}
              </label>
            </div>
          </div>
        </div>

        <div className={styles.section}>
          <h2 className={styles.sectionTitle}>
            
            {t('speech.signup.contact_info')}
          </h2>
          
          <div className={styles.formGrid}>
            {renderFloatingInput(
              'contact_info.email',
              formData.mandate_general.contact_info.email,
              `${t('speech.signup.email')} *`,
              'email'
            )}

            {renderFloatingInput(
              'contact_info.phone',
              formData.mandate_general.contact_info.phone,
              `${t('speech.signup.phone')} *`,
              'tel',
              
            )}

            {renderFloatingInput(
              'contact_info.street',
              formData.mandate_general.contact_info.street,
              `${t('speech.signup.street')} *`
            )}

            {renderFloatingInput(
              'contact_info.postal_code',
              formData.mandate_general.contact_info.postal_code,
              `${t('speech.signup.postal_code')} *`
            )}

            {renderFloatingInput(
              'contact_info.city',
              formData.mandate_general.contact_info.city,
              `${t('speech.signup.city')} *`
            )}

            {renderFloatingInput(
              'contact_info.country',
              formData.mandate_general.contact_info.country,
              `${t('speech.signup.country')} *`
            )}
          </div>
        </div>

        <div className={styles.section}>
          <h2 className={styles.sectionTitle}>
            <IoIosPeople className={styles.sectionIcon} />
            {t('speech.signup.contacts_setup')}
          </h2>
          <div className={styles.contactsSection}>
            <p className={styles.contactsDescription}>
              {t('speech.signup.contacts_description')}
            </p>
            <div className={styles.contactsActions}>
              <button 
                type="button"
                className={`${sharedStyles.secondaryButton} ${styles.skipButton}`}
                onClick={() => handleInputChange('setup_contacts', 'false')}
              >
                {t('speech.signup.skip_for_now')}
              </button>
              <button 
                type="button"
                className={`${sharedStyles.primaryButton} ${styles.setupButton}`}
                onClick={() => handleInputChange('setup_contacts', 'true')}
              >
                {t('speech.signup.setup_contacts')}
              </button>
            </div>
          </div>
        </div>

        <div className={styles.actions}>
          <button 
            type="button"
            className={`${sharedStyles.secondaryButton} ${styles.cancelButton}`}
            onClick={onBack}
          >
            {t('speech.signup.cancel')}
          </button>
          <button 
            type="submit"
            className={`${sharedStyles.primaryButton} ${styles.submitButton}`}
          >
            {t('speech.signup.submit')}
          </button>
        </div>
      </form>
    </div>
  );
}

export default SpeechSignUp;
