import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';

import MuiDialog from "@/components/MuiDialog";
import { Button, Autocomplete, Card, Checkbox, DialogActions, Grid, Typography } from "@mui/material";
import { Paper } from "@mui/material";
import { Stack } from '@mui/material';
import React, { useEffect, useState } from 'react';
import { DetailFinalLogType } from "../Model/Types";
import { MedicineType } from "../Model/Types";
import { fDateTimesecond, toTitleCase } from "@/utils/formatTime";
import { useFieldArray, useForm } from 'react-hook-form';
import { FormProvider, RHFDatepicker, RHFSelect, RHFTextField } from '@/components/hook-form';

import axios from "@/utils/axios";
import { enqueueSnackbar } from "notistack";
import { useNavigate } from "react-router";
import { LoadingButton } from '@mui/lab';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import RHFTextFieldMoney from "@/components/hook-form/v2/RHFTextFieldMoney";
import { IconButton } from '@mui/material';
import { postAddMedince } from '../Model/Functions';

type DialogConfirmationType = {
    openDialog: boolean;
    setOpenDialog: any;
    onSubmit?: void;
    requestLog: DetailFinalLogType|undefined; 
}

export default function DialogMedicine({requestLog, setOpenDialog, openDialog } : DialogConfirmationType ) {
    const handleCloseDialogMedicine = () => {
        setOpenDialog(false);
    }

    const requestID = requestLog?.id

    const defaultValues: MedicineType = {
        medicine : [{
            id: 0,
            medicine_name: '',
            medicine_price: 0,
            request_log_id: requestID,
            medicine: '', // input to database
            price: 0, // input to database
        }],
    };

    const validationSchema = Yup.object().shape({
        medicine: Yup.array().of(
            Yup.object().shape({
                medicine_name : Yup.string().typeError('').required(''),
                medicine_price : Yup.number().typeError('').required(''),
                request_log_id : Yup.number().typeError('').required(''),
            })
        )
    })

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

    const {fields, append, remove} = useFieldArray({name: 'medicine',control: methods.control})
    
    useEffect(() => {
        let temp = fields.map((item, i) => {
            return {
                medicine_name: 'test',
                medicine_price: 0,
                request_log_id: 3,
            }
        })

        reset({medicine: temp})
    }, [])



    const { handleSubmit, reset, watch, setValue, formState: { isDirty, isSubmitting, errors } } = methods;
    // Submit Form
    // =====================================
    const submitHandler = async (data: MedicineType) => {
        const response = await postAddMedince(data);

        if (response == true) {
            reset();
            // navigate('custormer-service/final-log/detail/'+requestLog?.id);
            window.location.reload()
        }
    }

    const getContent = () => (
    <FormProvider methods={methods} onSubmit={handleSubmit(submitHandler)}>
        <Stack spacing={2} sx={{marginTop: 2, padding: 2}}>
            <Grid container spacing={2}>
                {/* Medicine */}
                <Grid item xs={12}>
                    <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                        <Typography variant='subtitle1' gutterBottom>Medicine*</Typography>
                        <Button color="inherit" variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => append({medicine_name: '', medicine_price: 0, request_log_id: requestLog?.id })}>
                            <Typography variant="button" display="block">Medicine</Typography>
                        </Button>
                    </Stack>
                </Grid>

                {fields.map((field, index) => (
                    <React.Fragment key={index}>
                        <Grid item xs={6}>
                        <RHFTextField
                            id='medicine_name'
                            key={field.id}
                            name={`medicine.${index}.medicine_name`}
                            label="Medicine"
                            required
                            placeholder="Medicine"
                        />
                        </Grid>
                        <Grid item xs={5}>
                        <RHFTextFieldMoney
                            id='medicine_price'
                            key={field.id}
                            name={`medicine.${index}.medicine_price`}
                            label="Price"
                            required
                            placeholder="Price"
                        />
                        </Grid>
                        {
                            index != (fields.length-1) ?
                                (
                                    <Grid item xs={1} sx={{ textAlign: 'center' }}>
                                        <IconButton size='large' color='error' onClick={() => remove(index)}>
                                            <RemoveIcon />
                                        </IconButton>
                                    </Grid>
                                ) : null
                            }
                        
                    </React.Fragment>
                ))}
                
            </Grid>
        </Stack>
        <DialogActions>
            <Stack direction="row" alignItems="center" justifyContent="space-between" spacing={2}>
                <Button color="inherit" variant="outlined" onClick={handleCloseDialogMedicine}><Typography>Cancel</Typography></Button>
                <LoadingButton disabled={!isDirty} type="submit" variant="contained" loading={isSubmitting}>
                    Add
                </LoadingButton>
            </Stack>
        </DialogActions>

    </FormProvider>
    );

    const getAction = () => null;


    return (
        <MuiDialog
          title={{name: "Medicine"}}
          openDialog={openDialog}
          setOpenDialog={setOpenDialog}
          action={getAction()}
          content={getContent()}
          maxWidth="xl"
        />
      );
}