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, { useRef, useEffect, useMemo, useState } from 'react';
import axios from '../../../utils/axios';
import { FormProvider, RHFDatepicker, RHFTextField } from '../../../components/hook-form';

import { makeFormData } from '@/utils/jsonToFormData';
import {
  Autocomplete,
  Button,
  Grid,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableRow,
  TextField,
  Typography,
  useTheme,
  List,
  ListItem,
  IconButton,
  ListItemAvatar,
  Avatar,
  ListItemText,
  Card,
  InputAdornment,
  Divider,
  ButtonBase,
  Box,
  DialogActions,
} from '@mui/material';
import Iconify from '../../../components/Iconify';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';
import { LoadingButton } from '@mui/lab';
import { fCurrency } from '../../../utils/formatNumber';
import MemberSelectDialog from '../../../components/dialogs/MemberSelectDialog';
import { Add, ArrowBackIosNew, DeleteOutline } from '@mui/icons-material';
import { ClaimRequest, Files } from '@/@types/claims';
import { fDateOnly, fDateTimesecond, fPostFormat } from '@/utils/formatTime';
import RHFDatePicker from '@/components/hook-form/RHFDatePickerV2';
import RHFDateTimePicker from '@/components/hook-form/v2/RHFDateTimePicker';
import MuiDialog from '@/components/MuiDialog';

