import React, { useState } from 'react'
import './SideEffectsAndTreatments.css';

function SideEffectsAndTreatments() {
    // Define state variables for your input fields and predictions
    const [age, setAge] = useState('');
    const [gender, setGender] = useState('');
    const [drugType, setDrugType] = useState('');
    const [drugUsageMg, setDrugUsageMg] = useState('');
    const [months, setMonths] = useState('');
    const [routeOfAdministration, setRouteOfAdministration] = useState(''); 
    const [takingCooccurringSubstances, setTakingCooccurringSubstances] = useState('');
    const [coOccurringSubstances, setCoOccurringSubstances] = useState(''); 
    const [preExistingMedicalCondition, setPreExistingMedicalCondition] = useState('');
    const [predictions, setPredictions] = useState(null);
    const [formSubmitted, setFormSubmitted] = useState(false);


    const mapGender = (selectedGender) => {
        switch (selectedGender) {
        case 'male':
            return 1;
        case 'female':
            return 2;
        }
    };
    
    const mapDrugTypeToValue = (selectedDrugType) => {
        switch (selectedDrugType) {
        case 'Heroin':
            return 1;
        case 'Cannabis':
            return 2;
        case 'Opium':
            return 3;
        case 'Hashish':
            return 4;
        case 'Cocaine':
            return 5;
        case 'Methamphetamine':
            return 6;
        }
    };

    const maprouteOfAdministration = (selectedrouteOfAdministration) => {
        switch (selectedrouteOfAdministration) {
        case 'Inhalation':
            return 1;
        case 'Injection':
            return 2;
        case 'Smoking':
            return 3;
        }
    };

    const maptakingCooccurringSubstances = (selectedtakingCooccurringSubstances) => {
        switch (selectedtakingCooccurringSubstances) {
        case 'yes':
            return 1;
        case 'no':
            return 2;
        }
    };

    const mapcoOccurringSubstances = (selectedcoOccurringSubstances) => {
        switch (selectedcoOccurringSubstances) {
            case 'Cannabis':
                return 1;
            case 'Cocaine':
                return 2;
            case 'Hashish':
                return 3;
            case 'Heroin':
                return 4;
            case 'Methamphetamine':
                return 5;
            case 'Alcohol':
                return 6;
            case 'No':
                return 7;
        }
    };

    const mappreExistingMedicalCondition = (selectedpreExistingMedicalCondition) => {
        switch (selectedpreExistingMedicalCondition) {
        case 'yes':
            return 1;
        case 'no':
            return 2;
        }
    };

    const handleSubmit = async (event) => {
        event.preventDefault();

        try {
            
          // Form validation
          if (!age) {
            setFormSubmitted(true);
            return;
          }

          if (!drugType) {
            setFormSubmitted(true);
            return;
          }

          if (!drugUsageMg) {
            setFormSubmitted(true);
            return;
          }

          if (!months) {
            setFormSubmitted(true);
            return;
          }

          if (!gender) {
            setFormSubmitted(true);
            return;
          }

          if (!routeOfAdministration) {
            setFormSubmitted(true);
            return;
          }

          if (!takingCooccurringSubstances) {
            setFormSubmitted(true);
            return;
          }

          if (!coOccurringSubstances) {
            setFormSubmitted(true);
            return;
          }

          if (!preExistingMedicalCondition) {
            setFormSubmitted(true);
            return;
          }

          //console.log('Parsed Data:', requestData);
          const genderValue = mapGender(gender);
          const drugTypeValue = mapDrugTypeToValue(drugType);
          const routeOfAdministrationValue = maprouteOfAdministration(routeOfAdministration);
          const takingCooccurringSubstancesValue = maptakingCooccurringSubstances(takingCooccurringSubstances);
          const coOccurringSubstancesValue = mapcoOccurringSubstances(coOccurringSubstances);
          const preExistingMedicalConditionValue = mappreExistingMedicalCondition(preExistingMedicalCondition);
          
          const response = await fetch('http://localhost:5500/predict', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                age:[age],
                gender: [genderValue],
                drug_type: [drugTypeValue],
                measures_of_drug_used_per_day: [drugUsageMg],
                time_used: [months],
                taking_co_occurring_substances: [takingCooccurringSubstancesValue],
                co_occurring_substances: [coOccurringSubstancesValue],
                route_of_administration: [routeOfAdministrationValue],
                pre_existing_condision: [preExistingMedicalConditionValue]
            }),
          });

          const data = await response.json();
          setPredictions(data);
    
        } catch (error) {
            console.error('Error fetching predictions:', error);
        }
      };
    
    
    return (
        <div className='side-effect-wrapper'><div className='side-effect-form'><br/>
        <h1 className='title'>Side Effect & Treatments</h1><br/>
        <form onSubmit={handleSubmit} className='form'>
            <div className='input-group'>
                <label>Age <span className='required-star'> *</span>:</label>
                <input type='number' placeholder='Age' value={age} onChange={(e) => {const inputValue = e.target.value;if (/^\d+$/.test(inputValue) || inputValue === '') {setAge(inputValue);}}}/>
                {formSubmitted && !age && (<div className='error-message'>Age is Required!</div>)}
            </div>
            <div className='input-group'>
                <label>Gender<span className='required-star'> *</span>: </label>
                <input type='radio' name='gender' value='male' onChange={(e) => setGender(e.target.value)}/>
                <span>Male</span>
                <input type='radio' name='gender' value='female' onChange={(e) => setGender(e.target.value)}/>
                <span>Female</span>
                {formSubmitted && !gender && (<div className='error-message'>Gender is Required!</div>)}
            </div>
            <div className='input-group'>
                <label>Drug Type<span className='required-star'> *</span>: </label>
                <select value={drugType} name="drugtype" onChange={(e) => setDrugType(e.target.value)}>
                    <option>Choose a Drug Type</option>
                    <option>Heroin</option>
                    <option>Cannabis</option>
                    <option>Opium</option>
                    <option>Hashish</option>
                    <option>Cocaine</option>
                    <option>Methamphetamine</option>
                </select>
                {formSubmitted && !drugType && (<div className='error-message'>Drug Type is Required!</div>)}
            </div>
            <div className='input-group'>
                <label>Measures of drug used per day(mg)<span className='required-star'> *</span>: </label>
                <input type='number' placeholder='mg' value={drugUsageMg} onChange={(e) => {const inputValue = e.target.value;if (/^\d+$/.test(inputValue) || inputValue === '') {setDrugUsageMg(inputValue);}}}/>
            </div>
            {formSubmitted && !drugUsageMg && (<div className='error-message'>Measures of drug used per day is Required!</div>)}
            <div className='input-group'>
                <label>Time Used(Month)<span className='required-star'> *</span>: </label>
                <input type='number' placeholder='No of months' value={months} onChange={(e) => {const inputValue = e.target.value;if (/^\d+$/.test(inputValue) || inputValue === '') {setMonths(inputValue);}}}/>
                {formSubmitted && !months && (<div className='error-message'>Time Used is Required!</div>)}
            </div>
            <div className='input-group'>
                <label>Route of Administration<span className='required-star'> *</span>: </label>
                <select value={routeOfAdministration} name="route_of_administration " onChange={(e) => setRouteOfAdministration(e.target.value)}>
                    <option>Choose a Route of Administration</option>
                    <option>Inhalation</option>
                    <option>Injection</option>
                    <option>Smoking</option>
                </select>
            </div>
            {formSubmitted && !routeOfAdministration && (<div className='error-message'>Route of Administration is Required!</div>)}
            <div className='input-group'>
                <label>Taking Co-occurring Substances<span className='required-star'> *</span>: </label>
                <input type='radio' name='takingCooccurringSubstances' value='yes' checked={takingCooccurringSubstances === 'yes'} onChange={() => setTakingCooccurringSubstances('yes')}/>
                <span>Yes</span>
                <input type='radio' name='takingCooccurringSubstances' value='no' checked={takingCooccurringSubstances === 'no'} onChange={() => setTakingCooccurringSubstances('no')}/>
                <span>No</span>
            </div>
            {formSubmitted && !takingCooccurringSubstances && (<div className='error-message'>Taking Co-occurring Substances is Required!</div>)}
            <div className='input-group'>
                <label>Co-occurring Substances<span className='required-star'> *</span>: </label>
                <select value={coOccurringSubstances} name="co-occurringsubstances " onChange={(e) => setCoOccurringSubstances(e.target.value)}>
                    <option>Choose a Co-occurring Substances</option>
                    <option>Cannabis</option>
                    <option>Cocaine</option>
                    <option>Hashish</option>
                    <option>Heroin</option>
                    <option>Methamphetamine</option>
                    <option>Alcohol</option>
                    <option>No</option>
                </select>
            </div>
            {formSubmitted && !coOccurringSubstances && (<div className='error-message'>Co-occurring Substances is Required!</div>)}
            <div className='input-group'>
                <label>Any pre-existing medical conditions?<span className='required-star'> *</span>: </label>
                <input type='radio' name='preExistingmedicalcondition' value='yes' checked={preExistingMedicalCondition === 'yes'} onChange={() => setPreExistingMedicalCondition('yes')}/>
                <span>Yes</span>
                <input type='radio' name='preExistingmedicalcondition' value='no' checked={preExistingMedicalCondition === 'no'} onChange={() => setPreExistingMedicalCondition('no')}/>
                <span>No</span>
            </div>
            {formSubmitted && !preExistingMedicalCondition && (<div className='error-message'>Pre-existing medical conditions is Required!</div>)}

            <div className='btn-area'>
                <button type="submit" className='btn'>Predict</button>
            </div>
            <div className='input-group1'>
                {predictions && (
                <div>
                    <p><h1>Predictions</h1></p>
                        <ul>
                            {Object.keys(predictions).map((key) => {
                            const predictionText = predictions[key];
                            return (
                                <li key={key}>
                                    <strong>{key}:</strong> {predictionText}
                                </li>
                            );
                            })}
                        </ul>
                </div>
                )}
            </div>
        </form>
    </div></div>
    )
}

export default SideEffectsAndTreatments;