import * as Yup from 'yup';
import { useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';
import { useCallback, useEffect, useMemo, useState } from 'react';
// form
import { Controller, 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,
  Card,
  FormControl,
  FormControlLabel,
  FormHelperText,
  FormLabel,
  Grid,
  InputLabel,
  Menu,
  MenuItem,
  OutlinedInput,
  Radio,
  RadioGroup,
  Select,
  SelectChangeEvent,
  Stack,
  Typography,
} from '@mui/material';

// components
import {
  FormProvider,
  RHFTextField,
  RHFRadioGroup,
  RHFUploadAvatar,
  RHFSwitch,
  RHFEditor,
  RHFDatepicker,
  RHFMultiCheckbox,
  RHFCheckbox,
  RHFCustomMultiCheckbox,
  RHFSelect,
} from '../../components/hook-form';
import { Corporate } from '../../@types/corporates';
import axios from '../../utils/axios';
import { fCurrency } from '../../utils/formatNumber';
import RHFAutocomplete from '../../components/hook-form/RHFAutocomplete';
import UploadImage from '../../components/UploadImage';
import { fPostFormat } from '@/utils/formatTime';
import AddIcon from '@mui/icons-material/Add';
import Link from '@/theme/overrides/Link';

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;
  currentCorporate?: Corporate;
};

