import { useForm, Controller, FormProvider } from 'react-hook-form';
import {
  Box,
  Grid,
  TextField,
  Switch,
  Button,
  Typography,
  Stack,
  Paper,
  Divider,
  ToggleButtonGroup,
  ToggleButton,
} from '@mui/material';
import { api, formatError, clearDonateCache } from '@blocklet/payment-react';
import Toast from '@arcblock/ux/lib/Toast';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { TSetting } from '@blocklet/payment-types';
import { useState, useEffect, useRef } from 'react';
import DonationPreview from './preview';

type FormData = {
  settings: {
    btnText: string;
    amount: {
      presets: string[];
      preset: string;
      minimum: string;
      maximum: string;
      custom: boolean;
    };
    historyType: 'avatar' | 'table';
  };
};

function NumberArrayInput({ value, onChange }: { value: string[]; onChange: (value: string[]) => void }) {
  const { t } = useLocaleContext();
  const [inputValue, setInputValue] = useState(value.join(', '));
  const isSelfUpdate = useRef(false); // 新增标志位

  useEffect(() => {
    if (isSelfUpdate.current) {
      isSelfUpdate.current = false;
      return;
    }
    setInputValue(value.join(', '));
  }, [value]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value: val } = e.target;

    if (!/^[\d,.\s]*$/.test(val)) return;

    setInputValue(val);

    // 添加处理空字符串的情况
    const rawValues = val.split(/[,\s]+/).filter(Boolean);
    const numbers = rawValues
      .map((v) => v.trim())
      .filter((v) => !Number.isNaN(Number(v)))
      .map(Number)
      .filter((v, i, arr) => arr.indexOf(v) === i);

    isSelfUpdate.current = true; // 标记为内部更新
    onChange(numbers.map(String));
  };

  return (
    <TextField
      fullWidth
      label={t('admin.donate.presets')}
      helperText={t('admin.donate.presetsHelper')}
      value={inputValue}
      onChange={handleChange}
      placeholder="1, 5, 10"
      sx={{ bgcolor: 'background.paper' }}
      onBlur={() => {
        // 失焦时强制同步显示格式
        const formatted = (inputValue.match(/[\d.]+/g) || []).join(', ');
        setInputValue(formatted);
      }}
    />
  );
}

