import * as Yup from 'yup';
import { IcdType } from '@/@types/diagnosis';
import { OrganizationType, PractitionerType } from '@/@types/doctor';
import AutocompleteDiagnosisControlled from '@/components/autocomplete/AutocompleteDiagnosisControlled';
import { LoadingButton } from '@mui/lab';
import { Paper, Stack, TextField } from '@mui/material';
import { Controller, useForm } from 'react-hook-form';
import { useEffect, useMemo, useState } from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import { enqueueSnackbar } from 'notistack';
import axios from '@/utils/axios';
import { FormProvider, RHFDatepicker, RHFTextField } from '@/components/hook-form';
import AutocompleteDoctor from '@/components/autocomplete/AutocompleteDoctor';
import AutocompleteHealthcare from '@/components/autocomplete/AutocompleteHealthcare';

export default function ClaimDetail({ claim }) {
  // --------------------------------------------------------------
  // Diagnosis
  const [primaryDiagnosis, setPrimaryDiagnosis] = useState(null);
  const [secondaryDiagnosis, setSecondaryDiagnosis] = useState(null);
  const [loadingDiagnosis, setLoadingDiagnosis] = useState(false);
  const [primaryDiagnosisOptions, setPrimaryDiagnosisOptions] = useState([]);
  const [secondaryDiagnosisOptions, setSecondaryDiagnosisOptions] = useState([]);

  const ClaimDetailSchema = Yup.object().shape({
    primary_diagnosis: Yup.object().required('Diagnosis Utama Wajib dipilih'),
    // secondary_diagnosis: Yup.object().required('Diagnosis Utama Wajib dipilih'),
    doctor: Yup.object().required('Dokter Harus dipilih'),
    healthcare: Yup.object().required('Healthcare Harus dipilih'),
  });

  interface FormValuesProps extends Partial<any> {
    primary_diagnosis: IcdType;
    secondary_diagnosis: IcdType;
    doctor: PractitionerType;
    healthcare: OrganizationType;
  }

  const defaultValues = useMemo(
    () => ({
      primary_diagnosis: claim?.primary_diagnosis[0]?.icd ?? null,
      secondary_diagnosis: claim?.secondary_diagnosis[0]?.icd ?? null,
    }),
    [claim]
  );

  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(ClaimDetailSchema),
    defaultValues,
  });

  const {
    reset,
    watch,
    control,
    setValue,
    getValues,
    setError,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  const handleSaveDiagnosis = () => {
    setLoadingDiagnosis(true);

    axios
      .post(`claims/${claim.id}/update-diagnosis`, {
        primary: [getValues('primary_diagnosis')?.id],
        secondary: [getValues('secondary_diagnosis')?.id],
      })
      .then((res) => {
        enqueueSnackbar(res.data.message, { variant: 'success' });
      })
      .catch((err) => {
        setLoadingDiagnosis(false);
        enqueueSnackbar(err.response?.data?.message ?? err?.message, { variant: 'error' });
      })
      .then(() => {
        setLoadingDiagnosis(false);
      });
  };

  useEffect(() => {
    if (claim) {
      // SET Default Primary Diagnosis
      if (claim.primary_diagnosis.length && claim.primary_diagnosis[0].icd) {
        setPrimaryDiagnosisOptions(
          claim.primary_diagnosis.map((diagnosis) => {
            if (diagnosis.icd) {
              return diagnosis.icd;
            }
          })
        );
        setValue('primary_diagnosis', claim.primary_diagnosis[0].icd);
      }

      // SET Default Secondary Diagnosis
      if (claim.secondary_diagnosis.length && claim.secondary_diagnosis[0].icd) {
        setSecondaryDiagnosisOptions(
          claim.secondary_diagnosis.map((diagnosis) => {
            if (diagnosis.icd) {
              return diagnosis.icd;
            }
          })
        );
        setValue('secondary_diagnosis', claim.secondary_diagnosis[0].icd);
      }
    }
  }, [claim]);

  function onSubmit(){
    console.log('submit');
  }

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
    <Stack spacing={2}>
        <Stack spacing={2} sx={{ background: 'white', p: 2 }}>
          <RHFDatepicker
            name="tanggal_masuk"
            placeholder="DD/MM/YYYY"
            label="Tanggal Masuk"
          ></RHFDatepicker>
          <RHFDatepicker
            name="tanggal_keluar"
            placeholder="DD/MM/YYYY"
            label="Tanggal Keluar"
          ></RHFDatepicker>
          
          <Controller
              name="healthcare"
              control={control}
              render={({ field: { onChange, value } }) => (
                <AutocompleteHealthcare
                  onChange={onChange}
                  currentOptions={[]}
                  currentValue={value}
                  textLabel="Tempat Dirawat"
                />
              )}
            />
          <Controller
              name="doctor"
              control={control}
              render={({ field: { onChange, value } }) => (
                <AutocompleteDoctor
                  onChange={onChange}
                  currentOptions={[]}
                  currentValue={value}
                  textLabel="Dokter yang merawat"
                />
              )}
            />
          <RHFTextField
            name="doktor"
            placeholder="Nomor Rekam Medis di RS"
            label="No. Rekam Medis"
          ></RHFTextField>
          <RHFTextField
            name="doktor"
            label="Jumlah Tempat Tidur"
          ></RHFTextField>
          <RHFTextField
            name="doktor"
            label="Lama Perawatan (hari)"
          ></RHFTextField>
        </Stack>

        <Paper variant="outlined" sx={{ background: 'white', p: 2 }}>
          <Stack spacing={2}>
            {/* {JSON.stringify(getValues('primary_diagnosis'))} */}
            <Controller
              name="primary_diagnosis"
              control={control}
              render={({ field: { onChange, value } }) => (
                <AutocompleteDiagnosisControlled
                  onChange={onChange}
                  currentOptions={primaryDiagnosisOptions}
                  currentValue={value}
                  textLabel="Diagnosis Utama (ICD-X)"
                />
              )}
            />

            <Controller
              name="secondary_diagnosis"
              control={control}
              render={({ field: { onChange, value } }) => (
                <AutocompleteDiagnosisControlled
                  onChange={onChange}
                  currentOptions={secondaryDiagnosisOptions}
                  currentValue={value}
                  textLabel="Diagnosis Tambahan (ICD-X)"
                />
              )}
            />
          </Stack>
        </Paper>

        {(claim?.status == 'requested' || claim?.status == 'received') && (
          <LoadingButton
            variant="contained"
            sx={{ marginTop: 2 }}
            loading={loadingDiagnosis}
            onClick={() => {
              handleSaveDiagnosis();
            }}
          >
            Simpan Detail
          </LoadingButton>
        )}
    </Stack>
      </FormProvider>
  );
}
