import * as Yup from 'yup';
import { useMemo } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
// @mui
import LoadingButton from '@mui/lab/LoadingButton';
import Box from '@mui/material/Box';
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import MenuItem from '@mui/material/MenuItem';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
// types
import { Customer, updateCustomerSchema } from 'src/schemas';
// assets
import { countries } from 'src/assets/data';
// components
import Iconify from 'src/components/iconify';
import { useSnackbar } from 'src/components/snackbar';
import FormProvider, { RHFSelect, RHFTextField, RHFAutocomplete } from 'src/components/hook-form';
import { updateCustomer } from 'src/api/customer';

// ----------------------------------------------------------------------

export const USER_STATUS_OPTIONS = [
  { value: 'active', label: 'Active' },
  { value: 'banned', label: 'Banned' },
  { value: 'inactive', label: 'Inactive' },
];

type Props = {
  open: boolean;
  onClose: VoidFunction;
  currentCustomer?: Customer;
};

export default function CustomerQuickEditForm({ currentCustomer, open, onClose }: Props) {
  const { enqueueSnackbar } = useSnackbar();

  // @ts-ignore
  const defaultValues: Customer = useMemo(
    () => ({
      name: currentCustomer?.name || '',
      representative: currentCustomer?.representative || '',
      email: currentCustomer?.email || '',
      logoUrl: currentCustomer?.logoUrl || '',
      address: {
        country: currentCustomer?.address?.country || '',
        state: currentCustomer?.address?.state || '',
        street: currentCustomer?.address?.street || '',
        zip: currentCustomer?.address?.zip || '',
        city: currentCustomer?.address?.city || '',
      },
      vatNumber: currentCustomer?.vatNumber || '',
      companyNumber: currentCustomer?.companyNumber || '',
      id: currentCustomer?.id || '',
      phoneNumber: currentCustomer?.phoneNumber || '',
      status: currentCustomer?.status || '',
    }),
    [currentCustomer]
  );

  const methods = useForm({
    resolver: zodResolver(updateCustomerSchema),
    defaultValues,
  });

  const {
    reset,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const onSubmit = handleSubmit(async (data) => {
    try {
      console.log('currentCustomer', currentCustomer);
      if (!currentCustomer) return;
      console.log('data', data);
      await updateCustomer(currentCustomer.id!, data);

      reset();
      onClose();
      enqueueSnackbar('Update success!');
      console.info('DATA', data);
    } catch (error) {
      console.error(error);
      enqueueSnackbar('Update failed!', { variant: 'error' });
    }
  });

  return (
    <Dialog
      fullWidth
      maxWidth={false}
      open={open}
      onClose={onClose}
      PaperProps={{
        sx: { maxWidth: 720 },
      }}
    >
      <FormProvider methods={methods} onSubmit={onSubmit}>
        <DialogTitle>Quick Update</DialogTitle>

        <DialogContent>
          {/* <Alert variant="outlined" severity="info" sx={{ mb: 3 }}>
            Account is waiting for confirmation
          </Alert> */}

          <Box
            rowGap={3}
            columnGap={2}
            display="grid"
            sx={{ mt: 3 }}
            gridTemplateColumns={{
              xs: 'repeat(1, 1fr)',
              sm: 'repeat(2, 1fr)',
            }}
          >
            <RHFSelect name="status" label="Status">
              <MenuItem key="none" value="" />
              {USER_STATUS_OPTIONS.map((status) => (
                <MenuItem key={status.value} value={status.value}>
                  {status.label}
                </MenuItem>
              ))}
            </RHFSelect>

            <Box sx={{ display: { xs: 'none', sm: 'block' } }} />

            <RHFTextField name="name" label="Name" />
            <RHFTextField name="representative" label="Representative" />
            <RHFTextField name="email" label="Email Address" />
            <RHFTextField name="phoneNumber" label="Phone Number" />

            <RHFTextField name="address.country" label="Country" />

            {/* <RHFAutocomplete
              name="address.country"
              label="Country"
              options={countries.map((country) => country.code)}
              getOptionLabel={(option) => option}
              renderOption={(props, option) => {
                const { code, label, phone } = countries.filter(
                  (country) => country.label === option
                )[0];

                if (!label) {
                  return null;
                }

                return (
                  <li {...props} key={label}>
                    <Iconify
                      key={label}
                      icon={`circle-flags:${code.toLowerCase()}`}
                      width={28}
                      sx={{ mr: 1 }}
                    />
                    {label} ({code}) +{phone}
                  </li>
                );
              }}
            /> */}

            <RHFTextField name="address.state" label="State/Region" />
            <RHFTextField name="address.city" label="City" />
            <RHFTextField name="address.street" label="Street" />
            <RHFTextField name="address.zip" label="Zip/Code" />
            <RHFTextField name="vatNumber" label="VAT" />
            <RHFTextField name="companyNumber" label="Company Number" />
          </Box>
        </DialogContent>

        <DialogActions>
          <Button variant="outlined" onClick={onClose}>
            Cancel
          </Button>

          <LoadingButton type="submit" variant="contained" loading={isSubmitting}>
            Update
          </LoadingButton>
        </DialogActions>
      </FormProvider>
    </Dialog>
  );
}