interface FormValuesProps extends Partial<ClaimRequest> {
  taxes: boolean;
  inStock: boolean;
}

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

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

  const { enqueueSnackbar } = useSnackbar();

  const EditClaimSchema = Yup.object().shape({
    date: Yup.string().required('Date Submission is required'),
  });

  const defaultValues = useMemo(
    () => ({
      id: currentClaim?.id || '-',
      code: currentClaim?.code || '-',
      member_name: currentClaim?.name || '-',
      date: currentClaim?.submission_date ? fDateTimesecond(currentClaim?.submission_date) : '-',
      claim_method: currentClaim?.claim_method || '-',
      service_type: currentClaim?.service_type || '-',
      organization_id: currentClaim?.provider_code || '-',
    }),
    [currentClaim]
  );

  
  const [date, setDate] = useState(currentClaim?.submission_date ? fDateTimesecond(currentClaim?.submission_date) : null)
  const id  = currentClaim?.id

  useEffect(() => {
    setDate(currentClaim?.submission_date)
  }, [currentClaim]);

  useEffect(() => {
    if (isEdit && currentClaim) {
      reset(defaultValues);
    }
    if (!isEdit) {
      reset(defaultValues);
    }
  }, [isEdit, currentClaim]);


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

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


    // ----------------------------------------------------------------------
  const onSubmit = async (data: FormValuesProps) => {
    try {
      const formData = new FormData();
      // formData.append('result_files', fileHasilPenunjangs);
      // formData.append('diagnosa_files', fileDiagnosaInput);
      // formData.append('kondisi_files', fileKondisiInput);
      // formData.append('provider_code', data.organization_id);
      // formData.append('_method', 'PUT');
      // formData.append('date', fPostFormat(id));
      

      // const response = await axios.post(`/claim-requests/${data.id}/update`, formData);
      
      reset();
      enqueueSnackbar('Claim Request Updated Successfully!', { variant: 'success' });
      navigate('/claim-requests');
    } 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('Failed Processing Request', { variant: 'error' });
        }
      } else {
        enqueueSnackbar(error.message ?? 'Failed Processing Request', { variant: 'error' });
      }
    }
  };

  const handleApprove = () => {
    if(selectedReason.value != '-'){
      const formData = makeFormData({
        date: fPostFormat(date),
        reason: selectedReason.value,
      });
      const response = axios.post(`/claim-requests/${id}/update`, formData);

      if (!response.error){
        reset();
        enqueueSnackbar('Claim Request Updated Successfully!', { variant: 'success' });
        navigate('/claim-requests');
      } else {
        enqueueSnackbar('Claim Request Updated Error!', { variant: 'error' });
      }
    } else {
      setError('Please select a reason')
    }
  }
  const [openDialog, setOpenDialog] = useState(false);
  const style1 = {
    color: '#919EAB',
    width: '30%'
  }
  const style2 = {
      width: '70%'
  }
  const marginBottom1 = {
      marginBottom: 1,
  }
  const marginBottom2 = {
      marginBottom: 2,
  }
  const handleCloseDialog = () => {
      setOpenDialog(false);
  }

  const reason = [
    { value: 'Wrong Setting', label: 'Wrong Setting' },
    { value: 'Hospital Request', label: 'Hospital Request' }
  ];
  const [selectedReason, setSelectedReason] = React.useState({value:'-', label:''}); 
  const [error, setError] = useState('');

  const getContent = () => (
    <Stack spacing={1} marginTop={2}>
            <Typography variant="subtitle2">Are you sure to update this claim ?</Typography>
            <Grid item xs={12} md={12} marginTop={4}>
              <Card sx={{padding:2, marginTop:2}}  >
                  <Stack direction='row' spacing={2} sx={marginBottom1}>
                      <Typography variant='subtitle2' sx={style1} gutterBottom>Code</Typography>
                      <Typography variant='subtitle2' sx={style2} gutterBottom>{currentClaim?.code}</Typography>
                  </Stack>
                  <Stack direction='row' spacing={2} sx={marginBottom1}>
                      <Typography variant='subtitle2' sx={style1} gutterBottom>Name</Typography>
                      <Typography variant='subtitle2' sx={style2} gutterBottom>{currentClaim?.name}</Typography>
                  </Stack>
                  <Stack direction='row' spacing={2} sx={marginBottom1}>
                      <Typography variant='subtitle2' sx={style1} gutterBottom>Date of Submission</Typography>
                      <Typography variant='subtitle2' sx={style2} gutterBottom>{date ? fDateTimesecond(date) : '-'}</Typography>
                  </Stack>
                  <Stack direction='row' spacing={2} sx={marginBottom1}>
                      <Typography variant='subtitle2' sx={style1} gutterBottom>Claim Method</Typography>
                      <Typography variant='subtitle2' sx={style2} gutterBottom>{currentClaim?.claim_method}</Typography>
                  </Stack>
                  <Stack direction='row' spacing={2} sx={marginBottom1}>
                      <Typography variant='subtitle2' sx={style1} gutterBottom>Service Type</Typography>
                      <Typography variant='subtitle2' sx={style2} gutterBottom>{currentClaim?.service_type || '-'}</Typography>
                  </Stack>
                  <Stack direction='row' spacing={2} sx={marginBottom1}>
                      <Typography variant='subtitle2' sx={style1} gutterBottom>Code Provider</Typography>
                      <Typography variant='subtitle2' sx={style2} gutterBottom>{currentClaim?.provider_code || '-'}</Typography>
                  </Stack>
              </Card>
              <Card sx={{padding:2, marginTop:2}}  >
              <Typography variant="subtitle1" marginY={2}>Reason for Update*</Typography>
                  <Stack direction='row' spacing={2} sx={marginBottom2}>
                      <Autocomplete
                          options={reason}
                          getOptionLabel={(option) => option.label}
                          fullWidth
                          value={selectedReason} 
                          onChange={(event, newValue) => {
                              setSelectedReason(newValue);
                              // Validasi jika newValue adalah null
                              if (!newValue) {
                                  setError('Please select a reason');
                              } else {
                                  setError('');
                              }
                          }}
                          renderInput={(params) => (
                              <TextField
                                  {...params}
                                  label="Reason for updates"
                                  variant="outlined"
                                  name='reason'
                                  error={Boolean(error)} // Menampilkan error jika ada
                                  helperText={error} // Menampilkan pesan kesalahan
                              />
                          )}
                      />
                  </Stack>
              </Card>
            </Grid>
            <DialogActions>
                <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialog}>Cancel</Button>
                <Button color="primary"  variant="contained" onClick={() => handleApprove()}>Approve</Button>
            </DialogActions>
        </Stack>
  )

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
        <Stack direction="row" alignItems="center" sx={{ mb: 5 }}>
            <Box sx={{ display: 'flex', alignItems: 'center'}}>
                <IconButton size='large' color='inherit' onClick={() => navigate(`/claim-requests`)} >
                    <ArrowBackIosNew/>
                </IconButton>

                <Typography variant="h5" sx={{ marginLeft: '24px' }}>
                    {'Edit Claim Requests'}
                </Typography>
            </Box>
        </Stack>

      <Card sx={{paddingX:2, paddingY:2}}>
        <Grid container spacing={2}>
          <Grid item xs={5}>
            <Typography variant="subtitle1">Code*</Typography>
          </Grid>
          <Grid item xs={7}>
            <Typography variant="subtitle1">Name*</Typography>
          </Grid>
          <Grid item xs={5}>
            <RHFTextField name="code" label="Code" disabled/>
          </Grid>
          <Grid item xs={7}>
            <RHFTextField name="member_name" label="Name" disabled/>
          </Grid>
          {/* <input type="hidden" name="id"/> */}


          <Grid item xs={12}></Grid>

          <Grid item xs={3}>
            <Typography variant="subtitle1">Date of Submission*</Typography>
          </Grid>
          <Grid item xs={3}>
            <Typography variant="subtitle1">Claim Method*</Typography>
          </Grid>
          <Grid item xs={3}>
            <Typography variant="subtitle1">Service Type*</Typography>
          </Grid>
          <Grid item xs={3}>
            <Typography variant="subtitle1">Code Provider*</Typography>
          </Grid>


          <Grid item xs={3}>
              <Controller
                name="date"
                control={control}
                render={({ field }) => (
                    <RHFDateTimePicker
                        {...field}
                        label="Date of Submission"
                        value={field.value} 
                        onChange={() =>
                           setDate(field.value)
                        }
                        dateFormat='dd MMM yyyy HH:mm:ss'
                    />
                )}
               
            />
          </Grid>
          <Grid item xs={3}>
            <RHFTextField name="claim_method" label="Claim Method" disabled/>
          </Grid>
          <Grid item xs={3}>
            <RHFTextField name="service_type" label="Service Type*" disabled/>
          </Grid>
          <Grid item xs={3}>
            <RHFTextField name="organization_id" label="Code Provider*" disabled/>
          </Grid>
        </Grid>
      </Card>
      <Grid container marginTop={3}>
        <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(`/claim-requests`)}
              >
                Cancel
              </Button>
              <Button
                // type="submit"
                variant="contained"
                size="large"
                onClick={() => date ? setOpenDialog(true) :  setOpenDialog(false)}
              >
                Update
              </Button>
          </Stack>
        </Grid>
      </Grid>
      <MuiDialog
        title={{name: "Update Status"}}
        openDialog={openDialog}
        setOpenDialog={setOpenDialog}
        content={getContent()}
        maxWidth="md"
      />
    </FormProvider>
  );
}
