import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { api, formatError, formatTime, useMobile } from '@blocklet/payment-react';
import { ArrowBackOutlined, EditOutlined } from '@mui/icons-material';
import { Alert, Box, Button, CircularProgress, Divider, Stack, Tooltip, Typography } from '@mui/material';
import { styled } from '@mui/system';
import { useRequest, useSetState } from 'ahooks';
import { useNavigate } from 'react-router-dom';
import { useForm, FormProvider } from 'react-hook-form';
import { dispatch } from 'use-bus';
import { FlagEmoji } from 'react-international-phone';

import Copyable from '../../../components/copyable';
import InfoMetric from '../../../components/info-metric';
import InfoRow from '../../../components/info-row';
import InfoRowGroup from '../../../components/info-row-group';
import InvoiceList from '../../../components/invoice/list';
import MetadataEditor from '../../../components/metadata/editor';
import MetadataList from '../../../components/metadata/list';
import SectionHeader from '../../../components/section/header';
import TaxRateActions from '../../../components/tax/actions';
import TaxRateForm, { TaxRateFormValues } from '../../../components/tax/tax-rate-form';
import DrawerForm from '../../../components/drawer-form';
import { goBackOrFallback } from '../../../libs/util';
import { getTaxCodeInfo, getCountryInfo } from '../../../components/tax/tax-utils';

const getTaxRate = (id: string) => api.get(`/api/tax-rates/${id}`).then((res: any) => res.data);

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

const toMetadataArray = (metadata: Record<string, any> = {}) =>
  Object.entries(metadata).map(([key, value]) => ({
    key,
    value: typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value),
  }));

const toMetadataObject = (metadataArray: Array<{ key: string; value: string }>) =>
  metadataArray.reduce((acc: Record<string, any>, item) => {
    if (!item.key) return acc;
    if (!item.value) return acc;
    try {
      acc[item.key] = JSON.parse(item.value);
    } catch {
      acc[item.key] = item.value;
    }
    return acc;
  }, {});

type Props = {
  id: string;
};

