/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, findCurrency, formatError, formatPrice, usePaymentContext, Collapse } from '@blocklet/payment-react';
import { AddOutlined } from '@mui/icons-material';
import { Box, Button, Divider } from '@mui/material';
import { cloneDeep } from 'lodash';
import { Fragment, useState, useEffect } from 'react';
import { FormProvider, useFieldArray, useForm } from 'react-hook-form';
import { dispatch } from 'use-bus';

import DrawerForm from '../../../../components/drawer-form';
import PriceActions from '../../../../components/price/actions';
import PriceForm, { DEFAULT_PRICE } from '../../../../components/price/form';
import ProductForm, { Product } from '../../../../components/product/form';
import { ProductsProvider } from '../../../../contexts/products';

type InitialPrice = {
  currency_id?: string;
  priceModel?: string;
  name?: string;
  metadata?: Record<string, any>;
};
type Props = {
  open?: boolean;
  onClose?: () => void;
  onSubmit?: () => void;
  mode?: 'standard' | 'credit';
  meterId?: string;
  initialPrice?: InitialPrice;
};

export default function ProductsCreate({
  open = true,
  onClose = () => {},
  mode = 'standard',
  meterId = '',
  onSubmit: onSubmitCallback = () => {},
  initialPrice = {} as InitialPrice,
}: Props) {
  const { t, locale } = useLocaleContext();
  const { settings } = usePaymentContext();

  // 管理收折状态，Credit 模式下默认展开定价部分
  const [expandedSection, setExpandedSection] = useState<'product' | 'pricing'>(
    mode === 'credit' ? 'pricing' : 'product'
  );

  // Credit 模式下的默认价格配置
  const getCreditDefaultPrice = () => ({
    ...DEFAULT_PRICE,
    currency_id: settings.baseCurrency.id,
    type: 'one_time' as const,
    nickname: t('admin.creditProduct.defaultNickname'),
    metadata: {
      ...(initialPrice?.metadata || {}),
      ...(meterId ? { meter_id: meterId } : ({} as any)),
      credit_config: {
        priority: 50,
        valid_duration_value: 0,
        valid_duration_unit: 'days',
        ...(initialPrice?.metadata?.credit_config || {}),
      },
    },
  });

  const methods = useForm<Product>({
    mode: 'onChange',
    defaultValues: {
      type: mode === 'credit' ? 'credit' : 'service',
      name:
        mode === 'credit'
          ? t('admin.creditProduct.defaultName', {
              name: initialPrice?.name || 'Credit',
            })
          : '',
      description: mode === 'credit' ? t('admin.creditProduct.defaultDescription') : '',
      images: [],
      statement_descriptor: '',
      unit_label: '',
      features: [],
      prices: [
        mode === 'credit'
          ? getCreditDefaultPrice()
          : {
              ...DEFAULT_PRICE,
              recurring: {
                ...DEFAULT_PRICE.recurring,
                meter_id: meterId,
                usage_type:
                  initialPrice?.priceModel === 'credit_metered' ? 'metered' : DEFAULT_PRICE.recurring?.usage_type,
              },
              unit_amount: '1',
              model: initialPrice?.priceModel || 'standard',
              currency_id: initialPrice?.currency_id || settings.baseCurrency.id,
            },
      ],
    },
  });
  const {
    control,
    handleSubmit,
    getValues,
    clearErrors,
    formState: { errors },
  } = methods;

  const prices = useFieldArray({ control, name: 'prices' });
  const getPrice = (index: number) => methods.getValues().prices[index];

  useEffect(() => {
    if (Object.keys(errors).length > 0) {
      const hasProductErrors =
        errors.name ||
        errors.description ||
        errors.images ||
        errors.statement_descriptor ||
        errors.unit_label ||
        errors.features ||
        errors.metadata;

      const hasPriceErrors = errors.prices;

      if (hasProductErrors) {
        setExpandedSection('product');
      } else if (hasPriceErrors) {
        setExpandedSection('pricing');
      }
    }
  }, [errors]);

  const onSubmit = (data: Product) => {
    if (mode === 'credit') {
      data.type = 'credit';
      data.prices.forEach((price: any) => {
        if (meterId) {
          price.metadata = price.metadata || {};
          const meterIdExists = price.metadata.meter_id;
          if (!meterIdExists) {
            price.metadata.meter_id = meterId;
          }
        }
      });
    } else {
      data.prices.forEach((price: any) => {
        if (price.billing_type === 'metered') {
          price.type = 'recurring';
          if (price.recurring) {
            price.recurring.usage_type = 'metered';
          }
        }
      });
    }

    api
      .post('/api/products', data)
      .then(() => {
        Toast.success(t('admin.product.saved'));
        methods.reset();
        dispatch('drawer.submitted');
        dispatch('product.created');
        if (onSubmitCallback) {
          onSubmitCallback();
        }
        if (onClose) {
          onClose();
        }
      })
      .catch((err: any) => {
        console.error(err);
        Toast.error(formatError(err));
      });
  };

  const onSubmitError = (formErrors: any) => {
    // 表单验证失败时，错误会通过 useEffect 自动处理展开逻辑
    // eslint-disable-next-line no-console
    console.log('Form validation errors:', formErrors);
  };

  const handleClose = () => {
    clearErrors();
    if (onClose) {
      onClose();
    }
  };

  const getDrawerTitle = () => {
    if (mode === 'credit') {
      return t('admin.creditProduct.create');
    }
    return t('admin.product.add');
  };

  return (
    <DrawerForm
      icon={<AddOutlined />}
      text={getDrawerTitle()}
      open={open}
      onClose={handleClose}
      width={640}
      addons={
        <Button variant="contained" size="small" onClick={handleSubmit(onSubmit, onSubmitError)}>
          {t('admin.product.save')}
        </Button>
      }>
      <FormProvider {...methods}>
        <ProductsProvider>
          <Collapse
            expanded={expandedSection === 'product'}
            value="product"
            card
            onChange={(_, expanded) => {
              if (expanded) {
                setExpandedSection('product');
              }
            }}
            style={{ mb: 2 }}
            trigger={t('admin.product.info')}>
            <Box sx={{ p: 1, pl: 2 }}>
              <ProductForm />
            </Box>
          </Collapse>

          <Collapse
            expanded={expandedSection === 'pricing'}
            value="pricing"
            onChange={(_, expanded) => {
              if (expanded) {
                setExpandedSection('pricing');
              }
            }}
            card
            trigger={
              expandedSection === 'pricing'
                ? t('admin.price.plan')
                : `${t('admin.price.plan')} (${prices.fields.length} 个价格)`
            }>
            <Box sx={{ p: 1, pl: 2 }}>
              {prices.fields.map((price, index) => (
                <Fragment key={price.id}>
                  <Collapse
                    expanded
                    style={{ fontWeight: 'bold', width: '100%' }}
                    addons={
                      <PriceActions onDuplicate={() => prices.append(price)} onRemove={() => prices.remove(index)} />
                    }
                    trigger={(expanded: boolean) => {
                      if (expanded) {
                        return t('admin.price.order', {
                          order: index + 1,
                        });
                      }
                      const priceItem = getPrice(index);
                      const currency =
                        findCurrency(settings.paymentMethods, priceItem?.currency_id || '') || settings.baseCurrency;

                      // @ts-ignore
                      return formatPrice(priceItem as any, currency, getValues().unit_label, 1, false, locale);
                    }}>
                    <Box sx={{ width: '100%', p: 1 }}>
                      <PriceForm prefix={`prices.${index}`} meterId={meterId} />
                    </Box>
                  </Collapse>
                  <Divider sx={{ mt: 2, mb: 2 }} />
                </Fragment>
              ))}
              <Button
                variant="outlined"
                color="primary"
                sx={{
                  color: 'text.primary',
                  width: '100%',
                }}
                onClick={() => {
                  const newPrice =
                    mode === 'credit'
                      ? getCreditDefaultPrice()
                      : ({ ...cloneDeep(DEFAULT_PRICE), currency_id: settings.baseCurrency.id } as any);
                  prices.append(newPrice);
                }}>
                <AddOutlined fontSize="small" /> {t('admin.price.addAnother')}
              </Button>
            </Box>
          </Collapse>
        </ProductsProvider>
      </FormProvider>
    </DrawerForm>
  );
}
