import * as Yup from 'yup';
import { useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';
import { useContext, 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 { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
// 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({currentCorporate }: Props) {
  const navigate = useNavigate();
  const [corporate_groups, setCorporateGroups] = useState([]);
  const { corporateValue } = useContext(UserCurrentCorporateContext);
  // const [ errors, setErrors ] = useState<{ [key: string]: string }>({});

  const { enqueueSnackbar } = useSnackbar();
  let NewCorporateSchema = Yup.object().shape({
      welcome_message: Yup.string().required('Welcome Message is required'),
      // reason: Yup.string().required('Reason for update is required when editing data'),
    });

  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(() => {
    axios
      .get(`/${corporateValue}/corporate`)
      .then((res) => {
        // console.log(res.data.data[0], 'tussr')
        const data = res.data.data[0];
        setCorporateGroups(res.data.data[0]);
          reset({
            code: data?.code || '',
            name: data?.name || '',
            reason: data?.reason || '',
            payor_id: data?.payor_id || '',
            welcome_message: data?.welcome_message || '',
            help_text: data?.help_text || '',
            active: data?.id ? data?.active === 1 : true,
            automatic_linking: data?.id ? data?.automatic_linking === 1 : true,
            policy_id: data?.current_policy?.id || '',
            policy_code: data?.current_policy?.code || '',
            policy_total_premi: data?.current_policy?.total_premi || 0,
            policy_minimal_deposit_percentage:
              data?.current_policy?.minimal_deposit_percentage || 50,
            policy_minimal_deposit_net: data?.current_policy?.minimal_deposit_net || 0,
            policy_minimal_alert_percentage:
              data?.current_policy?.minimal_alert_percentage || 25,
            policy_minimal_alert_net: data?.current_policy?.minimal_alert_net || 0,
            policy_stop_service_percentage:
              data?.current_policy?.minimal_stop_service_percentage || 25,
            policy_stop_service_net: data?.current_policy?.minimal_stop_service_net || 0,
            policy_start: data?.current_policy?.start || '',
            policy_end: data?.current_policy?.end || '',
            linking_rules: data?.linking_rules || ['nric', 'nik', 'member_id'],
            type: data?.type || 'corporate',
            logo: data?.logo || '',
          });
      })
      .catch((err) => {
        enqueueSnackbar('Opps, failed to get Corporate Group List', { variant: 'error' });
      });

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [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('automatic_linking', data.automatic_linking ? 1 : 0);
      formData.append('welcome_message', data.welcome_message);
      formData.append('reason', data.reason);
      formData.append('help_text', data.help_text);
      formData.append('linking_rules', data.linking_rules);

      // console.log('MOTHERFUCKER', data.linking_rules)
      formData.append('_method', 'PUT');
      const response = await axios.post(`/${corporateValue}/corporate-update`, formData);
      
      reset();
      enqueueSnackbar(
         'Corporate Updated Successfully!',
        { variant: 'success' }
      );
      navigate('/corporate');
    } 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(true);
  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="#19BBBB">Corporate Profile</Typography>
              </Grid>

              <Typography variant='subtitle1' color="#637381">Corporate Profile*</Typography>
              <RHFSelect name="type" label="Type" placeholder="Type" disabled>
                <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} />

              {/* <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="Worng Setting">Worng 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>
                  <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" disabled />
                  </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>

          <Grid item xs={12} md={11}>
            <Stack direction="row" spacing={2} justifyContent="flex-end">
              <Typography>
                <Button
                  variant="outlined"
                  size="small"
                  color="inherit"
                  onClick={() => navigate(`/corporate`)}
                >
                  {'Cancel'}
                </Button>
              </Typography>
              <Typography>
                <LoadingButton
                  type="submit"
                  variant="contained"
                  size="small"
                
                  loading={isSubmitting}
                >
                  {'Save'}
                </LoadingButton>
              </Typography>
            </Stack>
          </Grid>
      </Grid>
    </FormProvider>
  );
}
