import React, { useEffect, useState } from 'react';
import { getPatient, savePatient, getPatientIdentifierSources, exportPatientIdentifiersFromSource } 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, PatientCreateViewModel } 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 PatientCreate() {

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

  const [patientIdenResourceId, setPatientIdenResourceId] = useState("");

  const [identifiers, setIdentifiers] = useState([]);

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


  const [patient, setPatient] = useState<Patient>({
    // 1. Basic Info
    familyName: "",
    givenName: "",
    middleName: "",
    openMRSId: "",
    openMRSIdentifierNumber: "",
    oldIdentifierNumber: "",
    gender: "M",
    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({
    familyName: Yup.string().required("This field is required!"),
    givenName: Yup.string().required("This field is required!"),
  });

  useEffect(() => {
    getResource();
  }, []);

  useEffect(() => {
    // console.log(patientIdenResourceId)
    if (patientIdenResourceId)
      generateIdentifiers(patientIdenResourceId)
  }, [patientIdenResourceId]);

  async function generateIdentifiers(id: string) {

    let newObj = {
      generateIdentifiers: true,
      sourceUuid: id,
      numberToGenerate: 1
    }
    console.log(newObj)
    let response = await exportPatientIdentifiersFromSource(newObj);
    setIdentifiers(response.data.identifiers)
  }

  async function getResource() {
    let response = await getPatientIdentifierSources();
    setPatientIdenResourceId(response.data.results[0].uuid);
  }

  function hanledFormSubmit(patient: Patient) {
    setIsLoading(true)
    let newPatient: PatientCreateViewModel = {
      identifiers: [
        {
          "identifier": identifiers[0],
          "identifierType": "05a29f94-c0ed-11e2-94be-8c13b969e334",
          "location": "c0937d4f-1691-11df-97a5-7038c432aabf",
          "preferred": true
        }
      ],
      person: {
        gender: patient.gender,
        age: patient.age,
        birthdate: patient.birthdate,
        birthdateEstimated: false,
        dead: false,
        names: [
          {
            givenName: patient.givenName,
            familyName: patient.familyName,
            middleName: patient.middleName
          }
        ],
        addresses: [
          {
            address1: patient.addressLine1,
            cityVillage: patient.city,
            country: patient.country,
            postalCode: patient.postCode,
            latitude: patient.latitude,
            longitude: patient.longitude,
          }
        ]
      }
    }

    // console.log(newPatient)
    savePatient(newPatient).then((data) => {
      if (data) {
        alert("Create Patient Success!")
      } else {
        alert("Something wrong!")
      }

    });
    setIsLoading(false);
  }

  // async function createOpenMrsPatient(patient: Patient) {



  // setIsLoading(false);
  // }

  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"
                  // dateFormat="Y-m-d"
                  />
                </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="Address Line 1"
                    name="addressLine1"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    // isLoading={isLoading}
                    label="Country"
                    name="country"
                  />
                </Column>
                <Column md={4} sm={4} >
                  <GlobitsTextInput
                    // isLoading={isLoading}
                    label="City"
                    name="city"
                  />
                </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>
            )}


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


          </Grid >

        </Form >
      )
      }
    </Formik >



  );
};