import * as Yup from 'yup';
import { useCallback, useMemo } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
// @mui
import LoadingButton from '@mui/lab/LoadingButton';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Switch from '@mui/material/Switch';
import Grid from '@mui/material/Unstable_Grid2';
import Typography from '@mui/material/Typography';
import FormControlLabel from '@mui/material/FormControlLabel';
// utils
import { fData } from 'src/utils/format-number';
// routes
import { paths } from 'src/routes/paths';
import { useRouter } from 'src/routes/hooks';
// types
import { Customer, NewCustomer, newCustomerSchema } from 'src/schemas';
// components
import Label from 'src/components/label';
import { useSnackbar } from 'src/components/snackbar';
import FormProvider, { RHFTextField, RHFUploadAvatar } from 'src/components/hook-form';
import uploadToFirebaseStorage from 'src/utils/upload-to-firebase-storage';
import { addDoc, collection } from 'firebase/firestore';
import { db } from 'src/lib/firebase';
import { createCustomer } from 'src/api/customer';

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

type Props = {
  currentUser?: Customer;
};

export default function CustomerNewEditForm({ currentUser: currentCustomer }: Props) {
  const router = useRouter();

  const { enqueueSnackbar } = useSnackbar();

  const defaultValues: NewCustomer = useMemo(
    () => ({
      name: currentCustomer?.name || '',
      representative: currentCustomer?.representative || '',
      email: currentCustomer?.email || '',
      logoUrl: currentCustomer?.logoUrl || null,
      address: currentCustomer?.address || {
        country: '',
        state: '',
        street: '',
        zip: '',
        city: '',
      },
      vatNumber: currentCustomer?.vatNumber || '',
      companyNumber: currentCustomer?.companyNumber || '',
      id: currentCustomer?.id || '',
      phoneNumber: currentCustomer?.phoneNumber || '',
      status: 'active',
    }),
    [currentCustomer]
  );

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

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

  const values = watch();

  const onSubmit = handleSubmit(async (data) => {
    try {
      // await new Promise((resolve) => setTimeout(resolve, 500));
      const logoFile = data.logoUrl as File & { preview: string };

      const storagePath: string = `customers/${logoFile.name}`;
      const logoUrl = await uploadToFirebaseStorage(logoFile, storagePath);

      await createCustomer({ ...data, logoUrl });

      reset();
      enqueueSnackbar(currentCustomer ? 'Update success!' : 'Create success!');
      router.push(paths.dashboard.customer.list);
      console.info('DATA', data);
    } catch (error) {
      console.error(error);
    }
  });

  const handleDrop = useCallback(
    (acceptedFiles: File[]) => {
      const file = acceptedFiles[0];

      const newFile = Object.assign(file, {
        preview: URL.createObjectURL(file),
      });

      if (file) {
        setValue('logoUrl', newFile, { shouldValidate: true });
      }
    },
    [setValue]
  );

  return (
    <FormProvider methods={methods} onSubmit={onSubmit}>
      <Grid container spacing={3}>
        <Grid xs={12} md={4}>
          <Card sx={{ pt: 10, pb: 5, px: 3 }}>
            {currentCustomer && (
              <Label
                color={
                  (values.status === 'active' && 'success') ||
                  (values.status === 'banned' && 'error') ||
                  'warning'
                }
                sx={{ position: 'absolute', top: 24, right: 24 }}
              >
                {values.status}
              </Label>
            )}

            <Box sx={{ mb: 5 }}>
              <RHFUploadAvatar
                name="logoUrl"
                maxSize={3145728}
                onDrop={handleDrop}
                helperText={
                  <Typography
                    variant="caption"
                    sx={{
                      mt: 3,
                      mx: 'auto',
                      display: 'block',
                      textAlign: 'center',
                      color: 'text.disabled',
                    }}
                  >
                    Allowed *.jpeg, *.jpg, *.png, *.gif
                    <br /> max size of {fData(3145728)}
                  </Typography>
                }
              />
            </Box>

            {currentCustomer && (
              <FormControlLabel
                labelPlacement="start"
                control={
                  <Controller
                    name="status"
                    control={control}
                    render={({ field }) => (
                      <Switch
                        {...field}
                        checked={field.value !== 'active'}
                        onChange={(event) =>
                          field.onChange(event.target.checked ? 'banned' : 'active')
                        }
                      />
                    )}
                  />
                }
                label={
                  <>
                    <Typography variant="subtitle2" sx={{ mb: 0.5 }}>
                      Banned
                    </Typography>
                    <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                      Apply disable account
                    </Typography>
                  </>
                }
                sx={{ mx: 0, mb: 3, width: 1, justifyContent: 'space-between' }}
              />
            )}
          </Card>
        </Grid>

        <Grid xs={12} md={8}>
          <Card sx={{ p: 3 }}>
            <Box
              rowGap={3}
              columnGap={2}
              display="grid"
              gridTemplateColumns={{
                xs: 'repeat(1, 1fr)',
                sm: 'repeat(2, 1fr)',
              }}
            >
              <RHFTextField name="name" label="Name" />
              <RHFTextField name="email" label="Email Address" />
              <RHFTextField name="representative" label="Representative" />
              <RHFTextField name="phoneNumber" label="Phone Number" />

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

              {/* <RHFAutocomplete
                name="address.country"
                label="Country"
                options={countries.map((country) => country.label)}
                getOptionLabel={(option) => option}
                isOptionEqualToValue={(option, value) => option === value}
                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>

            <Stack alignItems="flex-end" sx={{ mt: 3 }}>
              <LoadingButton type="submit" variant="contained" loading={isSubmitting}>
                {!currentCustomer ? 'Create Customer' : 'Save Changes'}
              </LoadingButton>
            </Stack>
          </Card>
        </Grid>
      </Grid>
    </FormProvider>
  );
}
