import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import Toast from '@arcblock/ux/lib/Toast';
import { formatError } from '@blocklet/payment-react';
import { Check, Close, EditOutlined } from '@mui/icons-material';
import { IconButton, Stack, TextField, Typography } from '@mui/material';
import { useState, useEffect } from 'react';

interface EditInLineProps {
  value: string;
  onSave: (newValue: string) => Promise<void>;
  placeholder?: string;
  required?: boolean;
  disabled?: boolean;
  multiline?: boolean;
  maxLength?: number;
  validate?: (value: string) => string | null;
  successMessage?: string;
  autoFocus?: boolean;
  onEdit?: () => void;
  onCancel?: () => void;
  hideSuccessToast?: boolean;
}

export default function EditInLine({
  value,
  onSave,
  placeholder = '',
  required = true,
  disabled = false,
  multiline = false,
  maxLength = 255,
  validate = () => null,
  successMessage = '',
  autoFocus = false,
  onEdit = () => {},
  onCancel = () => {},
  hideSuccessToast = false,
}: EditInLineProps) {
  const [edit, setEdit] = useState(false);
  const [tempValue, setTempValue] = useState(value);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const { t } = useLocaleContext();

  // 当外部 value 变化时同步更新
  useEffect(() => {
    if (!edit) {
      setTempValue(value);
    }
  }, [value, edit]);

  const validateValue = (val: string): string => {
    if (required && !val.trim()) {
      return t('common.required');
    }
    if (maxLength && val.length > maxLength) {
      return t('common.maxLength', { len: maxLength });
    }
    if (validate) {
      const customError = validate(val);
      if (customError) {
        return customError;
      }
    }
    return '';
  };

  const handleSave = async () => {
    const validationError = validateValue(tempValue);
    if (validationError) {
      setError(validationError);
      return;
    }

    setLoading(true);
    try {
      await onSave(tempValue);
      if (!hideSuccessToast) {
        Toast.success(successMessage || t('common.saved'));
      }
      setEdit(false);
      setError('');
    } catch (err) {
      Toast.error(formatError(err));
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    setTempValue(value);
    setEdit(false);
    setError('');
    onCancel?.();
  };

  const handleChange = (newValue: string) => {
    setTempValue(newValue);
    const validationError = validateValue(newValue);
    setError(validationError);
  };

  const handleEdit = () => {
    setEdit(true);
    setTempValue(value);
    setError('');
    onEdit?.();
  };

  if (disabled) {
    return (
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {value || <span style={{ fontStyle: 'italic' }}>{placeholder}</span>}
      </Typography>
    );
  }

  return (
    <Stack
      direction="row"
      spacing={1}
      sx={{
        alignItems: multiline ? 'flex-start' : 'center',
        flexWrap: 'wrap',
        width: '100%',
      }}>
      {edit ? (
        <>
          <TextField
            value={tempValue}
            onChange={(e) => handleChange(e.target.value)}
            variant="outlined"
            size="small"
            multiline={multiline}
            rows={multiline ? 3 : 1}
            sx={{ flex: 1, minWidth: '200px' }}
            placeholder={placeholder}
            error={!!error}
            disabled={loading}
            autoFocus={autoFocus}
            slotProps={{
              input: {
                endAdornment: error ? (
                  <Typography color="error" sx={{ whiteSpace: 'nowrap' }}>
                    {error}
                  </Typography>
                ) : undefined,
              },
              htmlInput: {
                maxLength,
              },
            }}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !multiline && !e.shiftKey) {
                e.preventDefault();
                handleSave();
              }
              if (e.key === 'Escape') {
                e.preventDefault();
                handleCancel();
              }
            }}
          />
          <Stack direction="row" spacing={0.5}>
            <IconButton
              onClick={handleSave}
              size="small"
              disabled={!!error || loading}
              color="primary"
              title={t('common.save')}>
              <Check />
            </IconButton>
            <IconButton onClick={handleCancel} size="small" disabled={loading} title={t('common.cancel')}>
              <Close />
            </IconButton>
          </Stack>
        </>
      ) : (
        <>
          <Typography
            variant="body2"
            sx={{
              wordBreak: 'break-word',
              whiteSpace: multiline ? 'pre-wrap' : 'nowrap',
              overflow: multiline ? 'visible' : 'hidden',
              textOverflow: multiline ? 'clip' : 'ellipsis',
            }}>
            {value || <span style={{ color: '#999', fontStyle: 'italic' }}>{placeholder}</span>}
          </Typography>
          <IconButton onClick={handleEdit} size="small" title={t('common.edit')}>
            <EditOutlined fontSize="small" />
          </IconButton>
        </>
      )}
    </Stack>
  );
}
