import {useState, useEffect} from 'react'
import { Button, InputCompOne, Stepper } from '../../shared/index';

import {Formik, Form} from 'formik'
import * as Yup from "yup";

import { getEmployersList } from '../../../core/apiRequest';

type Props = {
  handleNextStep:(value:{})=>any
}

// type EmployerProps = {
//   loading?: boolean,
//   data?: Array<{[index:string]: string}> | {[index:string]: Array<{[index:string]: string}> }
// }

const initialValues = {
  job_title: "",
  name: "",
  sector: "",
  industry: "",
  resumption_date: "",
  email:"",
  annual_income: "",
  monthly_salary: "",
  salary_payment_date: "",
  employment_id: "",
  highest_eductaion: "",
  employer_uid: "",
  isChecked: false
};

// To get the validation schema
const validationSchema = Yup.object().shape({
  isChecked: Yup.bool(), // use bool instead of boolean
  // .oneOf([true, false], "You must accept the terms and conditions"),
  job_title: Yup.string()
    .required("Required"),
  name: Yup.string().when('isChecked', {
      is: true, 
      then: () => Yup.string().required('required'),
      otherwise: () => Yup.string(),
    }),
  sector: Yup.string().when('isChecked', {
      is: true, 
      then: () => Yup.string().required('required'),
    }),
  industry: Yup.string().when('isChecked', {
      is: true, 
      then: () => Yup.string().required('required'),
    }),
  resumption_date: Yup.string()
    .required("Required"),
  email: Yup.string().when('isChecked', {
      is: true, 
      then: () => Yup.string().required('required'),
    })
    .email("Invalid"),
  annual_income: Yup.string()
    .required("Required")
    .test("no-e", "Invalid", (value:any) => {
      if (value && /^[0-9]*$/.test(value) == false) {
        return false;
      }
      return true;
    }),
  monthly_salary: Yup.string()
    .required("Required")
    .test("no-e", "Invalid", (value:any) => {
      if (value && /^[0-9]*$/.test(value) == false) {
        return false;
      }
      return true;
    }),
  salary_payment_date: Yup.string()
    .required("Required"),
  employment_id: Yup.string()
    .required("Required"),
  highest_eductaion: Yup.string()
    .required("Required"),
  employer_uid: Yup.string().when('isChecked', {
      is: false, 
      then: () => Yup.string().required('required'),
    }),
});

