import React, { useEffect, useState } from 'react';
import { getPatient, getPersonAddress, getPersonName, getPatientIdentifier } from "./PatientService";
import { age, navigate } from '@openmrs/esm-framework';
import * as Yup from "yup";
import { Formik, Form } from "formik";
import { Button, ButtonSkeleton, Column, Grid, TextInput, TextInputSkeleton } from 'carbon-components-react';
import { Patient } from '../models/patient';
import GlobitsTextInput from '../common/form/GlobitsTextInput';
import GlobitsSelectInput from '../common/form/GlobitsSelectInput';
import GlobitsDateInput from '../common/form/GlobitsDateInput';
import styles from './patient.scss';

interface PatientEditProps {

}

export default function PatientEdit() {

  const queryParams = new URLSearchParams(window.location.search);
  const id = queryParams.get('id');

  const [isLoading, setIsLoading] = useState(true);

  const backToPatientList = () => navigate({ to: `/openmrs/spa/dashboard/patient` });


  const [patient, setPatient] = useState<Patient>({
    // 1. Basic Info
    familyName: "",
    givenName: "",
    middleName: "",
    openMRSId:"",
    openMRSIdentifierNumber: "",
    oldIdentifierNumber: "",
    gender: "",
    birthdate: null,
    age: null,
    //2. Contact Details
    postCode: "",
    longitude: "",
    estateNearestCentre: "",
    sectionHomestead: "",
    addressLine1: "",
    addressLine2: "",
    country: "",
    region: "",
    latitude: "",
    location: "",
    sublocation: "",
    city: "",
    district: "",
    division: "",
    phoneNumber: "",
    email: "",


  });

  const validationSchema = Yup.object({
    family: Yup.string().required("This field is required!"),
    given: Yup.string().required("This field is required!"),
  });

  function hanledFormSubmit(patient: Patient) {
    console.log(patient)
  }

  useEffect(() => {
    if (id) {
      setIsLoading(true);
      loadPatient(id).then((patient) => setPatient(patient));
    } else {
      setIsLoading(false);
    }
  }, [id]);

  async function loadPatient(id: string) {
    let response = await getPatient(id);

    let newPatient: Patient = {
      //1. Basic Info
      familyName: "",
      middleName: "",
      givenName: "",
      openMRSId:"",
      openMRSIdentifierNumber: "",
      oldIdentifierNumber: "",
      gender: response.data.person.gender,
      birthdate: response.data.person.birthdate,
      age: response.data.person.age,
      //2. Contact Details
      postCode: "",
      longitude: "",
      estateNearestCentre: "",
      sectionHomestead: "",
      addressLine1: "",
      addressLine2: "",
      country: "",
      region: "",
      latitude: "",
      location: "",
      sublocation: "",
      city: "",
      district: "",
      division: "",
      phoneNumber: "",
      email: "",
    }

    if (response && response.data.person.preferredAddress) {
      let personAd = await getPersonAddress(id, response.data.person.preferredAddress.uuid);
      newPatient.addressLine1 = personAd?.data.address1;
      newPatient.addressLine2 = personAd?.data.address2;
      newPatient.city = personAd?.data.cityVillage;
      newPatient.country = personAd?.data.country;
      newPatient.postCode = personAd?.data.postalCode;
    }

    if (response && response.data.person.preferredName) {
      let personName = await getPersonName(id);

      if (personName && personName.data && personName.data.results && personName.data.results.length > 0) {
        newPatient.familyName = personName.data.results[0].familyName;
        newPatient.middleName = personName.data.results[0].middleName;
        newPatient.givenName = personName.data.results[0].givenName
      }

    }

    if (response && response.data.identifiers && response.data.identifiers.length > 0) {
      let patientIden = await getPatientIdentifier(id);

      if (patientIden && patientIden.data && patientIden.data.results && patientIden.data.results.length > 0) {
        newPatient.openMRSIdentifierNumber = patientIden.data.results[0]?.identifier;
        newPatient.oldIdentifierNumber = patientIden.data.results[1]?.identifier;
      }
    }
    // if (response.data.identifier && response.data.identifier.length > 0) {
    //   newPatient.openMRSIdentifierNumber = response.data.identifier[0]?.value;
    //   newPatient.oldIdentifierNumber = response.data.identifier[1]?.value;
    // }
    // if (response.data.address && response.data.address.length > 0) {
    //   newPatient.postCode = response.data.address[0].postalCode;
    //   newPatient.country = response.data.address[0].country;
    //   newPatient.city = response.data.address[0].city;
    //   newPatient.district = response.data.address[0].state;
    //   if (response.data.address[0].extension
    //     && response.data.address[0].extension.length > 0
    //     && response.data.address[0].extension[0].extension
    //     && response.data.address[0].extension[0].extension.length > 0) {
    //     newPatient.addressLine1 = response.data.address[0].extension[0].extension[0].valueString;
    //     newPatient.addressLine2 = response.data.address[0].extension[0].extension[1].valueString;
    //   }
    // }

    setIsLoading(false);
    return newPatient;
  }

  return (

    <Formik
      validationSchema={validationSchema}
      enableReinitialize
      initialValues={patient}
      onSubmit={(values: Patient) => hanledFormSubmit(values)}
    >
      {({ isSubmitting }) => (
        <Form autoComplete="off">
          <Grid>
            <Column sm={12} >
              <h3 className={styles.formTitle}>1. Basic Info</h3>
              <span className={styles.formSubTitle}>All fields are required unless marked optional</span>
              <Grid className={styles.formCard}>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Given Name"
                    name="givenName"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Middle Name"
                    name="middleName"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Family Name"
                    name="familyName"
                  />
                </Column>

                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="OpenMRS Id"
                    name="openMRSId"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="OpenMRS Identifier Number"
                    name="openMRSIdentifierNumber"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Old Identifier Number"
                    name="oldIdentifierNumber"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsSelectInput
                    isLoading={isLoading}
                    label="Gender"
                    name="gender"
                    options={[
                      { value: "M", name: "Male" },
                      { value: "F", name: "Female" },
                      { value: "O", name: "Other" },
                      { value: "U", name: "Unknown" },
                    ]}
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsDateInput
                    isLoading={isLoading}
                    label="Birth Date"
                    name="birthdate"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Age"
                    name="age"
                  />
                </Column>
              </Grid>
            </Column>
            <Column sm={12} >
              <h3 className={styles.formTitle}>2. Contact Details</h3>
              <span className={styles.formSubTitle}>All fields are required unless marked optional</span>
              <Grid className={styles.formCard}>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Post Code"
                    name="postCode"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Longitude"
                    name="longitude"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Latitude"
                    name="latitude"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Location"
                    name="location"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Sublocation"
                    name="sublocation"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Estate Nearest Centre"
                    name="estateNearestCentre"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Section Homestead"
                    name="sectionHomestead"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Address Line 1"
                    name="addressLine1"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Address Line 2"
                    name="addressLine2"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Country"
                    name="country"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Region"
                    name="region"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="City"
                    name="city"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="District"
                    name="district"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Division"
                    name="division"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Phone Number (optional)"
                    name="phoneNumber"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    isLoading={isLoading}
                    label="Email address (optional)"
                    name="email"
                  />
                </Column>

              </Grid>
            </Column>
            {isLoading ? (
              <ButtonSkeleton />
            ) : (
              <Button type="submit">Submit</Button>
            )}

            {isLoading ? (
              <ButtonSkeleton />
            ) : (
              <Button kind="ghost" onClick={() => {
                backToPatientList();
              }}>
                Cancel
              </Button>
            )}


          </Grid >

        </Form >
      )
      }
    </Formik >



  );
};