import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Fade, InputAdornment, Stack } from '@mui/material';
import type { SxProps } from '@mui/material';
import { Controller, useFormContext, useWatch } from 'react-hook-form';
import FormInput from '../../components/input';
import FormLabel from '../../components/label';
import CountrySelect from '../../components/country-select';
import { getFieldValidation, validatePostalCode } from '../../libs/validator';

type Props = {
  mode: string;
  sx?: SxProps;
  fieldValidation?: Record<string, any>;
  errorPosition?: 'right' | 'bottom';
};

export default function AddressForm({ mode, sx = {}, fieldValidation = {}, errorPosition = 'right' }: Props) {
  const { t, locale } = useLocaleContext();
  const { control } = useFormContext();
  const country = useWatch({ control, name: 'billing_address.country' });
  if (mode === 'required') {
    return (
      <Fade in>
        <Stack className="cko-payment-address cko-payment-form" sx={sx}>
          <Stack direction="column" className="cko-payment-form" spacing={0}>
            <FormLabel className="base-label">{t('payment.checkout.billing.line1')}</FormLabel>
            <FormInput
              name="billing_address.line1"
              rules={{
                required: t('payment.checkout.required'),
                ...getFieldValidation('billing_address.line1', fieldValidation, locale),
              }}
              errorPosition={errorPosition}
              variant="outlined"
              placeholder={t('payment.checkout.billing.line1')}
            />
            <FormLabel className="base-label">{t('payment.checkout.billing.city')}</FormLabel>
            <FormInput
              name="billing_address.city"
              rules={{
                required: t('payment.checkout.required'),
                ...getFieldValidation('billing_address.city', fieldValidation, locale),
              }}
              errorPosition={errorPosition}
              variant="outlined"
              placeholder={t('payment.checkout.billing.city')}
            />
            <FormLabel className="base-label">{t('payment.checkout.billing.state')}</FormLabel>
            <FormInput
              name="billing_address.state"
              rules={{
                required: t('payment.checkout.required'),
                ...getFieldValidation('billing_address.state', fieldValidation, locale),
              }}
              errorPosition={errorPosition}
              variant="outlined"
              placeholder={t('payment.checkout.billing.state')}
            />
            <FormLabel className="base-label">{t('payment.checkout.billing.postal_code')}</FormLabel>
            <FormInput
              name="billing_address.postal_code"
              rules={{
                required: t('payment.checkout.required'),
                validate: (x: string) => {
                  const isValid = validatePostalCode(x, country);
                  return isValid ? true : t('payment.checkout.invalid');
                },
                ...getFieldValidation('billing_address.postal_code', fieldValidation, locale),
              }}
              errorPosition={errorPosition}
              variant="outlined"
              placeholder={t('payment.checkout.billing.postal_code')}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start" style={{ marginRight: '2px', marginLeft: '-8px' }}>
                    <Controller
                      name="billing_address.country"
                      control={control}
                      render={({ field }) => (
                        <CountrySelect
                          {...field}
                          ref={field.ref as unknown as React.RefObject<HTMLDivElement | null>}
                          sx={{
                            '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                              borderColor: 'transparent',
                            },
                          }}
                        />
                      )}
                    />
                  </InputAdornment>
                ),
              }}
            />
          </Stack>
        </Stack>
      </Fade>
    );
  }

  return (
    <Fade in>
      <Stack className="cko-payment-address cko-payment-form" sx={sx}>
        <Stack direction="column" className="cko-payment-form" spacing={0}>
          <FormLabel className="base-label">{t('payment.checkout.billing.state')}</FormLabel>
          <FormInput
            name="billing_address.state"
            rules={{
              required: t('payment.checkout.required'),
              ...getFieldValidation('billing_address.state', fieldValidation, locale),
            }}
            errorPosition={errorPosition}
            variant="outlined"
            placeholder={t('payment.checkout.billing.state')}
          />
          <FormLabel className="base-label">{t('payment.checkout.billing.postal_code')}</FormLabel>
          <Stack direction="row" spacing={0}>
            <FormInput
              name="billing_address.postal_code"
              rules={{
                required: t('payment.checkout.required'),
                validate: (x: string) => {
                  const isValid = validatePostalCode(x, country);
                  return isValid ? true : t('payment.checkout.invalid');
                },
                ...getFieldValidation('billing_address.postal_code', fieldValidation, locale),
              }}
              errorPosition={errorPosition}
              variant="outlined"
              placeholder={t('payment.checkout.billing.postal_code')}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start" style={{ marginRight: '2px', marginLeft: '-8px' }}>
                    <Controller
                      name="billing_address.country"
                      control={control}
                      render={({ field }) => (
                        <CountrySelect
                          {...field}
                          ref={field.ref as unknown as React.RefObject<HTMLDivElement | null>}
                          sx={{
                            '.MuiOutlinedInput-notchedOutline': {
                              borderColor: 'transparent !important',
                            },
                          }}
                        />
                      )}
                    />
                  </InputAdornment>
                ),
              }}
            />
          </Stack>
        </Stack>
      </Stack>
    </Fade>
  );
}