export default function TaxRateDetail({ id }: Props) {
  const { t, locale } = useLocaleContext();
  const { isMobile } = useMobile();
  const navigate = useNavigate();

  const [state, setState] = useSetState({
    editing: {
      metadata: false,
      taxRate: false,
    },
    loading: {
      metadata: false,
      taxRate: false,
    },
  });

  const methods = useForm<FormData>({
    defaultValues: {
      display_name: '',
      description: '',
      country: '',
      state: '',
      postal_code: '',
      tax_code: '',
      percentage: 0,
      metadata: [{ key: '', value: '' }],
    },
  });

  const { data, loading, error, runAsync } = useRequest<any, any[]>(() => getTaxRate(id));

  if (loading && !data) {
    return <CircularProgress />;
  }

  if (error) {
    return <Alert severity="error">{error.message}</Alert>;
  }

  if (!data) {
    return null;
  }

  const onChange = (action?: string) => {
    if (action === 'delete') {
      navigate('/admin/tax/rates');
    } else {
      runAsync();
    }
  };

  const handleEditMetadata = () => {
    setState((prev) => ({ editing: { ...prev.editing, metadata: true } }));
  };

  const handleEditTaxRate = () => {
    methods.reset({
      display_name: data.display_name,
      description: data.description || '',
      country: (data.country || '').toLowerCase(),
      state: data.state || '',
      postal_code: data.postal_code || '',
      tax_code: data.tax_code || '',
      percentage: data.percentage,
      metadata: toMetadataArray(data.metadata || {}),
    });
    setState((prev) => ({ editing: { ...prev.editing, taxRate: true } }));
  };

  const onUpdateMetadata = async (updates: any) => {
    try {
      setState((prev) => ({ loading: { ...prev.loading, metadata: true } }));
      await api.put(`/api/tax-rates/${id}`, updates);
      Toast.success(t('common.saved'));
      dispatch('tax-rate.updated');
      runAsync();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState((prev) => ({ loading: { ...prev.loading, metadata: false } }));
    }
  };

  const onUpdateTaxRate = async (formData: FormData) => {
    try {
      setState((prev) => ({ loading: { ...prev.loading, taxRate: true } }));
      const { metadata, ...rest } = formData;
      await api.put(`/api/tax-rates/${id}`, {
        ...rest,
        percentage: Number(rest.percentage),
        metadata: toMetadataObject(metadata || []),
      });
      Toast.success(t('admin.taxRate.updated'));
      dispatch('tax-rate.updated');
      setState((prev) => ({ editing: { ...prev.editing, taxRate: false } }));
      runAsync();
    } catch (err) {
      console.error(err);
      Toast.error(formatError(err));
    } finally {
      setState((prev) => ({ loading: { ...prev.loading, taxRate: false } }));
    }
  };

  const countryInfo = data.country ? getCountryInfo(data.country) : null;
  const locationParts = [data.state, data.postal_code].filter(Boolean);
  const location = countryInfo
    ? `${countryInfo.name}${locationParts.length > 0 ? ` · ${locationParts.join(' · ')}` : ''}`
    : '—';

  const taxCodeInfo = data.tax_code ? getTaxCodeInfo(data.tax_code, locale) : null;

  return (
    <Root direction="column" spacing={2.5} sx={{ mb: 4 }}>
      <Box>
        {!data.active && (
          <Alert severity="warning" sx={{ mb: 2 }}>
            {t('admin.taxRate.inactiveWarning')}
          </Alert>
        )}
        <Stack
          className="page-header"
          direction="row"
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          <Stack
            direction="row"
            onClick={() => goBackOrFallback('/admin/tax/rates')}
            sx={{
              alignItems: 'center',
              fontWeight: 'normal',
              cursor: 'pointer',
            }}>
            <ArrowBackOutlined fontSize="small" sx={{ mr: 0.5, color: 'text.secondary' }} />
            <Typography variant="h6" sx={{ color: 'text.secondary', fontWeight: 'normal' }}>
              {t('admin.taxRates')}
            </Typography>
          </Stack>
          <TaxRateActions data={data} onChange={onChange} />
        </Stack>
        <Box
          sx={{
            mt: 4,
            mb: 3,
            display: 'flex',
            gap: {
              xs: 2,
              sm: 2,
              md: 5,
            },
            flexWrap: 'wrap',
            flexDirection: {
              xs: 'column',
              sm: 'column',
              md: 'row',
            },
            alignItems: {
              xs: 'flex-start',
              sm: 'flex-start',
              md: 'center',
            },
          }}>
          <Stack
            direction="row"
            sx={{
              justifyContent: 'space-between',
              alignItems: 'center',
            }}>
            <Stack
              direction="column"
              sx={{
                alignItems: 'flex-start',
                justifyContent: 'space-around',
              }}>
              <Typography
                variant="h2"
                sx={{
                  color: 'text.primary',
                }}>
                {data.display_name}
              </Typography>
              {data.description && (
                <Typography
                  variant="subtitle1"
                  sx={{
                    color: 'text.lighter',
                  }}>
                  {data.description}
                </Typography>
              )}
            </Stack>
          </Stack>
          <Stack
            className="section-body"
            sx={{
              justifyContent: 'flex-start',
              flexWrap: 'wrap',
              'hr.MuiDivider-root:last-child': {
                display: 'none',
              },
              flexDirection: {
                xs: 'column',
                sm: 'column',
                md: 'row',
              },
              alignItems: 'flex-start',
              gap: {
                xs: 1,
                sm: 1,
                md: 3,
              },
            }}>
            <InfoMetric label={t('common.id')} value={<Copyable text={id} style={{ marginLeft: 4 }} />} divider />
            <InfoMetric label={t('admin.taxRate.percentage')} value={`${data.percentage}%`} divider />
            <InfoMetric
              label={t('admin.taxRate.location')}
              value={
                countryInfo ? (
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <FlagEmoji iso2={data.country.toLowerCase()} style={{ width: 24 }} />
                    <Typography variant="body2">{location}</Typography>
                  </Box>
                ) : (
                  location
                )
              }
              divider
            />
            <InfoMetric label={t('common.createdAt')} value={formatTime(data.created_at)} divider />
          </Stack>
        </Box>
        <Divider />
      </Box>
      <Stack
        sx={{
          flexDirection: {
            xs: 'column',
            lg: 'row',
          },
          gap: {
            xs: 2.5,
            md: 4,
          },
          '.tax-column-1': {
            minWidth: {
              xs: '100%',
              lg: '600px',
            },
          },
          '.tax-column-2': {
            width: {
              xs: '100%',
              md: '100%',
              lg: '320px',
            },
            maxWidth: {
              xs: '100%',
              md: '33%',
            },
          },
        }}>
        <Box
          className="tax-column-1"
          sx={{
            flex: 1,
            gap: 2.5,
            display: 'flex',
            flexDirection: 'column',
          }}>
          <Box className="section" sx={{ containerType: 'inline-size' }}>
            <SectionHeader title={t('admin.details')}>
              <Button
                variant="text"
                color="inherit"
                size="small"
                sx={{ color: 'text.link' }}
                disabled={state.editing.taxRate}
                onClick={handleEditTaxRate}>
                {t('common.edit')}
              </Button>
            </SectionHeader>
            <InfoRowGroup
              sx={{
                display: 'grid',
                gridTemplateColumns: {
                  xs: 'repeat(1, 1fr)',
                  xl: 'repeat(2, 1fr)',
                },
                '@container (min-width: 1000px)': {
                  gridTemplateColumns: 'repeat(2, 1fr)',
                },
                '.info-row-wrapper': {
                  gap: 1,
                  flexDirection: {
                    xs: 'column',
                    xl: 'row',
                  },
                  alignItems: {
                    xs: 'flex-start',
                    xl: 'center',
                  },
                  '@container (min-width: 1000px)': {
                    flexDirection: 'row',
                    alignItems: 'center',
                  },
                },
              }}>
              <InfoRow label={t('admin.taxRate.displayName')} value={data.display_name} />
              <InfoRow
                label={t('admin.taxRate.country')}
                value={
                  countryInfo ? (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <FlagEmoji iso2={data.country.toLowerCase()} style={{ width: 24 }} />
                      <Typography variant="body2">{countryInfo.name}</Typography>
                    </Box>
                  ) : (
                    '—'
                  )
                }
              />
              <InfoRow label={t('admin.taxRate.state')} value={data.state || '—'} />
              <InfoRow label={t('admin.taxRate.postalCode')} value={data.postal_code || '—'} />
              <InfoRow label={t('admin.taxRate.percentage')} value={`${data.percentage}%`} />
              <InfoRow
                label={t('admin.taxRate.taxCode')}
                value={
                  taxCodeInfo ? (
                    <Tooltip title={taxCodeInfo.description} arrow placement="top">
                      <Box>
                        <Typography variant="body2" sx={{ fontWeight: 500 }}>
                          {taxCodeInfo.name}
                        </Typography>
                        <Typography
                          variant="caption"
                          sx={{
                            color: 'text.secondary',
                          }}>
                          {taxCodeInfo.id}
                        </Typography>
                      </Box>
                    </Tooltip>
                  ) : (
                    data.tax_code || '—'
                  )
                }
              />
              <InfoRow label={t('common.status')} value={data.active ? t('common.active') : t('common.inactive')} />
              <InfoRow label={t('common.updatedAt')} value={formatTime(data.updated_at)} />
            </InfoRowGroup>
          </Box>
          <Divider />

          <Box className="section">
            <SectionHeader title={t('admin.taxRate.associatedInvoices')} />
            <Box className="section-body">
              <InvoiceList
                features={{ customer: true, filter: false, toolbar: false }}
                tax_rate_id={id}
                mode="admin"
                status=""
              />
            </Box>
          </Box>
        </Box>
        {isMobile && <Divider />}
        <Box className="tax-column-2" sx={{ gap: 2.5, display: 'flex', flexDirection: 'column' }}>
          <Box className="section">
            <SectionHeader title={t('common.metadata.label')}>
              <Button
                variant="text"
                color="inherit"
                size="small"
                sx={{ color: 'text.link' }}
                disabled={state.editing.metadata}
                onClick={handleEditMetadata}>
                {t('common.edit')}
              </Button>
            </SectionHeader>
            <Box className="section-body">
              <MetadataList data={data.metadata || {}} handleEditMetadata={handleEditMetadata} />
              {state.editing.metadata && (
                <MetadataEditor
                  data={data}
                  loading={state.loading.metadata}
                  onSave={onUpdateMetadata}
                  onCancel={() => setState((prev) => ({ editing: { ...prev.editing, metadata: false } }))}
                />
              )}
            </Box>
          </Box>
        </Box>
      </Stack>
      {state.editing.taxRate && (
        <DrawerForm
          icon={<EditOutlined />}
          text={t('admin.taxRate.edit')}
          open={state.editing.taxRate}
          onClose={() => setState((prev) => ({ editing: { ...prev.editing, taxRate: false } }))}
          width={640}
          addons={
            <Button
              variant="contained"
              size="small"
              disabled={state.loading.taxRate}
              onClick={methods.handleSubmit(onUpdateTaxRate)}>
              {t('common.save')}
            </Button>
          }>
          <FormProvider {...methods}>
            <TaxRateForm />
          </FormProvider>
        </DrawerForm>
      )}
    </Root>
  );
}

const Root = styled(Stack)``;
