import * as Yup from 'yup';
import { LoadingButton } from '@mui/lab';
import { Card, Grid, Stack, Typography, Button } from '@mui/material';
import { CorporatePlan } from '../../../@types/corporates';
import { FormProvider, RHFEditor, RHFSwitch, RHFTextField } from '../../../components/hook-form';
import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useSnackbar } from 'notistack';
import { useNavigate, useParams } from 'react-router-dom';
import axios from '../../../utils/axios';
import MemberSelectDialog from '../../../components/dialogs/MemberSelectDialog';

type Props = {
  isEdit: boolean;
  currentCorporatePlan?: CorporatePlan;
};

export default function CorporatePlanForm({ isEdit, currentCorporatePlan }: Props) {
  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();
  const { corporate_id } = useParams();

  const NewCorporatePlanSchema = Yup.object().shape({
    code: Yup.string().required('Corporate Code is required'),
    service: Yup.string().required('Corporate Service is required'),
    plan: Yup.string().required('Corporate Plan is required'),
    type: Yup.string().required('Corporate Type is required'),
    limit: Yup.string().required('Corporate Limit is required'),
  });

  const defaultValues = useMemo(
    () => ({
      // name: currentCorporatePlan?.name || '',
      code: currentCorporatePlan?.code || '',
      // active: currentCorporatePlan?.active || true,
      type: currentCorporatePlan?.type || '',
      limit: currentCorporatePlan?.limit_rules || '',
      service: currentCorporatePlan?.service_code || '',
      plan: currentCorporatePlan?.corporate_plan_id || '',
    }),
    [currentCorporatePlan]
  );

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

  const methods = useForm({
    resolver: yupResolver(NewCorporatePlanSchema),
    defaultValues,
  });

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

  const onSubmit = async (data: any) => {
    console.log(data);
    if (!isEdit) {
      await axios
        .post('/corporates/' + corporate_id + '/corporate-plans', data)
        .then((res) => {
          enqueueSnackbar('Corporate Plan created successfully', { variant: 'success' });
        })
        .then((res) => {
          navigate(`/corporates/${corporate_id}/plans`, { replace: true });
        })
        .catch(({ response }) => {
          if (response.status === 422) {
            for (const [key, value] of Object.entries(response.data.errors)) {
              setError(key, { message: value[0] });
              enqueueSnackbar(value[0] ?? 'Failed Processing Request', { variant: 'error' });
            }
          } else {
            enqueueSnackbar('Create Failed : ' + response.data.message, { variant: 'error' });
          }
        });
    } else {
      await axios
        .put('/corporates/' + corporate_id + '/corporate-plans/' + currentCorporatePlan?.id, data)
        .then((res) => {
          enqueueSnackbar('Corporate Plan updated successfully', { variant: 'success' });
        })
        .then((res) => {
          navigate('/corporates/' + corporate_id + '/plans', { replace: true });
        })
        .catch(({ response }) => {
          enqueueSnackbar('Update Failed : ' + response.data.message, { variant: 'error' });
        });
    }
  };

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Card sx={{ p: 2, marginTop: 2 }}>
        <Grid container spacing={4} paddingX={2} paddingY={2}>
          <Grid item xs={3}>
            <Typography variant="subtitle1">Service*</Typography>
            <RHFTextField name="service" label="service" sx={{marginTop:2}}/>
          </Grid>
          <Grid item xs={3}>
            <Typography variant="subtitle1">Plan*</Typography>
            <RHFTextField name="plan" label="plan" sx={{marginTop:2}} />
          </Grid>
          <Grid item xs={3}>
            <Typography variant="subtitle1">Code*</Typography>
            <RHFTextField name="code" label="code" sx={{marginTop:2}} />
          </Grid>
          <Grid item xs={3}>
            <Typography variant="subtitle1">Type*</Typography>
            <RHFTextField name="type" label="type" sx={{marginTop:2}} />
          </Grid>
          <Grid item xs={6}>
            <Typography variant="subtitle1">Plan Limit*</Typography>
            <RHFTextField name="limit" label="limit" sx={{marginTop:2}} />
          </Grid>

          {/* <Grid item xs={3}>
            <Stack spacing={3}>
              <Typography variant="h6">Corporate Plan Detail</Typography>

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

              <RHFTextField name="code" label="Code" />

              <Stack spacing={1}>
                <Typography variant="subtitle2" sx={{ color: 'text.secondary' }}>
                  Description
                </Typography>
                <RHFEditor name="description" />
              </Stack>

              <LoadingButton
                type="submit"
                variant="contained"
                size="large"
                fullWidth={true}
                loading={isSubmitting}
              >
                { isEdit ? 'Update' : 'Create'} Corporate Plan
              </LoadingButton>
            </Stack>
          </Grid> */}
        </Grid>
      </Card>
      <Stack direction="row" alignItems="center" justifyContent="flex-end">
            <Button
              sx={{marginTop:2}}
              type="submit"
              variant="contained"
              size="large"
              color='inherit'
              onClick={() => navigate(`/corporates/${corporate_id}/plans`)}
              
            >
              Cancel
            </Button>
            <LoadingButton
              type="submit"
              variant="contained"
              size="large"
              // fullWidth={true}
              loading={isSubmitting}
              sx={{marginTop:2, marginLeft:2}}
            >
              Save
            </LoadingButton>
        </Stack>
    </FormProvider>
  );
}
