import * as Yup from 'yup';
import { useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
// form
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
// @mui
import { styled } from '@mui/material/styles';
import { LoadingButton } from '@mui/lab';
import {
  Box,
  Button,
  ButtonGroup,
  Card,
  FormHelperText,
  Grid,
  Stack,
  Typography,
} from '@mui/material';

import CancelIcon from '@mui/icons-material/Cancel';

// components
import {
  FormProvider,
  RHFTextField,
  RHFRadioGroup,
  RHFUploadAvatar,
  RHFSwitch,
  RHFEditor,
  RHFDatepicker,
  RHFMultiCheckbox,
  RHFCheckbox,
  RHFCustomMultiCheckbox,
} from '../../../components/hook-form';
import { Corporate } from '../../../@types/corporates';
import axios from '../../../utils/axios';
import { fCurrency } from '../../../utils/formatNumber';

const LabelStyle = styled(Typography)(({ theme }) => ({
  ...theme.typography.subtitle2,
  color: theme.palette.text.secondary,
  marginBottom: theme.spacing(1),
}));

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

type Props = {
  isEdit: boolean;
  currentFormularium?: Corporate;
};

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

  // const [ errors, setErrors ] = useState<{ [key: string]: string }>({});

  const { enqueueSnackbar } = useSnackbar();

  const NewCorporateSchema = Yup.object().shape({
    name: Yup.string().required('Name is required'),
    // code: Yup.string().required('Corporate Code is required'),
    // file: Yup.boolean().required('Corporate Status is required'),
  });

  const defaultValues = useMemo(
    () => ({
      code: currentFormularium?.code || '',
      name: currentFormularium?.name || '',
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [currentFormularium]
  );

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

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

  const values = watch();

  useEffect(() => {
    if (isEdit && currentFormularium) {
      reset(defaultValues);
    }
    if (!isEdit) {
      reset(defaultValues);
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEdit, currentFormularium]);

  const onSubmit = async (data: FormValuesProps) => {
    try {
      if (!isEdit) {
        const response = await axios.post('/master/formulariums', data);
      } else {
        const response = await axios.put('/master/formulariums/' + currentFormularium?.id ?? '', data);
      }
      reset();
      enqueueSnackbar(!isEdit ? 'Formularium Created Successfully!' : 'Formularium Udpated Successfully!', { variant: 'success' });
      navigate('/master/formularium');
    } 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 = "";
    }
  };

  const handleDrop = useCallback(
    (acceptedFiles) => {
      setValue(
        'logo',
        acceptedFiles.map((file: Blob | MediaSource) =>
          Object.assign(file, {
            preview: URL.createObjectURL(file),
          })
        )
      );
    },
    [setValue]
  );

  const handleRemove = (file: File | string) => {
    setValue('logo', null);
  };

  const linking_rules_checkbox_name = "linking_rules"
  const linking_tools = [
    {
      "value" : "nrik",
      "label" : "No. KTP"
    },
    {
      "value" : "nik",
      "label" : "Nomor Induk Karyawan (NIK)"
    },
    {
      "value" : "member_id",
      "label" : "Member ID"
    },
    {
      "value" : "phone",
      "label" : "Nomor Telepon"
    },
    {
      "value" : "email",
      "label" : "E-Mail"
    },
  ]
  

  const importForm = useRef<HTMLInputElement>(null) 
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [currentImportFileName, setCurrentImportFileName] = useState<string|null>(null);
  
  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleImportButton = () => {
    if (importForm?.current) {
      handleClose();
      importForm.current ? importForm.current.click() : console.log('No File selected');
    } else {
      alert('No file selected')
    }
  }

  const handleCancelImportButton = () => {
    importForm.current.value = "";
    importForm.current.dispatchEvent(new Event("change", { bubbles: true }));
  }

  const handleImportChange = (event: any) => {
    if (event.target.files[0]) {
      setCurrentImportFileName(event.target.files[0].name)
    } else {
      setCurrentImportFileName(null);
    }
  }


  return (

    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Stack spacing={3}>

        <Typography variant="h6">Formularium Detail</Typography>

        <div>
        <RHFTextField name="code" label="Code" />
        {(!(currentFormularium?.id) && <Typography variant="caption">Will be generated if empty</Typography>)}
        </div>

        <RHFTextField name="name" label="Name" />

        <Typography variant="h6">Formularium Drug List Import</Typography>

        <input type='file' id='file' ref={importForm} style={{ display: 'none' }} onChange={handleImportChange} accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain" />
        <ButtonGroup variant="outlined" aria-label="outlined button group" fullWidth>
            <Button onClick={handleImportButton} fullWidth>{currentImportFileName ?? "No File Selected"}</Button>
            {(currentImportFileName && <Button onClick={handleCancelImportButton} size="small" fullWidth={false} sx={{ p: 1.8 }}><CancelIcon color="error"/></Button>)}
        </ButtonGroup>

        <LoadingButton type="submit" variant="contained" size="large" fullWidth={true} loading={isSubmitting}>
          {!isEdit ? 'Save New Corporate' : 'Save Update'}
        </LoadingButton>

      </Stack>
    </FormProvider>
  );
};
