import React, { useState, memo } from 'react';
import Modal from './modal/Modal';
import './ProfileModal.css';
import type { ProfileData } from '../sdk/models/ProfileData';

interface ProfileModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (profileData: ProfileData, validatorId: string | null, ownerId: string | null) => void;
  initialData?: Partial<ProfileData>;
}

function ProfileModal({ isOpen, onClose, onSubmit, initialData = {} }: ProfileModalProps) {
  const [profileData, setProfileData] = useState<ProfileData>({
    name: initialData.name || '',
    surname: initialData.surname || '',
    email: initialData.email || '',
    phone: initialData.phone || '',
    address: initialData.address || '',
    postalCode: initialData.postalCode || '',
    city: initialData.city || '',
    country: initialData.country || '',
    idDocument: initialData.idDocument || null,
    idCertified: false,
  });
  const [validatorId, setValidatorId] = useState<string | null>(null);
  const [ownerId, setOwnerId] = useState<string | null>(null);
  const [isOwnProfile, setIsOwnProfile] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, type, files, value } = e.target;

    if (type === 'file' && files) {
      // Assuming you want to handle a single file
      const file = files[0];
      setProfileData(prev => ({
        ...prev,
        [name]: file
      }));
    } else {
      setProfileData(prev => ({
        ...prev,
        [name]: value
      }));
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!validatorId && !ownerId) {
      setErrorMessage("Please set either a Validator ID or an Owner ID.");
      return;
    }
    setErrorMessage(null);
    onSubmit(profileData, validatorId, ownerId);
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Créer un profil">
      <div className="profile-form-container">
        <form onSubmit={handleSubmit} className="profile-form">
          <div className="form-section">
            <h3 className="section-title">Informations personnelles</h3>
            <div className="form-row">
              <div className="form-field">
                <label htmlFor="surname">Prénom<span className="required">*</span></label>
                <input
                  type="text"
                  id="surname"
                  name="surname"
                  value={profileData.surname}
                  onChange={handleChange}
                  placeholder="Votre prénom"
                  required
                />
              </div>
              <div className="form-field">
                <label htmlFor="name">Nom<span className="required">*</span></label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  value={profileData.name}
                  onChange={handleChange}
                  placeholder="Votre nom"
                  required
                />
              </div>
            </div>

            <div className="form-field">
              <label htmlFor="email">Email<span className="required">*</span></label>
              <input
                type="email"
                id="email"
                name="email"
                value={profileData.email}
                onChange={handleChange}
                placeholder="exemple@email.com"
                required
              />
            </div>

            <div className="form-field">
              <label htmlFor="phone">Téléphone<span className="required">*</span></label>
              <input
                type="tel"
                id="phone"
                name="phone"
                value={profileData.phone}
                onChange={handleChange}
                placeholder="+33 6 12 34 56 78"
                required
              />
            </div>
          </div>

          <div className="form-section">
            <h3 className="section-title">Adresse</h3>
            <div className="form-field">
              <label htmlFor="address">Adresse complète<span className="required">*</span></label>
              <input
                type="text"
                id="address"
                name="address"
                value={profileData.address}
                onChange={handleChange}
                placeholder="123 rue de Paris"
                required
              />
            </div>

            <div className="form-row">
              <div className="form-field">
                <label htmlFor="postalCode">Code postal<span className="required">*</span></label>
                <input
                  type="text"
                  id="postalCode"
                  name="postalCode"
                  value={profileData.postalCode}
                  onChange={handleChange}
                  placeholder="75001"
                  required
                />
              </div>
              <div className="form-field">
                <label htmlFor="city">Ville<span className="required">*</span></label>
                <input
                  type="text"
                  id="city"
                  name="city"
                  value={profileData.city}
                  onChange={handleChange}
                  placeholder="Paris"
                  required
                />
              </div>
            </div>

            <div className="form-field">
              <label htmlFor="country">Pays<span className="required">*</span></label>
              <input
                type="text"
                id="country"
                name="country"
                value={profileData.country}
                onChange={handleChange}
                placeholder="France"
                required
              />
            </div>
          </div>

          <div className="form-section">
            <h3 className="section-title">Document</h3>
            <div className="form-field">
              <label htmlFor="idDocument">Document d'identité&nbsp;<span className="optional">(optionnel)</span></label>
              <input
                type="file"
                id="idDocument"
                name="idDocument"
                onChange={handleChange}
              />
            </div>
          </div>

          <div className="form-section">
            <h3 className="section-title">Profil</h3>
            <button type="button" onClick={() => setIsOwnProfile(!isOwnProfile)}>
              {isOwnProfile ? "Je veux faire valider mon profil" : "Je valide le profil d'un utilisateur"}</button>
            {isOwnProfile ? (
              <div className="form-field">
                <label htmlFor="validatorId">ID du validateur</label>
                <input
                  type="text"
                  id="validatorId"
                  name="validatorId"
                  value={validatorId || ''}
                  onChange={(e) => {
                    setValidatorId(e.target.value);
                    setOwnerId(null);
                  }}
                  placeholder="ID du validateur"
                />
              </div>
            ) : (
              <div className="form-field">
                <label htmlFor="ownerId">ID de l'utilisateur</label>
                <input
                  type="text"
                  id="ownerId"
                  name="ownerId"
                  value={ownerId || ''}
                  onChange={(e) => {
                    setOwnerId(e.target.value);
                    setValidatorId(null);
                  }}
                  placeholder="ID de l'utilisateur"
                />
              </div>
            )}
          </div>

          {errorMessage && <div className="error-message">{errorMessage}</div>}

          <div className="form-actions">
            <button type="button" className="btn-cancel" onClick={onClose}>Annuler</button>
            <button type="submit" className="btn-submit">Créer le profil</button>
          </div>
        </form>
      </div>
    </Modal>
  );
};

ProfileModal.displayName = 'ProfileModal';
export default memo(ProfileModal);
