import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Tabs from '@arcblock/ux/lib/Tabs';
import { findCurrency, formatPrice, usePaymentContext } from '@blocklet/payment-react';
import type { TPrice, TProduct } from '@blocklet/payment-types';
import { Box, Checkbox, FormControlLabel, Stack, TextField, Typography } from '@mui/material';
import get from 'lodash/get';
import { useState } from 'react';
import { Controller, useFieldArray, useFormContext, useWatch } from 'react-hook-form';

import { useProductsContext } from '../../contexts/products';
import { getPriceFromProducts, groupPricingTableItems } from '../../libs/util';
import IconCollapse from '../collapse';

export function PricePaymentSettings({ index }: { index: number }) {
  const getFieldName = (name: string) => `items.${index}.${name}`;

  const { t } = useLocaleContext();
  const {
    control,
    setValue,
    getValues,
    formState: { errors },
  } = useFormContext();
  const type = useWatch({ control, name: getFieldName('after_completion.type') });
  const nftMintEnabled = useWatch({ control, name: getFieldName('nft_mint_settings.enabled') });

  const values = getValues();

  return (
    <Stack
      spacing={2}
      sx={{
        mb: 2,
      }}>
      <Controller
        name={getFieldName('billing_address_collection')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={get(values, getFieldName('billing_address_collection')) === 'required'}
                {...field}
                onChange={(_, checked) => setValue(field.name, checked ? 'required' : 'auto')}
              />
            }
            label={t('admin.paymentLink.requireBillingAddress')}
          />
        )}
      />
      <Controller
        name={getFieldName('phone_number_collection.enabled')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={get(values, getFieldName('phone_number_collection.enabled'))}
                {...field}
                onChange={(_, checked) => setValue(field.name, checked)}
              />
            }
            label={t('admin.paymentLink.requirePhoneNumber')}
          />
        )}
      />
      <Controller
        name={getFieldName('allow_promotion_codes')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={get(values, getFieldName('allow_promotion_codes'))}
                {...field}
                onChange={(_, checked) => setValue(field.name, checked)}
              />
            }
            label={t('admin.paymentLink.allowPromotionCodes')}
          />
        )}
      />
      <Controller
        name={getFieldName('cross_sell_behavior')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={get(values, getFieldName('cross_sell_behavior')) === 'required'}
                {...field}
                onChange={(_, checked) => setValue(field.name, checked ? 'required' : 'auto')}
              />
            }
            label={t('admin.paymentLink.requireCrossSell')}
          />
        )}
      />
      <Controller
        name={getFieldName('after_completion.type')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={get(values, getFieldName('after_completion.type')) === 'hosted_confirmation'}
                {...field}
                onChange={(_, checked) => setValue(field.name, checked ? 'hosted_confirmation' : 'redirect')}
              />
            }
            label={t('admin.paymentLink.showConfirmPage')}
          />
        )}
      />
      {type === 'hosted_confirmation' && (
        <Controller
          name={getFieldName('after_completion.hosted_confirmation.custom_message')}
          control={control}
          rules={{
            maxLength: {
              value: 200,
              message: t('common.maxLength', { len: 200 }),
            },
          }}
          render={({ field }) => (
            <TextField
              {...field}
              placeholder={t('admin.paymentLink.customMessage')}
              fullWidth
              size="small"
              error={!!get(errors, field.name)}
              helperText={(get(errors, field.name)?.message as string) || t('admin.paymentLink.customMessageTip')}
              slotProps={{
                htmlInput: {
                  maxLength: 200,
                },
              }}
            />
          )}
        />
      )}
      <Controller
        name={getFieldName('after_completion.type')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={get(values, getFieldName('after_completion.type')) === 'redirect'}
                {...field}
                onChange={(_, checked) => setValue(field.name, checked ? 'redirect' : 'hosted_confirmation')}
              />
            }
            label={t('admin.paymentLink.noConfirmPage')}
          />
        )}
      />
      {type === 'redirect' && (
        <Controller
          name={getFieldName('after_completion.redirect.url')}
          control={control}
          rules={{
            maxLength: {
              value: 2048,
              message: t('common.maxLength', { len: 2048 }),
            },
          }}
          render={({ field }) => (
            <TextField
              placeholder="Redirect customers to your site"
              {...field}
              fullWidth
              size="small"
              error={!!get(errors, field.name)}
              helperText={get(errors, field.name)?.message as string}
            />
          )}
        />
      )}
      <Controller
        name={getFieldName('nft_mint_settings.enabled')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            control={
              <Checkbox
                checked={get(values, 'nft_mint_settings.enabled')}
                {...field}
                onChange={(_, checked) => setValue(field.name, checked)}
              />
            }
            label={t('admin.paymentLink.mintNft')}
          />
        )}
      />
      {nftMintEnabled && (
        <Controller
          name={getFieldName('nft_mint_settings.factory')}
          control={control}
          rules={{
            maxLength: {
              value: 40,
              message: t('common.maxLength', { len: 40 }),
            },
          }}
          render={({ field }) => (
            <TextField
              {...field}
              placeholder={t('admin.paymentLink.mintNftFrom')}
              fullWidth
              size="small"
              error={!!get(errors, field.name)}
              helperText={get(errors, field.name)?.message as string}
            />
          )}
        />
      )}
    </Stack>
  );
}

export function ProductPaymentSettings({ product, prices }: { product: TProduct; prices: TPrice[] }) {
  const { settings } = usePaymentContext();
  const { products } = useProductsContext();
  const [current, setCurrent] = useState(prices[0]?.id);
  const tabs = prices.map((x: any) => {
    const currency = findCurrency(settings.paymentMethods, x.currency_id);
    return {
      value: x.id,
      label: formatPrice(getPriceFromProducts(products, x.price_id) as TPrice, currency || settings.baseCurrency),
      component: <PricePaymentSettings index={x.index} />,
    };
  });

  return (
    <Box sx={{ px: 2, py: 0, border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
      <IconCollapse
        key={product.id}
        expanded
        trigger={<Typography variant="h6">{product.name}</Typography>}
        style={{ py: 1 }}>
        {/* @ts-ignore */}
        <Tabs
          // @ts-ignore
          tabs={tabs}
          // @ts-ignore
          current={current}
          // @ts-ignore
          onChange={(v: string) => setCurrent(v)}
          style={{ width: '100%' }}
          scrollButtons="auto"
        />
        {tabs.find((x) => x.value === current)?.component}
      </IconCollapse>
    </Box>
  );
}

export default function PricingTablePaymentSettings() {
  const { t } = useLocaleContext();
  const { products } = useProductsContext();
  const { control } = useFormContext();
  const items = useFieldArray({ control, name: 'items' });

  const grouped = groupPricingTableItems(items.fields);

  return (
    <Stack
      spacing={2}
      sx={{
        alignItems: 'flex-start',
      }}>
      <Typography variant="h6" sx={{ mb: 2, fontWeight: 600 }}>
        {t('admin.paymentLink.products')}
      </Typography>
      <Stack spacing={2} sx={{ width: '100%' }}>
        {grouped.map((item) => {
          const [productId, prices] = item;
          const product = products.find((x) => x.id === productId);
          return product ? <ProductPaymentSettings key={productId} product={product} prices={prices} /> : null;
        })}
      </Stack>
    </Stack>
  );
}