export default function EditDonationForm({
  item,
  onSuccess,
  onCancel,
}: {
  item: TSetting;
  onSuccess: () => void;
  onCancel: () => void;
}) {
  const { t } = useLocaleContext();
  const methods = useForm<FormData>({
    defaultValues: {
      settings: {
        amount: {
          presets: item?.settings?.amount?.presets,
          preset: item?.settings?.amount?.preset,
          minimum: item?.settings?.amount?.minimum,
          maximum: item?.settings?.amount?.maximum,
          custom: item?.settings?.amount?.custom,
        },
        btnText: item?.settings?.btnText,
        historyType: item?.settings?.historyType,
      },
    },
  });

  const { handleSubmit, watch } = methods;
  const formValues = watch();

  const onSubmit = async (data: FormData) => {
    if (data.settings.amount.presets?.length > 0 && data.settings.amount.preset) {
      const inPresets = data.settings.amount.presets.includes(data.settings.amount.preset);
      if (!inPresets) {
        Toast.error(t('admin.donate.validation.invalidPreset'));
        return;
      }
    }
    try {
      await api.put(`/api/settings/${item.id}`, data);
      clearDonateCache(item.mount_location);
      Toast.success(t('admin.donate.updateSuccess'));
      onSuccess();
    } catch (err) {
      Toast.error(formatError(err));
    }
  };

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
      }}>
      <Box
        sx={{
          flex: 1,
          overflow: {
            xs: 'visible',
            md: 'auto',
          },
          pb: 2,
          display: 'flex',
          flexDirection: 'column',
        }}>
        <FormProvider {...methods}>
          <Grid
            container
            spacing={3}
            sx={{
              flex: 1,
              minHeight: 0,
            }}>
            <Grid
              sx={{
                height: '100%',
              }}
              size={{
                xs: 12,
                md: 6,
              }}>
              <Paper
                elevation={0}
                sx={{
                  p: { xs: 2, md: 3 },
                  bgcolor: 'background.neutral',
                  height: '100%',
                  overflow: 'auto',
                }}>
                <Stack spacing={4}>
                  <Box>
                    <Typography
                      variant="h6"
                      gutterBottom
                      sx={{
                        color: 'text.primary',
                        mb: 3,
                      }}>
                      {t('admin.donate.buttonSettings')}
                    </Typography>
                    <Stack spacing={3}>
                      <Controller
                        name="settings.btnText"
                        render={({ field }) => (
                          <TextField
                            {...field}
                            fullWidth
                            label={t('admin.donate.btn.text')}
                            helperText={t('admin.donate.btn.helper')}
                            sx={{ bgcolor: 'background.paper' }}
                          />
                        )}
                      />

                      <Stack
                        sx={{
                          gap: 1,
                        }}>
                        <Typography variant="subtitle2" gutterBottom>
                          {t('admin.donate.historyType.title')}
                        </Typography>
                        <Controller
                          name="settings.historyType"
                          render={({ field }) => (
                            <ToggleButtonGroup
                              value={field.value}
                              exclusive
                              onChange={(_, value) => field.onChange(value)}
                              size="small"
                              sx={{ bgcolor: 'background.paper' }}>
                              <ToggleButton value="table" size="small">
                                {t('admin.donate.historyType.list')}
                              </ToggleButton>
                              <ToggleButton value="avatar" size="small">
                                {t('admin.donate.historyType.avatar')}
                              </ToggleButton>
                            </ToggleButtonGroup>
                          )}
                        />
                      </Stack>
                    </Stack>
                  </Box>

                  <Divider />

                  <Box>
                    <Typography
                      variant="h6"
                      gutterBottom
                      sx={{
                        color: 'text.primary',
                        mb: 3,
                      }}>
                      {t('admin.donate.amountSettings')}
                    </Typography>
                    <Stack spacing={3}>
                      <Controller
                        control={methods.control}
                        name="settings.amount.presets"
                        render={({ field }) => <NumberArrayInput value={field.value || []} onChange={field.onChange} />}
                      />
                      <Controller
                        name="settings.amount.preset"
                        render={({ field }) => (
                          <TextField
                            {...field}
                            fullWidth
                            label={t('admin.donate.preset')}
                            helperText={t('admin.donate.presetHelper')}
                            sx={{ bgcolor: 'background.paper' }}
                          />
                        )}
                      />

                      <Box
                        sx={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: 2,
                        }}>
                        <Typography variant="subtitle2" gutterBottom>
                          {t('admin.donate.custom')}
                        </Typography>
                        <Controller
                          name="settings.amount.custom"
                          render={({ field }) => (
                            <Switch
                              checked={field.value}
                              onChange={(e) => field.onChange(e.target.checked)}
                              size="small"
                            />
                          )}
                        />
                      </Box>

                      {formValues.settings.amount.custom && (
                        <Stack spacing={2} sx={{ mt: 2 }}>
                          <Controller
                            name="settings.amount.minimum"
                            render={({ field }) => (
                              <TextField
                                {...field}
                                fullWidth
                                label={t('admin.donate.minimum')}
                                type="number"
                                sx={{ bgcolor: 'background.paper' }}
                              />
                            )}
                          />
                          <Controller
                            name="settings.amount.maximum"
                            render={({ field }) => (
                              <TextField
                                {...field}
                                fullWidth
                                label={t('admin.donate.maximum')}
                                type="number"
                                sx={{ bgcolor: 'background.paper' }}
                              />
                            )}
                          />
                        </Stack>
                      )}
                    </Stack>
                  </Box>
                </Stack>
              </Paper>
            </Grid>

            <Grid
              sx={{
                display: { xs: 'none', md: 'block' },
                height: '100%',
              }}
              size={{
                md: 6,
              }}>
              <Paper
                elevation={0}
                sx={{
                  p: 3,
                  bgcolor: 'background.neutral',
                  height: '100%',
                  overflow: 'auto',
                }}>
                <DonationPreview config={methods.watch()} />
              </Paper>
            </Grid>
          </Grid>
        </FormProvider>
      </Box>
      <Box
        sx={{
          mt: 2,
          pt: 2,
          pb: 2,
          px: 2,
          borderTop: 1,
          borderColor: 'divider',
          display: 'flex',
          justifyContent: 'flex-end',
          gap: 2,
          bgcolor: 'background.paper',
          position: 'sticky',
          bottom: 0,
          left: 0,
          right: 0,
          zIndex: 1,
        }}>
        <Button onClick={onCancel} variant="outlined">
          {t('common.cancel')}
        </Button>
        <Button variant="contained" onClick={handleSubmit(onSubmit)}>
          {t('common.save')}
        </Button>
      </Box>
    </Box>
  );
}
