import 'react-international-phone/style.css';

import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import {
  FormInput,
  PhoneInput,
  CountrySelect,
  validatePhoneNumber,
  getPhoneUtil,
  validatePostalCode,
  FormLabel,
} from '@blocklet/payment-react';
import { Stack } from '@mui/material';
import { Controller, useFormContext, useWatch } from 'react-hook-form';
import isEmail from 'validator/es/lib/isEmail';
import { useMount } from 'ahooks';

export default function CustomerForm() {
  const { t } = useLocaleContext();
  const { control } = useFormContext();
  useMount(() => {
    getPhoneUtil().catch((err) => {
      console.error('Failed to preload phone validator:', err);
    });
  });

  const country = useWatch({ control, name: 'address.country' });

  return (
    <Stack
      direction="column"
      spacing={1}
      sx={{
        '.MuiFormLabel-root': {
          color: 'text.primary',
          mt: 1,
          mb: 0.5,
        },
      }}>
      <FormInput
        name="name"
        variant="outlined"
        errorPosition="right"
        rules={{
          required: t('payment.checkout.required'),
          minLength: {
            value: 2,
            message: t('common.minLength', { len: 2 }),
          },
          maxLength: {
            value: 30,
            message: t('common.maxLength', { len: 30 }),
          },
        }}
        inputProps={{
          maxLength: 30,
        }}
        label={t('payment.checkout.customer.name')}
      />
      <FormInput
        name="email"
        variant="outlined"
        errorPosition="right"
        rules={{
          required: t('payment.checkout.required'),
          validate: (x) => (isEmail(x) ? true : t('payment.checkout.invalid')),
        }}
        label={t('payment.checkout.customer.email')}
      />
      <FormLabel className="base-label">{t('payment.checkout.customer.phone')}</FormLabel>
      <PhoneInput
        name="phone"
        variant="outlined"
        countryFieldName="address.country"
        errorPosition="right"
        placeholder={t('payment.checkout.customer.phonePlaceholder')}
        rules={{
          required: t('payment.checkout.required'),
          validate: async (x: string) => {
            const isValid = await validatePhoneNumber(x);
            return isValid ? true : t('payment.checkout.invalid');
          },
        }}
      />
      <FormLabel className="base-label">{t('payment.checkout.billing.required')}</FormLabel>
      <Controller
        name="address.country"
        control={control}
        render={({ field }) => (
          <CountrySelect
            {...field}
            ref={field.ref as unknown as React.RefObject<HTMLDivElement | null>}
            sx={{ pl: '6px' }}
          />
        )}
      />
      <FormInput
        name="address.state"
        variant="outlined"
        errorPosition="right"
        label={t('payment.checkout.billing.state')}
        placeholder={t('payment.checkout.billing.state')}
        inputProps={{
          maxLength: 50,
        }}
        rules={{
          maxLength: {
            value: 50,
            message: t('common.maxLength', { len: 50 }),
          },
        }}
      />
      <FormInput
        name="address.city"
        variant="outlined"
        errorPosition="right"
        label={t('payment.checkout.billing.city')}
        placeholder={t('payment.checkout.billing.city')}
        inputProps={{
          maxLength: 50,
        }}
        rules={{
          maxLength: {
            value: 50,
            message: t('common.maxLength', { len: 50 }),
          },
        }}
      />
      <FormInput
        name="address.line1"
        variant="outlined"
        errorPosition="right"
        label={t('payment.checkout.billing.line1')}
        placeholder={t('payment.checkout.billing.line1')}
        inputProps={{
          maxLength: 100,
        }}
        rules={{
          maxLength: {
            value: 100,
            message: t('common.maxLength', { len: 100 }),
          },
        }}
      />
      <FormInput
        name="address.line2"
        variant="outlined"
        errorPosition="right"
        label={t('payment.checkout.billing.line2')}
        placeholder={t('payment.checkout.billing.line2')}
        inputProps={{
          maxLength: 100,
        }}
        rules={{
          maxLength: {
            value: 100,
            message: t('common.maxLength', { len: 100 }),
          },
        }}
      />
      <FormInput
        name="address.postal_code"
        variant="outlined"
        errorPosition="right"
        label={t('payment.checkout.billing.postal_code')}
        placeholder={t('payment.checkout.billing.postal_code')}
        rules={{
          maxLength: {
            value: 20,
            message: t('common.maxLength', { len: 20 }),
          },
          validate: (x: string) => {
            const isValid = validatePostalCode(x, country);
            return isValid ? true : t('payment.checkout.invalid');
          },
        }}
      />
    </Stack>
  );
}
