import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Collapse, CountrySelect, FormInput, FormLabel } from '@blocklet/payment-react';
import { InputAdornment, Stack, TextField, Typography } from '@mui/material';
import { Controller, useFormContext } from 'react-hook-form';
import { defaultCountries, parseCountry } from 'react-international-phone';

import MetadataForm from '../metadata/form';
import TaxCodeSelect from './tax-code-select';
import taxCodesRaw from './taxCodes.json';

export type TaxRateFormValues = {
  display_name: string;
  description?: string;
  country: string;
  state?: string;
  postal_code?: string;
  tax_code?: string;
  percentage: number;
  metadata?: Record<string, any>;
};

export const generateTaxRateDisplayName = (
  country: string,
  state: string | undefined,
  postalCode: string | undefined,
  percentage: number,
  taxCode: string | undefined,
  locale: string
): string => {
  const taxCodesById: Record<string, any> = taxCodesRaw as unknown as Record<string, any>;
  const parts: string[] = [];

  if (country) {
    const match = defaultCountries.find((item) => item[1] === country.toLowerCase());
    if (match) {
      const countryData = parseCountry(match);
      parts.push(countryData.name);
    } else {
      parts.push(country.toUpperCase());
    }
  }

  if (state) {
    parts.push(state);
  }

  if (postalCode) {
    parts.push(postalCode);
  }

  if (taxCode && taxCodesById[taxCode]) {
    const taxCodeData = taxCodesById[taxCode];
    const language = locale.startsWith('zh') ? 'zh' : 'en';
    const taxCodeName = taxCodeData.name?.[language] || taxCodeData.name?.en || '';
    if (taxCodeName) {
      parts.push(`(${taxCodeName})`);
    }
  }

  const locationPart = parts.join(' · ');
  return `${locationPart} - ${percentage}%`;
};

export default function TaxRateForm({ isEdit = false }: { isEdit?: boolean }) {
  const { t } = useLocaleContext();
  const {
    control,
    register,
    formState: { errors },
  } = useFormContext<TaxRateFormValues & { metadata: any }>();

  return (
    <Stack spacing={3} sx={{ py: 1 }}>
      <Stack spacing={2}>
        {/* 必填字段区域 */}
        <Stack spacing={1}>
          <FormLabel sx={{ color: 'text.primary', my: 0 }} required>
            {t('admin.taxRate.country')}
          </FormLabel>

          <Controller
            name="country"
            control={control}
            rules={{ required: t('admin.taxRate.countryRequired') }}
            render={({ field: { ref, ...fieldProps } }) => (
              <>
                <CountrySelect
                  {...fieldProps}
                  name={fieldProps.name as any}
                  onChange={(value) => fieldProps.onChange(value || '')}
                  disabled={isEdit}
                />
                {errors.country && (
                  <Typography variant="caption" color="error">
                    {errors.country.message as string}
                  </Typography>
                )}
              </>
            )}
          />
        </Stack>

        <FormInput
          name="percentage"
          type="number"
          label={t('admin.taxRate.percentage')}
          placeholder="0"
          required
          InputProps={{
            endAdornment: <InputAdornment position="end">%</InputAdornment>,
          }}
          rules={{
            required: t('admin.taxRate.percentageRequired'),
            min: { value: 0, message: t('admin.taxRate.percentageMin') },
            max: { value: 99.9999, message: t('admin.taxRate.percentageMax') },
          }}
        />

        {/* 可选字段区域 */}
        <Stack spacing={1}>
          <FormLabel sx={{ color: 'text.primary', my: 0 }}>{t('admin.taxRate.taxCode')}</FormLabel>
          <TaxCodeSelect label="" placeholder={t('admin.taxRate.selectTaxCode')} disabled={isEdit} />
        </Stack>

        <Stack direction={{ xs: 'column', md: 'row' }} spacing={2}>
          <Stack spacing={1} sx={{ flex: 1 }}>
            <FormLabel sx={{ color: 'text.primary', my: 0 }}>{t('admin.taxRate.state')}</FormLabel>
            <TextField size="small" {...register('state')} placeholder={t('admin.taxRate.state')} disabled={isEdit} />
          </Stack>
          <Stack spacing={1} sx={{ flex: 1 }}>
            <FormLabel sx={{ color: 'text.primary', my: 0 }}>{t('admin.taxRate.postalCode')}</FormLabel>

            <TextField
              size="small"
              {...register('postal_code')}
              placeholder={t('admin.taxRate.postalCode')}
              disabled={isEdit}
            />
          </Stack>
        </Stack>

        <FormInput
          name="display_name"
          label={t('admin.taxRate.displayName')}
          placeholder={t('admin.taxRate.displayNameAuto')}
          rules={{
            maxLength: {
              value: 100,
              message: t('common.maxLength', { len: 100 }),
            },
          }}
        />

        <FormInput
          name="description"
          label={t('admin.taxRate.description')}
          placeholder={t('admin.taxRate.descriptionPlaceholder')}
          multiline
          minRows={2}
          maxRows={4}
          rules={{
            maxLength: {
              value: 500,
              message: t('common.maxLength', { len: 500 }),
            },
          }}
        />
      </Stack>

      <Collapse trigger={t('admin.taxRate.advanced')}>
        <Stack spacing={1}>
          <MetadataForm title={t('common.metadata.label')} name="metadata" color="inherit" />
        </Stack>
      </Collapse>
    </Stack>
  );
}
