import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { api, formatError, useMobile, getCustomerAvatar, FormLabel } from '@blocklet/payment-react';
import type { TCustomer, TPaymentCurrency } from '@blocklet/payment-types';
import { Box, Stack, Autocomplete, TextField, Button, Avatar, Typography } from '@mui/material';
import { useSetState } from 'ahooks';
import Toast from '@arcblock/ux/lib/Toast';
import Dialog from '@arcblock/ux/lib/Dialog';
import dayjs from '../../libs/dayjs';

interface AddUsageDialogProps {
  open: boolean;
  onClose: () => void;
  meterId: string;
  customers: TCustomer[];
  paymentCurrency: TPaymentCurrency;
  onSuccess: () => void;
}

interface AddUsageState {
  loading: boolean;
  form: {
    customer_id: string;
    value: string;
    subscription_id: string;
    timestamp: Date;
  };
}

const addMeterEvent = (data: any): Promise<any> => {
  return api
    .post('/api/meter-events', {
      event_name: data.event_name,
      payload: {
        customer_id: data.customer_id,
        value: data.value,
        subscription_id: data.subscription_id || undefined,
      },
      timestamp: data.timestamp,
      identifier: `manual_${Date.now()}`,
      metadata: {
        source: 'manual',
        created_by: 'admin',
      },
      source_data: [
        {
          key: 'origin',
          label: 'created_by',
          value: 'Admin',
          type: 'text',
        },
      ],
    })
    .then((res: any) => res.data);
};

export default function AddUsageDialog({ open, onClose, meterId, customers, onSuccess }: AddUsageDialogProps) {
  const { t } = useLocaleContext();
  const { isMobile } = useMobile('md');

  const [state, setState] = useSetState<AddUsageState>({
    loading: false,
    form: {
      customer_id: '',
      value: '',
      subscription_id: '',
      timestamp: new Date(),
    },
  });

  const getCustomerDisplayName = (customer: TCustomer) => {
    return customer.name || customer.email || customer.did || customer.id;
  };

  const handleClose = () => {
    setState({
      form: {
        customer_id: '',
        value: '',
        subscription_id: '',
        timestamp: new Date(),
      },
    });
    onClose();
  };

  const handleSubmit = async () => {
    if (!state.form.customer_id || !state.form.value) {
      Toast.error(t('admin.meterEvent.add.validation'));
      return;
    }

    setState({ loading: true });
    try {
      // 获取计量器信息以获取事件名称
      const meterResponse = await api.get(`/api/meters/${meterId}`);
      const meter = meterResponse.data;

      await addMeterEvent({
        event_name: meter.event_name,
        customer_id: state.form.customer_id,
        value: state.form.value,
        subscription_id: state.form.subscription_id,
        timestamp: dayjs(state.form.timestamp).unix(),
      });

      Toast.success(t('admin.meterEvent.add.success'));
      handleClose();
      onSuccess();
    } catch (err) {
      console.error('Failed to add usage:', err);
      Toast.error(formatError(err));
    } finally {
      setState({ loading: false });
    }
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="sm"
      fullWidth
      fullScreen={isMobile}
      title={t('admin.meterEvent.add.title')}
      actions={
        <>
          <Button onClick={handleClose} variant="outlined" disabled={state.loading}>
            {t('common.cancel')}
          </Button>
          <Button onClick={handleSubmit} variant="contained" disabled={state.loading}>
            {t('admin.meterEvent.add.submit')}
          </Button>
        </>
      }>
      <Box>
        <Stack spacing={3}>
          <Box>
            <FormLabel sx={{ color: 'text.primary' }}>{t('admin.meterEvent.add.customerId')}</FormLabel>
            <Autocomplete
              options={customers}
              getOptionLabel={getCustomerDisplayName}
              value={customers.find((c) => c.id === state.form.customer_id) || null}
              onChange={(_, customer) =>
                setState({
                  form: {
                    ...state.form,
                    customer_id: customer?.id || '',
                  },
                })
              }
              renderOption={(props, customer) => (
                <Box component="li" {...props} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Avatar
                    src={getCustomerAvatar(
                      customer.did,
                      customer?.updated_at ? new Date(customer.updated_at).toISOString() : undefined,
                      24
                    )}
                    sx={{ width: 24, height: 24 }}
                    alt={getCustomerDisplayName(customer)}
                  />
                  {getCustomerDisplayName(customer)}
                </Box>
              )}
              renderInput={(params) => (
                <TextField {...params} placeholder={t('admin.meterEvent.add.customerIdPlaceholder')} fullWidth />
              )}
            />
          </Box>

          <Box>
            <FormLabel sx={{ color: 'text.primary' }}>{t('admin.meterEvent.add.value')}</FormLabel>
            <TextField
              type="number"
              fullWidth
              value={state.form.value}
              onChange={(e) =>
                setState({
                  form: {
                    ...state.form,
                    value: e.target.value,
                  },
                })
              }
              placeholder={t('admin.meterEvent.add.valuePlaceholder')}
            />
          </Box>

          <Box>
            <FormLabel sx={{ color: 'text.primary' }}>{t('admin.meterEvent.add.subscriptionId')}</FormLabel>
            <TextField
              fullWidth
              value={state.form.subscription_id}
              onChange={(e) =>
                setState({
                  form: {
                    ...state.form,
                    subscription_id: e.target.value,
                  },
                })
              }
              placeholder={t('admin.meterEvent.add.subscriptionIdPlaceholder')}
            />
            <Typography
              variant="caption"
              sx={{
                color: 'text.secondary',
                mt: 0.5,
                display: 'block',
              }}>
              {t('admin.meterEvent.add.subscriptionIdHint')}
            </Typography>
          </Box>

          <Box>
            <FormLabel sx={{ color: 'text.primary' }}>{t('admin.meterEvent.add.timestamp')}</FormLabel>
            <TextField
              type="datetime-local"
              fullWidth
              value={dayjs(state.form.timestamp).format('YYYY-MM-DDTHH:mm')}
              onChange={(e) =>
                setState({
                  form: {
                    ...state.form,
                    timestamp: new Date(e.target.value),
                  },
                })
              }
              InputLabelProps={{
                shrink: true,
              }}
            />
            <Typography
              variant="caption"
              sx={{
                color: 'text.secondary',
                mt: 0.5,
                display: 'block',
              }}>
              {t('admin.meterEvent.add.timestampHint')}
            </Typography>
          </Box>
        </Stack>
      </Box>
    </Dialog>
  );
}