export default function DashboardHomeEmploymentInfo({handleNextStep}:Props) {

  const [employersList, setEmployersList] = useState<any>({
    loading: true,
    data: []
  })


  //FUNCTION TO HANDLE SUBMIT
  const handleSubmit = (values:any) => {
    // Remember to changed the checked value's name
    if(values.employer_uid){
      let employer_uid = values.employer_uid
      delete values.employer_uid
      handleNextStep({employer_uid, employment: values})
    }else{
      handleNextStep({employment: values})
    }
  };

  useEffect(()=>{
    getEmployersList().then(res => {
      setEmployersList({loading:false, data:res?.data})
    }).catch(err => {
      console.log(err)
      setEmployersList({loading:false, data:[]})
    })
  },[])


  return (
    <div className="w-full">
      <div className="w-full flex justify-center">
        <Stepper step={2} />
      </div>
      <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
          >
            {(props)=>(
              <Form>          
                <div className="mt-[3.25rem] flex flex-col gap-9">
                  <p className='text-red-500 text-lg md:text-2xl'>Employment Informaton</p>
                  <div className="flex flex-col lg:flex-row items-start gap-[2rem]">
                    <div className='w-full lg:max-w-[30rem] flex flex-col'>
                      <div className='w-full gap-[2rem]'>
                        <InputCompOne
                          parentClass="w-full"
                          name="employer_uid"
                          floatLabel="Employer Name"
                          // labelClass="font-bold text-[1.125rem]"
                          select={true}
                          selectClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                          selectOptions={{loading:employersList?.loading, data: employersList?.data?.records}}
                          selectValue={props.values.employer_uid}
                          onChange={props.handleChange}
                          error={(props.errors.employer_uid && props.touched.employer_uid) ? props.errors.employer_uid : ''}
                          disabled={props.values.isChecked}
                        />
                        <div className='flex gap-4 items-start my-2'>
                          <input 
                            type='checkbox' 
                            name="isChecked"
                            className='w-4 h-4 p-2 accent-purple-600 text-purple-600 bg-gray-100 border-gray-300 rounded focus:ring-purple-500' 
                            onChange={props.handleChange}
                            checked={props.values.isChecked}
                          />
                          <p className='text-[12px] text-justify'>Check here if employer is not on the list</p>
                        </div>
                        <div className={`hidden p-4 ${props.values.isChecked && 'hidden'}`}>
                          Name: {'Name'}
                        </div>
                      </div>
                      <div className={`w-full flex flex-col gap-[2rem] ${!props.values.isChecked && 'hidden'}`}>
                        <InputCompOne
                          parentClass="w-full"
                          name="name"
                          floatLabel="Employer name"
                          // labelClass="font-bold text-[1.125rem]"
                          input
                          inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                          placeholder="Mr. Mark John"
                          value={props.values.name}
                          onChange={props.handleChange}
                          error={(props.errors.name && props.touched.name) ? props.errors.name : ''}
                        />
                        <InputCompOne
                          parentClass="w-full"
                          name="email"
                          floatLabel="Employers official email"
                          // labelClass="font-bold text-[1.125rem]"
                          input
                          inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                          placeholder="example@gmail.com"
                          value={props.values.email}
                          onChange={props.handleChange}
                          error={(props.errors.email && props.touched.email) ? props.errors.email : ''}
                        />
                        <InputCompOne
                          parentClass="w-full"
                          name="industry"
                          floatLabel="Select your industry"
                          // labelClass="font-bold text-[1.125rem]"
                          select={true}
                          selectClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                          selectOptions={industry}
                          selectValue={props.values.industry}
                          onChange={props.handleChange}
                          error={(props.errors.industry && props.touched.industry) ? props.errors.industry : ''}
                        />
                        <InputCompOne
                          parentClass="w-full"
                          name="sector"
                          floatLabel="Job Sector"
                          // labelClass="font-bold text-[1.125rem]"
                          select={true}
                          selectClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                          selectOptions={jobSector}
                          selectValue={props.values.sector}
                          onChange={props.handleChange}
                          error={(props.errors.sector && props.touched.sector) ? props.errors.sector : ''}
                        />
                      </div>
                    </div>

                    <div className='w-full lg:max-w-[30rem] flex flex-col gap-[2rem]'>  
                      <InputCompOne
                        parentClass="w-full"
                        name="job_title"
                        floatLabel="Job Title"
                        // labelClass="font-bold text-[1.125rem]"
                        input
                        inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                        placeholder="Software Engineer"
                        value={props.values.job_title}
                        onChange={props.handleChange}
                        error={(props.errors.job_title && props.touched.job_title) ? props.errors.job_title : ''}
                      />
                      <InputCompOne
                        parentClass="w-full"
                        name="highest_eductaion"
                        floatLabel="Highest level of education"
                        // labelClass="font-bold text-[1.125rem]"
                        select={true}
                        selectClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                        selectOptions={highestEductaion}
                        selectValue={props.values.highest_eductaion}
                        onChange={props.handleChange}
                        error={(props.errors.highest_eductaion && props.touched.highest_eductaion) ? props.errors.highest_eductaion : ''}
                      />
                      <div className="w-full flex flex-col sm:flex-row items-center gap-4">
                          <InputCompOne
                          parentClass="w-full"
                          name="resumption_date"
                          floatLabel="Date of resumption"
                          // labelClass="font-bold text-[1.125rem]"
                          input
                          inputType='date'
                          inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                          placeholder="12/12/2015"
                          value={props.values.resumption_date}
                          onChange={props.handleChange}
                          error={(props.errors.resumption_date && props.touched.resumption_date) ? props.errors.resumption_date : ''}
                        />
                        <InputCompOne
                          parentClass="w-full"
                          name="salary_payment_date"
                          floatLabel="Salary payment date"
                          // labelClass="font-bold text-[1.125rem]"
                          input
                          inputType='date'
                          inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                          placeholder="30th of every month"
                          value={props.values.salary_payment_date}
                          onChange={props.handleChange}
                          error={(props.errors.salary_payment_date && props.touched.salary_payment_date) ? props.errors.salary_payment_date : ''}
                        />
                      </div>
                      <div className="w-full flex flex-col sm:flex-row items-center gap-4">
                        <InputCompOne
                          parentClass="w-full"
                          name="annual_income"
                          floatLabel="Annual Income"
                          // labelClass="font-bold text-[1.125rem]"
                          input
                          inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem] text-right"
                          placeholder="1,200,000"
                          value={props.values.annual_income}
                          onChange={props.handleChange}
                          error={(props.errors.annual_income && props.touched.annual_income) ? props.errors.annual_income : ''}
                        />
                        <InputCompOne
                          parentClass="w-full"
                          name="monthly_salary"
                          floatLabel="Net monthly salary"
                          // labelClass="font-bold text-[1.125rem]"
                          input
                          inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem] text-right"
                          placeholder="100,000"
                          value={props.values.monthly_salary}
                          onChange={props.handleChange}
                          error={(props.errors.monthly_salary && props.touched.monthly_salary) ? props.errors.monthly_salary : ''}
                        />
                      </div>
                      <InputCompOne
                        parentClass="w-full"
                        name="employment_id"
                        floatLabel="Employee ID"
                        // labelClass="font-bold text-[1.125rem]"
                        input
                        inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                        placeholder="LS/001/005"
                        value={props.values.employment_id}
                        onChange={props.handleChange}
                        error={(props.errors.employment_id && props.touched.employment_id) ? props.errors.employment_id : ''}
                      />
                      <div className="w-full">
                        <Button
                          className="my-4 btn-Y text-black w-full h-11"
                          text="Next"
                          type="submit"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </Form>
            )}
      </Formik>
    </div>
  );
}



interface SelectOption {
  loading: boolean;
  data: {value: string;
  label: string}[]
}


const jobSector: SelectOption = {
  loading: false,
  data: [
    { value: "", label: "Please Select" },
    { value: "private (non academic)", label: "Private (non academic)" },
  ]
}

const industry: SelectOption = {
  loading: false,
  data: [
    { value: "", label: "Please Select" },
    { value: "engineering", label: "Engineering" },
  ]
}

const highestEductaion: SelectOption = {
  loading: false,
  data: [
    { value: "", label: "Please Select" },
    { value: "b.sc + professional qualification", label: "B.Sc + Professional Qualification" },
  ]
}