import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { FormInput, findCurrency, formatPrice, usePaymentContext } from '@blocklet/payment-react';
import type { TPrice } from '@blocklet/payment-types';
import { DeleteOutlineOutlined } from '@mui/icons-material';
import { Box, Checkbox, FormControlLabel, IconButton, InputAdornment, Stack, Typography } from '@mui/material';
import { get } from 'lodash';
import { Controller, useFormContext, useWatch } from 'react-hook-form';

type Props = {
  prefix: string;
  price: TPrice;
  onRemove: () => void;
};

export default function PriceItem({ prefix, price, onRemove }: Props) {
  const { t } = useLocaleContext();
  const getFieldName = (name: string) => (prefix ? `${prefix}.${name}` : name);
  const { settings } = usePaymentContext();
  const {
    control,
    setValue,
    formState: { errors },
  } = useFormContext();
  const includeFreeTrial = useWatch({ control, name: getFieldName('include_free_trial') });

  const currency = findCurrency(settings.paymentMethods, price?.currency_id ?? '') || settings.baseCurrency;
  return (
    <Box sx={{ width: '100%' }}>
      <Stack
        direction="row"
        sx={{
          alignItems: 'center',
          justifyContent: 'space-between',
        }}>
        <Typography>{formatPrice(price, currency!)}</Typography>
        <IconButton size="small" onClick={onRemove}>
          <DeleteOutlineOutlined color="inherit" sx={{ opacity: 0.75 }} />
        </IconButton>
      </Stack>
      <Controller
        name={getFieldName('include_free_trial')}
        control={control}
        render={({ field }) => (
          <FormControlLabel
            label={t('admin.paymentLink.includeFreeTrial')}
            control={
              <Checkbox
                sx={{ ml: 1 }}
                {...field}
                onChange={(_, checked) => {
                  setValue(field.name, checked);
                }}
              />
            }
          />
        )}
      />
      {includeFreeTrial && (
        <FormInput
          name={getFieldName('subscription_data.trial_period_days')}
          rules={{
            required: t('payment.checkout.required'),
            validate: (val) => {
              if (val <= 0) {
                return t('admin.paymentLink.freeTrialDaysPositive');
              }
              return true;
            },
          }}
          helperText={get(errors, getFieldName('subscription_data.trial_period_days'))?.message as string}
          error={!!get(errors, getFieldName('subscription_data.trial_period_days'))}
          sx={{ mt: 0.5 }}
          fullWidth={false}
          InputProps={{
            endAdornment: <InputAdornment position="end">{t('common.days')}</InputAdornment>,
          }}
        />
      )}
    </Box>
  );
}
