/* eslint-disable no-nested-ternary */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { FormInput, FormLabel, Collapse } from '@blocklet/payment-react';
import type { InferFormType, TProduct } from '@blocklet/payment-types';
import { Box, Stack, Typography, Select, MenuItem, Link } from '@mui/material';
import { useFormContext, useWatch, Controller } from 'react-hook-form';
import { Link as RouterLink } from 'react-router-dom';

import MetadataForm from '../metadata/form';
import type { Price } from '../price/form';
import Uploader from '../uploader';
import TaxCodeSelect from '../tax/tax-code-select';
import ProductFeatures from './features';
import VendorConfig from './vendor-config';

export type Product = InferFormType<TProduct> & {
  prices: Price[];
  vendor_config: {
    vendor_id: string;
    commission_rate: number;
    commission_type: 'percentage' | 'fixed';
  }[];
};

type Props = {
  simple?: boolean;
};

export default function ProductForm({ simple = false }: Props) {
  const { t } = useLocaleContext();
  const { control, setValue, formState } = useFormContext();
  const images = useWatch({ control, name: 'images' });
  const productType = useWatch({ control, name: 'type' }) ?? '';

  const onUploaded = (result: any) => {
    if (result.url) {
      const tmp = new URL(result.url);
      setValue('images', [tmp.pathname]);
    } else {
      setValue('images', []);
    }
  };

  return (
    <Stack
      spacing={3}
      sx={{
        mb: 3,
      }}>
      <Controller
        name="type"
        control={control}
        rules={{ required: true }}
        render={({ field }) => (
          <Box sx={{ width: '100%' }}>
            <FormLabel sx={{ color: 'text.primary', fontSize: '0.875rem' }}>{t('admin.product.type.label')}</FormLabel>
            <Select
              {...field}
              fullWidth
              size="small"
              renderValue={(value) => {
                const typeMap: Record<string, string> = {
                  good: t('admin.product.type.good'),
                  service: t('admin.product.type.service'),
                  credit: t('admin.product.type.credit'),
                };
                return typeMap[value as string] || value;
              }}>
              <MenuItem value="good">
                <Box>
                  <Typography variant="body2">{t('admin.product.type.good')}</Typography>
                  <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                    {t('admin.product.type.goodDesc')}
                  </Typography>
                </Box>
              </MenuItem>
              <MenuItem value="service">
                <Box>
                  <Typography variant="body2">{t('admin.product.type.service')}</Typography>
                  <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                    {t('admin.product.type.serviceDesc')}
                  </Typography>
                </Box>
              </MenuItem>
              <MenuItem value="credit">
                <Box>
                  <Typography variant="body2">{t('admin.product.type.credit')}</Typography>
                  <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                    {t('admin.product.type.creditDesc')}
                    {' - '}
                    <Link
                      component={RouterLink}
                      to="/admin/billing/meters"
                      target="_blank"
                      rel="noopener noreferrer"
                      sx={{
                        color: 'primary.main',
                        fontWeight: 500,
                        '&:hover': { textDecoration: 'underline' },
                      }}
                      onClick={(e) => e.stopPropagation()}>
                      {t('admin.product.type.creditDescLink')}
                    </Link>
                  </Typography>
                </Box>
              </MenuItem>
            </Select>
          </Box>
        )}
      />
      <Stack
        direction="row"
        sx={{
          alignItems: 'flex-start',
          flex: 1,
          gap: 2,
        }}>
        <Stack sx={{ flex: 1, gap: 2 }}>
          <FormInput
            name="name"
            rules={{
              required: t('admin.product.name.required'),
              maxLength: {
                value: 64,
                message: t('common.maxLength', { len: 64 }),
              },
            }}
            label={t('admin.product.name.label')}
            required
            placeholder={
              productType === 'credit' ? t('admin.creditProduct.name.placeholder') : t('admin.product.name.placeholder')
            }
            error={!!formState.errors.name}
            helperText={formState.errors.name?.message as string}
            autoFocus
            inputProps={{ maxLength: 64 }}
          />

          <FormInput
            name="description"
            rules={{
              required: t('admin.product.description.required'),
              maxLength: {
                value: 250,
                message: t('common.maxLength', { len: 250 }),
              },
            }}
            label={t('admin.product.description.label')}
            placeholder={
              productType === 'credit'
                ? t('admin.creditProduct.description.placeholder')
                : t('admin.product.description.placeholder')
            }
            error={!!formState.errors.description}
            helperText={formState.errors.description?.message as string}
            multiline
            required
            minRows={2}
            maxRows={4}
          />
        </Stack>

        <Box sx={{ width: '100%', maxWidth: 160 }}>
          <Typography variant="body2" sx={{ mb: 1, fontWeight: 500 }}>
            {t('admin.product.image.label')}
          </Typography>
          <Uploader onUploaded={onUploaded} preview={images[0]} />
        </Box>
      </Stack>
      <Stack sx={{ '& .vendor-config': { mt: 2 } }}>
        <Box sx={{ mb: 2 }}>
          <FormLabel
            description={
              <>
                {t('admin.taxRate.taxCodeDescription')}
                <Link
                  component={RouterLink}
                  to="/admin/tax"
                  target="_blank"
                  rel="noopener noreferrer"
                  sx={{
                    textDecoration: 'none',
                    color: 'primary.main',
                    mx: 0.5,
                    fontWeight: 500,
                    '&:hover': { textDecoration: 'underline' },
                  }}>
                  {t('admin.taxRate.taxCodeDescriptionLink')}
                </Link>
                {t('admin.taxRate.taxCodeDescriptionSuffix')}
              </>
            }>
            {t('admin.taxRate.taxCode')}
          </FormLabel>
          <TaxCodeSelect label="" />
        </Box>
        <Collapse trigger={t('admin.product.vendorConfig.title')}>
          <VendorConfig />
        </Collapse>
      </Stack>
      <Collapse trigger={t('admin.product.additional')}>
        <Stack
          spacing={2}
          sx={{
            alignItems: 'flex-start',
          }}>
          <FormInput
            name="statement_descriptor"
            label={t('admin.product.statement_descriptor.label')}
            rules={{
              maxLength: { value: 22, message: t('common.maxLength', { len: 22 }) },
              pattern: {
                value: /^(?=.*[A-Za-z])[^\u4e00-\u9fa5<>"'\\]*$/,
                message: t('common.latinOnly'),
              },
            }}
          />
          <FormInput
            name="unit_label"
            label={t('admin.product.unit_label.label')}
            rules={{
              maxLength: { value: 12, message: t('common.maxLength', { len: 12 }) },
            }}
          />
          {!simple && <ProductFeatures />}
          {!simple && <MetadataForm title={t('common.metadata.label')} color="inherit" />}
        </Stack>
      </Collapse>
    </Stack>
  );
}
