/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError, usePaymentContext } from '@blocklet/payment-react';
import type { TPricingTable } from '@blocklet/payment-types';
import { AddOutlined, Fullscreen, FullscreenExit } from '@mui/icons-material';
import { Box, Button, Stack, Typography } from '@mui/material';
import { useEffect, useRef, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useSearchParams } from 'react-router-dom';
import { dispatch } from 'use-bus';

import { useSetState } from 'ahooks';
import DrawerForm from '../../../../components/drawer-form';
// import PricingTableCustomerSettings from '../../../../components/pricing-table/customer-settings';
import PricingTablePaymentSettings from '../../../../components/pricing-table/payment-settings';
import PricingTablePreview from '../../../../components/pricing-table/preview';
import PricingTableProductSettings from '../../../../components/pricing-table/product-settings';
import { ProductsProvider } from '../../../../contexts/products';
import { useSessionContext } from '../../../../contexts/session';

export default function CreatePricingTable() {
  const { t } = useLocaleContext();
  const [params] = useSearchParams();
  const { session } = useSessionContext();
  const [step, setStep] = useState(0); // ['products', 'payment', 'portal']
  const [stashed, setStashed] = useState(0);
  const fullScreenRef = useRef(null);
  const [errors, triggerError] = useSetState({});
  const { settings } = usePaymentContext();

  const methods = useForm<TPricingTable & any>({
    shouldUnregister: false,
    defaultValues: {
      name: '',
      branding_settings: {
        background_color: '#ffffff',
        border_style: 'default',
        button_color: '#0074d4',
        font_family: 'default',
      },
      highlight: false,
      highlight_product_id: '',
      highlight_text: 'popular',
      items: [],
      metadata: [],
      currency_id: settings.baseCurrency.id,
    },
  });

  const changes = methods.watch([
    'items',
    'branding_settings',
    'highlight',
    'highlight_product_id',
    'highlight_text',
    'currency_id',
  ]);

  useEffect(() => {
    api.post('/api/pricing-tables/stash', methods.getValues()).then(() => {
      setStashed(stashed + 1);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(changes)]);

  const onSubmit = (data: TPricingTable) => {
    if (data.items.length === 0) {
      Toast.error(t('admin.paymentLink.noProducts'));
      return;
    }
    if (Object.values(errors).some((v) => v)) {
      return;
    }

    api
      .post('/api/pricing-tables', data)
      .then(() => {
        Toast.success(t('admin.pricingTable.saved'));
        methods.reset();
        setStep(0);
        dispatch('drawer.submitted');
        dispatch('pricingTable.created');
      })
      .catch((err: any) => {
        console.error(err);
        Toast.error(formatError(err));
      });
  };

  const onPrevious = () => {
    if (step > 0) {
      setStep(step - 1);
    }
  };

  const onContinue = () => {
    if (Object.values(errors).some((v) => v)) {
      return;
    }
    if (step < 1) {
      setStep(step + 1);
    } else {
      methods.handleSubmit(async (formData: any) => {
        await onSubmit(formData);
      })();
    }
  };

  return (
    <DrawerForm
      icon={<AddOutlined />}
      text={t('admin.pricingTable.add')}
      open={!!params.get('price_id')}
      width={1280}
      addons={
        // @ts-ignore
        <Button variant="contained" size="small" onClick={methods.handleSubmit(onSubmit)}>
          {t('admin.pricingTable.save')}
        </Button>
      }>
      <FormProvider {...methods}>
        <ProductsProvider>
          <Stack
            spacing={2}
            direction="row"
            sx={{
              height: '92vh',
            }}>
            <Box
              sx={{
                flex: 2,
                position: 'relative',
                borderRight: '1px solid',
                borderColor: 'divider',
              }}>
              <Stack
                spacing={2}
                sx={{
                  height: '100%',
                }}>
                <Box
                  sx={{
                    overflow: 'auto',
                    pr: 2,
                    pb: 8,
                  }}>
                  {step === 0 && <PricingTableProductSettings triggerError={triggerError} />}
                  {step === 1 && <PricingTablePaymentSettings />}
                  {/* {step === 2 && <PricingTableCustomerSettings />} */}
                </Box>
                <Stack
                  spacing={2}
                  direction="row"
                  sx={{
                    padding: 2,
                    width: '100%',
                    alignItems: 'center',
                    justifyContent: 'flex-end',
                    position: 'absolute',
                    borderTop: '1px solid',
                    borderColor: 'divider',
                    left: 0,
                    bottom: 0,
                  }}>
                  <Button variant="text" color="inherit" disabled={step === 0} onClick={onPrevious}>
                    {t('common.previous')}
                  </Button>
                  <Button variant="contained" color="primary" onClick={onContinue}>
                    {step === 1 ? t('common.save') : t('common.continue')}
                  </Button>
                </Stack>
              </Stack>
            </Box>
            <Box
              sx={{
                flex: 1,
                maxWidth: 680,
              }}>
              <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
                {t('common.preview')}
              </Typography>
              {stashed && (
                <PricingTablePreview id={`prctbl_${session?.user?.did}`} version={stashed} ref={fullScreenRef} />
              )}
              <Box
                sx={{
                  textAlign: 'center',
                  mt: 2.5,
                }}>
                <Button
                  variant="outlined"
                  color="primary"
                  onClick={() => (fullScreenRef?.current as any)?.toggleFullscreen()}>
                  {(fullScreenRef?.current as any)?.fullscreen ? <FullscreenExit /> : <Fullscreen />}
                  {t('common.fullscreen')}
                </Button>
              </Box>
            </Box>
          </Stack>
        </ProductsProvider>
      </FormProvider>
    </DrawerForm>
  );
}
