import {useEffect, useState} from 'react'
import {useLocation, useNavigate} from 'react-router-dom'
import { Button, InputCompOne } from "../../shared";
import {Formik, Form} from 'formik'
import * as Yup from "yup";
import { RouteHandler } from '../../../router/routes';
import { getLoanDetail } from '../../../core/apiRequest';
import CustomSpinner from '../../CustomSpinner';

interface LoanDetail {
  loan_amount: string;
  payment_month: string;
  sales_agent: string;
  [key: string]: any;  // to accommodate any additional properties
}

// interface InitialValues {
//   loan_amount: string;
//   payment_month: string;
//   sales_agent: string;
// }

const initialValues = {
  loan_amount: "",
  payment_month: "",
  sales_agent: "",
};

// To get the validation schema
const validationSchema = Yup.object().shape({
  payment_month: Yup.string()
    .required("Required"),
  loan_amount: Yup.string()
    .required("Required")
    .test("no-e", "Invalid", (value:any) => {
      if (value && /^[0-9]*$/.test(value) == false) {
        return false;
      }
      return true;
    }),
    sales_agent: Yup.string()
});

type LocationState = {
  application_uid: string
}

export default function ReferenceDetails() {

    const location = useLocation()
    const navigate = useNavigate()

    // const applicationUID = location?.state?.application_uid
    const stateExist = location?.state as LocationState

  //FUNCTION TO HANDLE SUBMIT
  const handleSubmit = (values:{}) => {
    // handleNextStep(values)
    console.log(values)
  };

  const [loanDetail, setLoanDetail] = useState<{loading:boolean, data:LoanDetail}>({
    loading: true,
    data: {
      loan_amount: '',
    payment_month: '',
    sales_agent: '',
    },
  })
  useEffect(()=>{
    if(!stateExist){
      navigate(RouteHandler.dashboardHome)
      return
    }
    getLoanDetail({application_uid:stateExist.application_uid}).then(res => {
      setLoanDetail({loading:false, data:res?.data?.loan})
      }).catch(err => {
        console.log(err)
        setLoanDetail((prev:any) => ({...prev, loading:false}))
      })
  },[])

  // const formInitialValue:LoanDetail = (loanDetail.loading) ? initialValues : loanDetail?.data
  const formInitialValue = (loanDetail.loading || Object.keys(loanDetail?.data)?.length < 1) ? initialValues : {...initialValues, ...loanDetail?.data}

  return (
    <>
        {loanDetail.loading ?
        <div className='flex flex-col justify-center items-center h-96'>
            <CustomSpinner width='w-8' height='h-8' />
        </div>
        :
        <div className="w-full">
        <Formik
                initialValues={formInitialValue}
                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'>Loan Details</p>
                    <div className='w-full flex flex-wrap items-center gap-4'>
                        <InputCompOne
                            parentClass="w-full sm:max-w-[10rem] flex flex-col gap-4"
                            name="loan_amount"
                            label="Amount"
                            labelClass="font-bold text-[1.125rem]"
                            input
                            inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem] text-right"
                            placeholder="350,000"
                            value={props.values.loan_amount}
                            disabled={true}
                            onChange={props.handleChange}
                            // error={(props.errors.loan_amount && props.touched.loan_amount) ? props.errors.loan_amount : ''}
                        />
                        <InputCompOne
                            parentClass="w-full sm:max-w-[10rem] flex flex-col gap-4"
                            name="payment_month"
                            label="Months?"
                            labelClass="font-bold text-[1.125rem]"
                            select={true}
                            disabled={true}
                            selectClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                            selectOptions={props.values.payment_month}
                            selectValue={props.values.payment_month}
                            onChange={props.handleChange}
                            // error={(props.errors.payment_month && props.touched.payment_month) ? props.errors.payment_month : ''}
                        />
                        <InputCompOne
                            parentClass="w-full sm:max-w-[10rem] flex flex-col gap-4"
                            name="sales_agent"
                            label="agent ID"
                            labelClass="font-bold text-[1.125rem]"
                            floatLabel='Enter agent ID'
                            input
                            disabled={true}
                            inputClass="w-full h-[3.625rem] bg-[#EFEFEF] px-4 rounded-[.375rem]"
                            placeholder="Agent ID"
                            value={props.values.sales_agent}
                            onChange={props.handleChange}
                            // error={(props.errors.sales_agent && props.touched.sales_agent) ? props.errors.sales_agent : ''}
                        />
                    </div>
                    <Button
                        className="hidden my-8 max-w-[25.875rem] btn-Y text-black w-full h-11"
                        text="Next"
                        type="submit"
                    />
                    </div>
                </Form>
                )}
        </Formik>
        </div>
        }
    </>
  );
}

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


// const paymentMonth: SelectOption = {
//   loading: false,
//   data: [
//     { value: "", label: "Please Select" },
//     { value: "6", label: "6 Months" },
//     { value: "12", label: "12 Months" },
//     { value: "18", label: "18 Months" },
//     { value: "24", label: "24 Months" },
//   ]
// }