export default function CorporateForm({ isEdit, currentCorporate }: Props) {
  const navigate = useNavigate();
  const [corporate_groups, setCorporateGroups] = useState([]);

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

  const { enqueueSnackbar } = useSnackbar();
  let NewCorporateSchema = null;
  if (isEdit) {
    NewCorporateSchema = Yup.object().shape({
      isEdited: Yup.boolean(),
      name: Yup.string().required('Name is required'),
      code: Yup.string().required('Corporate Code is required'),
      active: Yup.boolean().required('Corporate Status is required'),
      type: Yup.string().required('Type is required'),
      welcome_message: Yup.string().required('Welcome Message is required'),
      help_text: Yup.string().required('Help Text is required'),
      // policy_code: Yup.string().required('Policy Code is required'),
      policy_start: Yup.date().required('Start Date is required'),
      policy_end: Yup.date()
        .required('End Date is required')
        .min(Yup.ref('policy_start'), "end date can't be before start date"),
      policy_total_premi: Yup.number().required('Deposit Initial Fund is required').min(0),
      // linking_rules: Yup.string().required('Link Rules is required'),
      policy_minimal_deposit_percentage: Yup.number()
        .typeError('Please enter a valid number')
        .required('Percentage Deposit is required')
        .min(0, 'Minimum atleast 0')
        .max(100, 'Allowed maximum is 100'),
      policy_minimal_alert_percentage: Yup.number()
        .typeError('Please enter a valid number')
        .required('Percentage Alert is required')
        .min(0, 'Minimum atleast 0')
        .max(100, 'Allowed maximum is 100'),
      policy_stop_service_percentage: Yup.number()
        .typeError('Please enter a valid number')
        .min(0, 'Minimum atleast 0')
        .max(100, 'Allowed maximum is 100')
        .required('Percentage Stop is required'),
      // .test('max', 'Total should not exceed 100 %', function (value) {
      //   const { policy_minimal_alert_percentage } = this.parent;
      //   const { policy_minimal_deposit_percentage } = this.parent;
      //   return value == 100 - policy_minimal_alert_percentage - policy_minimal_deposit_percentage;
      // }),
      parent_id: Yup.string().when('type', {
        is: 'subcorporate',
        then: Yup.string().required('Corporate is required because type is Sub Corporate'),
      }),

      reason: Yup.string().required('Reason for update is required when editing data'),
    });
  } else {
    // console.log('test')
    NewCorporateSchema = Yup.object().shape({
      isEdited: Yup.boolean(),
      name: Yup.string().required('Name is required'),
     
      code: Yup.string()
        .required('Corporate Code is required')
        .test('unique-code', 'Code must be unique', async function (value) {
          const existingCodes = await getExistingCodes();
          return !existingCodes.includes(value);
      }),
      // payor_id: Yup.string().required('Payor is required'),
      active: Yup.boolean().required('Corporate Status is required'),
      type: Yup.string().required('Type is required'),
      welcome_message: Yup.string().required('Welcome Message is required'),
      help_text: Yup.string().required('Help Text is required'),
      // policy_code: Yup.string().required('Policy Code is required'),
      policy_start: Yup.date().required('Start Date is required'),
      policy_end: Yup.date()
        .required('End Date is required')
        .min(Yup.ref('policy_start'), "end date can't be before start date"),
      policy_total_premi: Yup.number().required('Deposit Initial Fund is required').min(0),
      // linking_rules: Yup.string().required('Link Rules is required'),
      policy_minimal_deposit_percentage: Yup.number()
        .typeError('Please enter a valid number')
        .required('Percentage Deposit is required')
        .min(0, 'Minimum atleast 0')
        .max(100, 'Allowed maximum is 100'),
      policy_minimal_alert_percentage: Yup.number()
        .typeError('Please enter a valid number')
        .required('Percentage Alert is required')
        .min(0, 'Minimum atleast 0')
        .max(100, 'Allowed maximum is 100'),
      policy_stop_service_percentage: Yup.number()
        .typeError('Please enter a valid number')
        .min(0, 'Minimum atleast 0')
        .max(100, 'Allowed maximum is 100')
        .required('Percentage Stop is required'),
      // .test('max', 'Total should not exceed 100 %', function (value) {
      //   const { policy_minimal_alert_percentage } = this.parent;
      //   const { policy_minimal_deposit_percentage } = this.parent;
      //   return value == 100 - policy_minimal_alert_percentage - policy_minimal_deposit_percentage;
      // }),
      parent_id: Yup.string().when('type', {
        is: 'subcorporate',
        then: Yup.string().required('Corporate is required because type is Sub Corporate'),
      }),
    });
  }

  async function getExistingCodes() {
    // axios
    // .get('/corporates/create')
    // .then((res) => {
    //   setCorporateGroups(res.data.corporate_groups);
    // })
    // .catch((err) => {
    //   enqueueSnackbar('Opps, failed to get Corporate Group List', { variant: 'error' });
    // });

    try {
      let response = await axios.get('/corporates/1/code'); // get data all corporate
      let codeCurrent = '';
      if (isEdit) {
        let responseCodeCurrent = await axios.get(`/corporates/${currentCorporate?.id}/edit`); // get data current corporate
        codeCurrent = responseCodeCurrent.data.code; // get data code corporate current
      }
      // console.log(response.data);
      let existingCodes = response.data.map((item) => item); // get data code corporate all

      let filteredArray = existingCodes.filter((e) => e != codeCurrent);
      return filteredArray;
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Failed to fetch existing codes', { variant: 'error' });
    }
  }

  async function getExistingPayorId() {
    // axios
    // .get('/corporates/create')
    // .then((res) => {
    //   setCorporateGroups(res.data.corporate_groups);
    // })
    // .catch((err) => {
    //   enqueueSnackbar('Opps, failed to get Corporate Group List', { variant: 'error' });
    // });

    try {
      let response = await axios.get('/corporates/1/code'); // get data all corporate
      let codeCurrent = '';
      if (isEdit) {
        let responseCodeCurrent = await axios.get(`/corporates/${currentCorporate?.id}/edit`); // get data current corporate
        codeCurrent = responseCodeCurrent.data.payor_id; // get data code corporate current
      }
      // console.log(response.data);
      let existingCodes = response.data.map((item) => item); // get data code corporate all

      let filteredArray = existingCodes.filter((e) => e != codeCurrent);
      console.log(filteredArray);
      return filteredArray;
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Failed to fetch existing codes', { variant: 'error' });
    }
  }

  const defaultValues = useMemo(
    () => ({
      code: currentCorporate?.code || '',
      name: currentCorporate?.name || '',
      reason: currentCorporate?.reason || '',
      payor_id: currentCorporate?.payor_id || '',
      welcome_message: currentCorporate?.welcome_message || '',
      help_text: currentCorporate?.help_text || '',
      active: currentCorporate?.id ? currentCorporate?.active === 1 : true,
      automatic_linking: currentCorporate?.id ? currentCorporate?.automatic_linking === 1 : true,
      policy_id: currentCorporate?.current_policy?.id || '',
      policy_code: currentCorporate?.current_policy?.code || '',
      policy_total_premi: currentCorporate?.current_policy?.total_premi || 0,
      policy_minimal_deposit_percentage:
        currentCorporate?.current_policy?.minimal_deposit_percentage || 50,
      policy_minimal_deposit_net: currentCorporate?.current_policy?.minimal_deposit_net || 0,
      policy_minimal_alert_percentage:
        currentCorporate?.current_policy?.minimal_alert_percentage || 25,
      policy_minimal_alert_net: currentCorporate?.current_policy?.minimal_alert_net || 0,
      policy_stop_service_percentage:
        currentCorporate?.current_policy?.minimal_stop_service_percentage || 25,
      policy_stop_service_net: currentCorporate?.current_policy?.minimal_stop_service_net || 0,
      policy_start: currentCorporate?.current_policy?.start || '',
      policy_end: currentCorporate?.current_policy?.end || '',
      linking_rules: currentCorporate?.linking_rules || ['nric', 'nik', 'member_id'],
      type: currentCorporate?.type || 'corporate',
      logo: currentCorporate?.logo || '',
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [currentCorporate]
  );

  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 && currentCorporate) {
      reset(defaultValues);
    }
    if (!isEdit) {
      reset(defaultValues);
    }

    axios
      .get('/corporates/create')
      .then((res) => {
        setCorporateGroups(res.data.corporate_groups);
      })
      .catch((err) => {
        enqueueSnackbar('Opps, failed to get Corporate Group List', { variant: 'error' });
      });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEdit, currentCorporate]);
  const currentImage = currentCorporate?.avatar_url;
  const [file, setFile] = useState(null);
  const [save, setSave] = useState(null);

  // console.log('save', save);

  const onSubmit = async (data: FormValuesProps) => {
    try {
      const formData = new FormData();
      formData.append('logo', file);
      formData.append('name', data.name);
      formData.append('code', data.code);
      formData.append('active', data.active ? '1' : '0');
      formData.append('automatic_linking', data.automatic_linking ? 1 : 0);
      formData.append('type', data.type);
      formData.append('welcome_message', data.welcome_message);
      formData.append('reason', data.reason);
      formData.append('help_text', data.help_text);
      formData.append('policy_id', data.policy_id);
      formData.append('payor_id', data.payor_id);
      formData.append('policy_code', data.policy_code);
      formData.append('policy_total_premi', data.policy_total_premi);
      formData.append('policy_minimal_deposit_percentage', data.policy_minimal_deposit_percentage);
      formData.append('policy_minimal_deposit_net', data.policy_minimal_deposit_net);
      formData.append('policy_minimal_alert_percentage', data.policy_minimal_alert_percentage);
      formData.append('policy_minimal_alert_net', data.policy_minimal_alert_net);
      formData.append('policy_stop_service_percentage', data.policy_stop_service_percentage);
      formData.append('policy_stop_service_net', data.policy_stop_service_net);
      formData.append('policy_start', fPostFormat(data.policy_start));
      formData.append('policy_end', fPostFormat(data.policy_end));
      formData.append('linking_rules', data.linking_rules);

      // console.log('MOTHERFUCKER', data.linking_rules)

      if (!isEdit) {
        const response = await axios.post('/corporates', formData);
      } else {
        formData.append('_method', 'PUT');
        const response = await axios.post(`/corporates/${currentCorporate?.id}`, formData);
      }
      reset();
      enqueueSnackbar(
        !isEdit ? 'Corporate Created Successfully!' : 'Corporate Updated Successfully!',
        { variant: 'success' }
      );
      navigate('/corporates');
    } 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' });
        // }
        for (const [key, value] of Object.entries(error.response.data.errors)) {
          // setError(key, { message: value[0] });
          enqueueSnackbar(value ?? 'Failed Processing Request', { variant: 'error' });
        }
      } else {
        enqueueSnackbar(error.message ?? 'Failed Processing Request', { variant: 'error' });
      }
    }
  };

  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);
  };

  // Only Handle Change on Policy Total Premi
  useEffect(() => {
    let calc_policy_minimal_deposit_net =
      (values.policy_total_premi * values.policy_minimal_deposit_percentage) / 100;
    setValue('policy_minimal_deposit_net', calc_policy_minimal_deposit_net);

    let calc_policy_minimal_alert_net =
      (values.policy_total_premi * values.policy_minimal_alert_percentage) / 100;
    setValue('policy_minimal_alert_net', calc_policy_minimal_alert_net);

    let calc_policy_stop_service_net =
      (values.policy_total_premi * values.policy_stop_service_percentage) / 100;
    setValue('policy_stop_service_net', calc_policy_stop_service_net);
  }, [values.policy_total_premi]);

  // Only Handle on Change Policy Minimal Deposit
  const handleMinimalDepositNetChange = (e) => {
    setValue('policy_minimal_deposit_net', e.target.value);
    setValue(
      'policy_minimal_deposit_percentage',
      (e.target.value / values.policy_total_premi) * 100
    );
  };
  const handleMinimalDepositPercentageChange = (e) => {
    setValue('policy_minimal_deposit_percentage', e.target.value);
    setValue('policy_minimal_deposit_net', (values.policy_total_premi * e.target.value) / 100);
  };
  // Only Handle on Change Minimal Alert
  const handleMinimalAlertNetChange = (e) => {
    setValue('policy_minimal_alert_net', e.target.value);
    setValue('policy_minimal_alert_percentage', (e.target.value / values.policy_total_premi) * 100);
  };
  const handleMinimalAlertPercentageChange = (e) => {
    setValue('policy_minimal_alert_percentage', e.target.value);
    setValue('policy_minimal_alert_net', (values.policy_total_premi * e.target.value) / 100);
  };
  // Only Handle on Change Minimum Stop Service
  const handleStopServiceNetChange = (e) => {
    setValue('policy_stop_service_net', e.target.value);
    setValue('policy_stop_service_percentage', (e.target.value / values.policy_total_premi) * 100);
  };
  const handleStopServicePercentageChange = (e) => {
    setValue('policy_stop_service_percentage', e.target.value);
    setValue('policy_stop_service_net', (values.policy_total_premi * e.target.value) / 100);
  };

  const linking_rules_checkbox_name = 'linking_rules';
  const linking_tools = [
    {
      value: 'nric',
      label: 'No. KTP',
    },
    {
      value: 'nik',
      label: 'Nomor Induk Karyawan (NIK)',
    },
    {
      value: 'member_id',
      label: 'Member ID',
    },
    {
      value: 'policy_code',
      label: 'Policy Number',
    },
    {
      value: 'phone',
      label: 'Nomor Telepon',
    },
    {
      value: 'email',
      label: 'E-Mail',
    },
    {
      value: 'name',
      label: 'Nama Lengkap',
    },
    {
      value: 'dob',
      label: 'Tanggal Lahir',
    },
  ];

  const types = [
    {
      value: 'corporate',
      label: 'Corporate',
    },
    {
      value: 'subcorporate',
      label: 'Sub Corporate',
    },
  ];

  const options = [
    {
      label: 'Something',
      id: 'Something',
    },
    {
      label: 'Syalalalal',
      id: 'Syalalalal',
    },
    {
      label: 'Lilili',
      id: 'Lilili',
    },
  ];
  const [isDisabled, setIsDisabled] = useState(isEdit);
  const handleTypeChange = (event: SelectChangeEvent) => {
    setValue('type', event.target.value);
  };

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      {/* <Card sx={{ p:3, mb:3, background: 'gray', color: 'white' }}><Typography>Corporate Detail</Typography></Card> */}
      <Grid container spacing={3}>
        <Grid item xs={12} md={8}>
          <Card sx={{ p: 3 }}>
            <Stack spacing={3}>
              <Grid item xs={12}>
                <Typography variant="h5" color={'primary'}>Corporate Profile</Typography>
              </Grid>

              <Typography variant='subtitle1' color="#637381">Corporate Profile*</Typography>
              <RHFSelect name="type" label="Type" placeholder="Type">
                <option value="" />
                {types.map((option, index) => (
                  <option key={index} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </RHFSelect>

              {/* // TODO Use Autocomplete */}
              {values.type == 'subcorporate' && (
                <RHFSelect
                  name="parent_id"
                  label="Parent Corporate Group"
                  placeholder="Parent Corporate Group"
                >
                  <option value="" />
                  {corporate_groups
                    .filter((option) => option.value != values.id)
                    .map((option, index) => (
                      <option key={index} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                </RHFSelect>
              )}
              <Typography variant='subtitle1' color="#637381">Corporate Code*</Typography>
              <RHFTextField name="code" label="Corporate Code" disabled={isDisabled} />

              <Typography variant='subtitle1' color="#637381">Corporate Name*</Typography>
              <RHFTextField name="name" label="Corporate Name" disabled={isDisabled} />

              <Typography variant='subtitle1' color="#637381">Payor ID*</Typography>
              <RHFTextField name="payor_id" label="Payor ID" disabled={isDisabled} />

              {isEdit && (
                // <RHFTextField name="reason" label="Reason for update" />
                <RHFSelect name="reason" label="Reason for update">
                  <option value=""></option>
                  <option value="Agreement changed">Agreement changed</option>
                  <option value="Endorsement">Endorsement</option>
                  <option value="Renewal">Renewal</option>
                  <option value="Wrong Setting">Wrong Setting</option>
                </RHFSelect>
              )}

              <Stack spacing={1}>
                <Typography variant="subtitle1" color="#637381">
                  Welcome Message *
                </Typography>
                <RHFEditor name="welcome_message" placeholder="Akun anda telah terverifikasi"/>
              </Stack>

              <Stack spacing={1}>
                <Typography variant="subtitle1" color="#637381">
                  Help Text *
                </Typography>
                <RHFEditor name="help_text" />
              </Stack>

              {/* <div>
                <LabelStyle>Images</LabelStyle>
                <RHFUploadMultiFile
                  name="images"
                  files={[]}
                  showPreview
                  accept="image/*"
                  maxSize={3145728}
                  onDrop={handleDrop}
                  onRemove={handleRemove}
                  onRemoveAll={handleRemoveAll}
                />
              </div> */}
            </Stack>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Stack spacing={3}>
            <Card sx={{ p: 3 }}>
              <Stack spacing={3} mt={2}>
                <Stack spacing={3} alignItems="center">
                  <Typography align="center">Company Logo</Typography>
                  {/* <RHFUploadAvatar
                  name="logo"
                  showPreview
                  accept="image/*"
                  maxSize={3145728}
                  onDrop={handleDrop}
                  onRemove={handleRemove}
                /> */}
                  <UploadImage setFile={setFile} currentImage={currentImage} />
                </Stack>
                <Box>
                  <Box
                    sx={{ display: 'flex', placeContent: 'space-between', placeItems: 'center' }}
                  >
                    <Typography>Company Active</Typography>
                    <RHFSwitch name="active" label="" labelPlacement="start" />
                  </Box>
                  <Box
                    sx={{ display: 'flex', placeContent: 'space-between', placeItems: 'center' }}
                  >
                    <Typography>Company Automatic Linking</Typography>
                    <RHFSwitch name="automatic_linking" label="" labelPlacement="start" />
                  </Box>
                </Box>
              </Stack>
            </Card>
            <Card sx={{ p: 3 }}>
              <Stack>
                <Typography variant="subtitle2" sx={{ color: 'text.secondary' }}>
                  Linking Rules
                </Typography>
                <Stack>
                  <RHFCustomMultiCheckbox name="linking_rules" options={linking_tools} />
                </Stack>
              </Stack>
            </Card>
          </Stack>
        </Grid>

        {values.type == 'corporate' && (
          <Grid item xs={12} md={12}>
            {/* <Card sx={{ p:3, mb:3, background: 'gray', color: 'white' }}><Typography>Policy Detail</Typography></Card> */}
            <Card sx={{ p: 3 }}>
              <Stack spacing={3} mt={2}>
                <Typography variant="h5" color={'primary'}>Policy Detail</Typography>

                <input type="hidden" name="policy_id" />

                <Stack spacing={1}>
                  <Typography variant="subtitle2">Policy Number*</Typography>
                  <RHFTextField name="policy_code" label="Policy Number" />
                  {!currentCorporate?.id && (
                    <Typography variant="caption">Will be generated if empty</Typography>
                  )}
                </Stack>

                <Stack direction="row" spacing={2}>
                  <Grid item xs={12} md={6}>
                    <Typography variant="subtitle2" sx={{marginBottom: '10px'}}>Tanggal Mulai Kerjasama*</Typography>
                    <RHFDatepicker name="policy_start" label="Start Date *" />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Typography variant="subtitle2" sx={{marginBottom: '10px'}}>Tanggal Akhir Kerjasama*</Typography>
                    <RHFDatepicker name="policy_end" label="End Date *" />
                  </Grid>
                </Stack>

                <Typography variant="subtitle2">Deposit Intial Fund*</Typography>
                <RHFTextField
                  name="policy_total_premi"
                  label={'Deposit Intial Fund (' + fCurrency(values.policy_total_premi) + ')'}
                />

                <Grid item xs={12}>
                  <Grid container spacing={2}>
                    <Grid item xs={12}>
                      <Typography variant="subtitle2">
                        Minimal Deposit Policy Level
                      </Typography>
                    </Grid>
                    <Grid item xs={12} md={3}>
                      <RHFTextField
                        name="policy_minimal_deposit_percentage"
                        label="Percentage (%)"
                        onChange={handleMinimalDepositPercentageChange}
                      />
                    </Grid>
                    <Grid item xs={12} md={9}>
                      <RHFTextField
                        name="policy_minimal_deposit_net"
                        label={'Net (' + fCurrency(values.policy_minimal_deposit_net) + ')'}
                        onChange={handleMinimalDepositNetChange}
                      />
                    </Grid>
                  </Grid>
                </Grid>

                <Grid item xs={12}>
                  <Grid container spacing={2}>
                    <Grid item xs={12}>
                      <Typography variant="subtitle2">
                        Minimal Alert Level
                      </Typography>
                    </Grid>
                    <Grid item xs={12} md={3}>
                      <RHFTextField
                        name="policy_minimal_alert_percentage"
                        label="Percentage (%)"
                        onChange={handleMinimalAlertPercentageChange}
                      />
                    </Grid>
                    <Grid item xs={12} md={9}>
                      <RHFTextField
                        name="policy_minimal_alert_net"
                        label={'Net (' + fCurrency(values.policy_minimal_alert_net) + ')'}
                        onChange={handleMinimalAlertNetChange}
                      />
                    </Grid>
                  </Grid>
                </Grid>

                <Grid item xs={12}>
                  <Grid container spacing={2}>
                    <Grid item xs={12}>
                      <Typography variant="subtitle2">
                        Stop Service Level
                      </Typography>
                    </Grid>
                    <Grid item xs={12} md={3}>
                      <RHFTextField
                        name="policy_stop_service_percentage"
                        label="Percentage (%)"
                        onChange={handleStopServicePercentageChange}
                      />
                    </Grid>
                    <Grid item xs={12} md={9}>
                      <RHFTextField
                        name="policy_stop_service_net"
                        label={'Net (' + fCurrency(values.policy_stop_service_net) + ')'}
                        onChange={handleStopServiceNetChange}
                      />
                    </Grid>
                  </Grid>
                </Grid>
              </Stack>
            </Card>
          </Grid>
        )}

      {/* Type contrack */}
        {/* <Grid item xs={12} md={12}>
            <Card sx={{ p: 3 }}>
              <Stack direction="row" spacing={2}>
                  <Grid item xs={12} md={6}>
                    <Typography variant="h5" color="#19BBBB">Tipe Pembayaran</Typography>
                  </Grid>
                  <Grid container item xs={12} md={12} justifyContent="flex-end">
                    <Button
                      size='small'
                      variant="contained"
                      startIcon={<AddIcon sx={{ color: 'black', fontWeight: 'bold' }} />}
                      sx={{ p: 1.8, typography: 'subtitle2', backgroundColor: '#DFE3E8' }}
                    >
                      <Typography variant="subtitle2" color="black">Contract</Typography>
                    </Button>
                  </Grid>
              </Stack>

              <Grid item xs={12} md={12}>
                <Typography variant="h5">#1</Typography>
              </Grid>

              <Stack direction="row" spacing={4} sx={{marginTop: '24px'}}>
                  <Grid item xs={12} md={6}>
                    <Typography variant="subtitle1" >Tanggal Mulai Kontrak*</Typography>
                  </Grid>
                  <Grid container item xs={12} md={6}>
                    <Typography variant="subtitle1">Tanggal Akhir Kontrak*</Typography>
                  </Grid>
              </Stack>
              <Stack direction="row" spacing={4} sx={{marginTop: '24px'}}>
                <Grid item xs={12} md={6}>
                  <RHFDatepicker name="contract_start" label="Start Date" />
                </Grid>
                <Grid item xs={12} md={6}>
                  <RHFDatepicker name="contract_start" label="End Date" />
                </Grid>
              </Stack>

              <Grid item xs={12} md={12} sx={{marginTop: '24px'}}>
                <Typography variant="subtitle2">Tipe Pembayaran</Typography>
                <RadioGroup 
                  aria-labelledby="demo-radio-buttons-group-label"
                  defaultValue="female"
                  name="type_payment"
                >
                  <FormControlLabel value="1" control={<Radio />} label="Deposit" />
                  <FormControlLabel value="2" control={<Radio />} label="Hutang" />
                  <FormControlLabel value="3" control={<Radio />} label="Penagihan Hutang" />
                </RadioGroup>
              </Grid>

              <Stack direction="row" spacing={2}>
                <Grid container item xs={12} md={12} justifyContent="flex-end">
                  <Button
                    size='small'
                    variant="contained"
                    startIcon={<AddIcon sx={{ color: 'black', fontWeight: 'bold' }} />}
                    sx={{ p: 1.8, typography: 'subtitle2', backgroundColor: '#FFFFFF', marginRight: '20px' }}
                  >
                    <Typography variant="subtitle2" color="black">Cancel</Typography>
                  </Button>
                  <LoadingButton
                    type="submit"
                    variant="contained"
                    size="small"
                    loading={isSubmitting}
                  >
                    <Typography variant="subtitle2" color="black">Save</Typography>
                  </LoadingButton>
                </Grid>
              </Stack>
            </Card>
        </Grid> */}

        <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(`/corporates`)}
            >
              Cancel
            </Button>
            <LoadingButton
              type="submit"
              variant="contained"
              size="large"
              // fullWidth={true}
              loading={isSubmitting}
            >
              Save
            </LoadingButton>
        </Stack>
        </Grid>
      </Grid>
    </FormProvider>
  );
}
