import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError } from '@blocklet/payment-react';
import { CircularProgress, Stack, Button } from '@mui/material';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import { dispatch } from 'use-bus';

import { EditOutlined } from '@mui/icons-material';
import DrawerForm from '../../../components/drawer-form';
import TaxRateForm, { TaxRateFormValues, generateTaxRateDisplayName } from '../../../components/tax/tax-rate-form';

type FormData = TaxRateFormValues & {
  metadata: Array<{ key: string; value: string }>;
};

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

export default function TaxRateEdit({
  id,
  initialData,
  onClose = undefined,
  onChange = () => {},
}: {
  id: string;
  initialData: TaxRateData;
  onClose?: () => void;
  onChange?: () => void;
}) {
  const { t, locale } = useLocaleContext();
  const navigate = useNavigate();

  const methods = useForm<FormData>({
    mode: 'onChange',
    defaultValues: {
      display_name: initialData.display_name,
      description: initialData.description || '',
      country: (initialData.country || '').toLowerCase(),
      state: initialData.state || '',
      postal_code: initialData.postal_code || '',
      tax_code: initialData.tax_code || '',
      percentage: initialData.percentage,
      metadata: initialData.metadata || {},
    },
  });

  const handleClose = () => {
    if (onClose) {
      onClose();
    } else {
      navigate(`/admin/tax/${id}`);
    }
  };

  const onSubmit = async (values: FormData) => {
    try {
      const displayName =
        values.display_name ||
        generateTaxRateDisplayName(
          values.country,
          values.state,
          values.postal_code,
          Number(values.percentage),
          values.tax_code,
          locale
        );

      await api.put(`/api/tax-rates/${id}`, {
        display_name: displayName,
        description: values.description,
        country: values.country,
        state: values.state || null,
        postal_code: values.postal_code || null,
        tax_code: values.tax_code || null,
        percentage: Number(values.percentage),
        metadata: values.metadata,
      });
      Toast.success(t('admin.taxRate.updated'));
      dispatch('tax-rate.updated');
      onChange();
      handleClose();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    }
  };

  return (
    <DrawerForm
      icon={<EditOutlined />}
      open
      onClose={handleClose}
      text={t('admin.taxRate.editTitle')}
      hideLiveMode
      width={720}
      addons={
        <Stack direction="row" spacing={1}>
          <Button variant="text" color="inherit" onClick={handleClose}>
            {t('common.cancel')}
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={methods.handleSubmit(onSubmit)}
            disabled={methods.formState.isSubmitting}>
            {methods.formState.isSubmitting && <CircularProgress size={16} sx={{ mr: 1 }} />}
            {t('common.save')}
          </Button>
        </Stack>
      }>
      <FormProvider {...methods}>
        <TaxRateForm isEdit />
      </FormProvider>
    </DrawerForm>
  );
}
