import * as Yup from 'yup';
import { useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';
import { yupResolver } from '@hookform/resolvers/yup';
import { Controller, useForm } from 'react-hook-form';
import React, { useEffect, useMemo, useState } from 'react';
import axios from '../../utils/axios';
import { FormProvider, RHFTextField } from '../../components/hook-form';
import {
  Autocomplete,
  Button,
  Grid,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableRow,
  TextField,
  Typography,
  useTheme,
  List,
  ListItem,
  IconButton,
  ListItemAvatar,
  Avatar,
  ListItemText,
  Card,
} from '@mui/material';
import Iconify from '../../components/Iconify';
import { LoadingButton } from '@mui/lab';
import { fCurrency } from '../../utils/formatNumber';
import MemberSelectDialog from '../../components/dialogs/MemberSelectDialog';
import { Add, DeleteOutline } from '@mui/icons-material';
import { ClaimsEdit } from '@/@types/claims';

type Props = {
  isEdit: boolean;
  currentClaim?: ClaimsEdit;
};

export default function ClaimForm({ isEdit, currentClaim }: Props) {
  const navigate = useNavigate();

  const { enqueueSnackbar } = useSnackbar();

  const NewCorporateSchema = Yup.object().shape({
    benefit_desc: Yup.string().required('Benefit Desc is required'),
    amount_incurred: Yup.string().required('Amount Incurred is required'),
    amount_approved: Yup.number().required('Amount Approved is required'),
    amount_not_approved: Yup.number().required('Amount Not Approved is required'),
    excess_paid: Yup.number().required('Excess Paid is required'),
    // file: Yup.boolean().required('Corporate Status is required'),
  });

  const defaultValues = useMemo(
    () => ({
      plan_id: currentClaim?.plan_id || null,
      payor_id: currentClaim?.payor_id || null,
      corporate_id: currentClaim?.corporate_id || null,
      policy_number: currentClaim?.policy_number || null,
      member_id: currentClaim?.member_id || null,
      benefit_code: currentClaim?.benefit_code || '-',
      benefit_desc: currentClaim?.benefit_desc || '-',
      amount_incurred: currentClaim?.amount_incurred || 0,
      amount_approved: currentClaim?.amount_approved || 0,
      amount_not_approved: currentClaim?.amount_not_approved || 0,
      excess_paid: currentClaim?.excess_paid || 0,
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [currentClaim]
  );

  const methods = useForm<any>({
    resolver: yupResolver(NewCorporateSchema),
    defaultValues,
  });
  const {
    reset,
    watch,
    control,
    setValue,
    getValues,
    setError,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  const [isCheckingLimit, setIsCheckingLimit] = useState(false);
  const [isEligible, setIsEligible] = useState(false);
  const [memberBenefits, setMemberBenefits] = useState([]);
  const [diagnosisOption, setDiagnosisOption] = useState([]);
  const [isMemberDialogOpen, setIsMemberDialogOpen] = useState(false);
  const [member, setMember] = useState({})

  
  useEffect(() => {
    console.log('defaultValues', defaultValues);
    if (isEdit && currentClaim) {
      reset(defaultValues);
      // setMember(defaultValues.member)
    }
    if (!isEdit) {
      reset(defaultValues);
      // setMember(defaultValues.member)
    }
  }, [isEdit, currentClaim]);

  const fileSelected = (event, type) => {
    const files = event.target.files;
    const currentFiles = getValues(`uploaded_files.${type}`) ?? [];

    setValue(`uploaded_files.${type}`, [...currentFiles, ...files]);

    console.log('currentFiles', getValues('uploaded_files'));
  };

  // const memberSelected = (member) => {
  //   setMember(member)
  // };

  // const checkLimit = async () => {
  //   console.log('CHECKING LIMIT');
  // };

  const onSubmit = async (data: any) => {
    try {
      if (!isEdit) {
        const response = await axios.post('/claims', data);
      } else {
        const response = await axios.put('/claims/' + currentClaim?.id ?? '', data);
      }
      reset();
      enqueueSnackbar(
        !isEdit ? 'Organizations Created Successfully!' : 'Claim Udpated Successfully!',
        { variant: 'success' }
      );
      navigate('/claims');
    } catch (error: any) {
      if (error && error.response.status === 422) {
        for (const [key, value] of Object.entries(error.response.data.errors)) {
          setError(key, { message: value[0] });
          enqueueSnackbar(value[0] ?? 'Failed Processing Request', { variant: 'error' });
        }
      } else {
        enqueueSnackbar(error.message ?? 'Failed Processing Request', { variant: 'error' });
      }
    }

    const ascent = document?.querySelector('ascent');
    if (ascent != null) {
      ascent.innerHTML = '';
    }
  };

  function generate(files, element: React.ReactElement) {
    return files.map((value) =>
      React.cloneElement(element, {
        key: value,
      })
    );
  }

  const headStyle = {};
  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
        <Card sx={{paddingX:2, paddingY:3}}>
          <Grid container spacing={2}>
            {/* Baris ke 1 */}
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Plan ID*</Typography>
              <RHFTextField name="plan_id" disabled />
            </Grid>
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Payor ID*</Typography>
              <RHFTextField name="payor_id" disabled />
            </Grid>
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Corporate ID*</Typography>
              <RHFTextField name="corporate_id"disabled />
            </Grid>
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Policy Number*</Typography>
              <RHFTextField name="policy_number" disabled />
            </Grid>

            {/* Baris ke 2 */}
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Memeber ID*</Typography>
              <RHFTextField name="member_id" disabled />
            </Grid>
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Benefit Code*</Typography>
              <RHFTextField name="benefit_code" disabled />
            </Grid>
            <Grid item xs={6}>
              <Typography marginBottom={2} variant="subtitle1">Benefit Desc*</Typography>
              <RHFTextField name="benefit_desc" label="Benefit Desc" />
            </Grid>

            {/* Baris ke 3 */}
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Amount Incurred*</Typography>
              <RHFTextField name="amount_incurred" label="Amount Incurred" type="number" />
            </Grid>
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Amount Approved*</Typography>
              <RHFTextField name="amount_approved" label="Amount Approved" type="number" />
            </Grid>
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Amount Not Approved*</Typography>
              <RHFTextField name="amount_not_approved" label="Amount Not Approved" type="number" />
            </Grid>
            <Grid item xs={3}>
              <Typography marginBottom={2} variant="subtitle1">Excess Paid*</Typography>
              <RHFTextField name="excess_paid" label="Excess Paid*" type="number" />
            </Grid>
          </Grid>
        </Card>
        <Grid container marginTop={2}>
          <Grid item xs={12} md={12} >
          <Stack direction="row" alignItems="center" justifyContent="flex-end">
              <Button
                sx={{
                  margin: 1
                }}
                type="submit"
                variant="contained"
                size="large"
                color='inherit'
                onClick={() => navigate(`/claims`)}
              >
                Cancel
              </Button>
              <LoadingButton
                type="submit"
                variant="contained"
                size="large"
                // fullWidth={true}
                loading={isSubmitting}
              >
                Save
              </LoadingButton>
          </Stack>
          </Grid>
        </Grid>
      </FormProvider>
  );
}
