import React, { useState } from 'react';
import kicService from 'src/forms/_resources/utils/kicService';
import { DropdownSelect, PrimaryButtonDark } from 'src/components';
import { ReferralTextInputComponent } from '../patientReferralForm/textInput';
import { ReferralInputContainer, ReferralInputLabel, FlexWrap } from '../patientReferralForm/referral.styles';
import { SchoolTableWrapper } from './studentRefeferralForm.styles';

const COUNTIES = [
    "Alameda",
    "Amador",
    "Butte",
    "Calaveras",
    "Colusa",
    "Contra Costa",
    "Del Norte",
    "El Dorado",
    "Fresno",
    "Glenn",
    "Humboldt",
    "Imperial",
    "Inyo",
    "Kern",
    "Kings",
    "Lake",
    "Lassen",
    "Los Angeles",
    "Madera",
    "Marin",
    "Mariposa",
    "Mendocino",
    "Merced",
    "Modoc",
    "Mono",
    "Monterey",
    "Napa",
    "Nevada",
    "Orange",
    "Placer",
    "Plumas",
    "Riverside",
    "Sacramento",
    "San Benito",
    "San Bernardino",
    "San Diego",
    "San Francisco",
    "San Joaquin",
    "San Luis Obispo",
    "San Mateo",
    "Santa Barbara",
    "Santa Clara",
    "Santa Cruz",
    "Shasta",
    "Sierra",
    "Siskiyou",
    "Solano",
    "Sonoma",
    "Stanislaus",
    "Sutter",
    "Tehama",
    "Trinity",
    "Tulare",
    "Tuolumne",
    "Ventura",
    "Yolo",
    "Yuba"
];

export interface ISchool {
    ID: number;
    school_name: string;
    county: string;
}

const findSchool = async (schoolName: string, schoolCounty: string, schoolPostal: string): Promise<any> => {
    const results = await kicService.fetchSchoolResults(schoolName, schoolCounty, schoolPostal);
    if (results) {
        return results;
    }
    else {
        return false;
    }
}

export const SchoolLookup: React.FC<{ onSchoolFound: any }> = ({
    onSchoolFound
}) => {

    const [schoolName, setSchoolName] = useState('');
    const [schoolCounty, setSchoolCounty] = useState('');
    const [schoolPostal, setSchoolPostal] = useState('')
    const [schoolError, setSchoolError] = useState('');

    const handleSchoolSearch = () => {
        setSchoolError('');

        if(schoolName != '' || schoolCounty != '' || schoolPostal != ''){
            findSchool(schoolName, schoolCounty, schoolPostal).then((schools) => {
                onSchoolFound(schools);
                if (schools.length == 0) {
                    setSchoolError('No Schools found matching your criteria.');
                }
            });
        }
        else{
            setSchoolError('At least one field is required.');
        }
    }

    return (
        <div>
            <strong>Search for your school by:</strong>

            <FlexWrap>
                <ReferralTextInputComponent
                    full
                    labelName="School Name"
                    propKey="school_name"
                    value={schoolName}
                    onChange={evt => setSchoolName(evt.target.value)}
                />

                <ReferralTextInputComponent
                    full
                    labelName="Postal Code"
                    propKey="postal_code"
                    value={schoolPostal}
                    onChange={evt => setSchoolPostal(evt.target.value)}
                />

                <ReferralInputContainer>
                    <ReferralInputLabel htmlFor='county'>County</ReferralInputLabel>
                        <DropdownSelect full defaultValue="County" items={COUNTIES} handleSelectChange={evt => setSchoolCounty(evt.selectedItem)} />
                </ReferralInputContainer>
            </FlexWrap>

            <PrimaryButtonDark onClick={handleSchoolSearch}>Search</PrimaryButtonDark>
            {
                schoolError && 
                <div>
                    <h4 style={{color: 'red'}}>{schoolError}</h4>
                    <h4><strong>Can't find your school?</strong></h4>
                    <p>If you can’t find your school, please call 858-300-1023.</p>
                </div>
            }
        </div>
    )

};

export const SchoolSelect: React.FC<{ schools: ISchool[]; onSchoolSelected: any}>  = ({
    schools,
    onSchoolSelected
}) => {

    return (
        <div>
            <p>Found {schools.length} Schools.</p>
            <SchoolTableWrapper>
                <table>
                    {schools.map((school, index) => {
                        return (<tr key={index}><td>{school.school_name}</td><td> <a onClick={() => {onSchoolSelected(school);}}>Select</a></td></tr>);
                    })}
                </table>
            </SchoolTableWrapper>
            <br/>
            <h4><strong>Can't find your school?</strong></h4>
            <p>If you can’t find your school, please call 858-300-1023.</p>
        </div>
    );
};

export const SchoolSelection: React.FC<{ onSchoolSelected: any}> = ({
    onSchoolSelected
}) => {

    const [schools, setSchools] = useState<ISchool[]>([]);

    const handleSchoolSelection = (schools: ISchool[]) => {
        setSchools(schools);
        if(schools.length == 1){
            onSchoolSelected(schools[0].ID);
        }
    }

    return (
        <div>
            { schools.length == 0 && <SchoolLookup onSchoolFound={(schools: ISchool[]) => handleSchoolSelection(schools)} />}
            { schools.length == 1 && 
                <ReferralInputContainer>
                    Your School:
                    <br />
                    <h4>{schools[0].school_name} <small>(<a onClick={() => { handleSchoolSelection([]) }}>Remove</a>)</small></h4>
                </ReferralInputContainer>
            }
            { schools.length > 1 && <SchoolSelect schools={schools} onSchoolSelected={(school: ISchool) => handleSchoolSelection([school])} />}
        </div>
    );

}
