import React, { useState } from 'react';
import { useCreation, useMemoizedFn } from 'ahooks';
import { Box, TextField, Typography, Tooltip, type TooltipProps, useTheme } from '@mui/material';
import { Verified as VerifiedIcon } from '@mui/icons-material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { mergeSx } from '@arcblock/ux/lib/Util/style';
import { translations } from '../libs/locales';

interface EditableFieldProps {
  value: string;
  onChange?: (value: string) => void;
  onValueValidate?: (value: string) => void;
  editable?: boolean;
  disabled?: boolean;
  component?: 'input' | 'textarea';
  placeholder?: string;
  rows?: number;
  maxLength?: number; // 最大字符数
  icon?: React.ReactNode;
  label?: string | React.ReactNode;
  children?: React.ReactNode;
  tooltip?: TooltipProps['title'];
  inline?: boolean;
  style?: React.CSSProperties;
  verified?: boolean;
  errorMsg?: string;
  canEdit?: boolean;
  hidePreview?: boolean;
  renderValue?: (value: string) => React.ReactNode;
}

/** only for sx */
export const commonInputStyle = {
  '.MuiOutlinedInput-root': {
    '&:hover': {
      fieldset: {
        borderColor: 'divider',
      },
    },
    '&.Mui-focused': {
      fieldset: {
        borderColor: 'divider',
      },
    },
  },
};

/** only for sx */
export const inputFieldStyle = {
  width: '100%',
  '& .MuiFormHelperText-root': {
    position: 'relative',
    bottom: 0,
    left: 0,
    margin: 0,
  },
  fieldset: {
    borderColor: 'divider',
  },
};

function EditableField({
  value,
  onChange = () => {},
  onValueValidate = () => {},
  errorMsg = '',
  editable = false,
  component = 'input',
  placeholder = '',
  rows = 2,
  maxLength = undefined,
  icon = undefined,
  label = '',
  children = undefined,
  tooltip = undefined,
  inline = true,
  style = {},
  verified = false,
  canEdit = true,
  renderValue = undefined,
  disabled = false,
  hidePreview = false,
}: EditableFieldProps) {
  const { locale } = useLocaleContext();
  const theme = useTheme();
  const isDark = theme.palette.mode === 'dark';
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  // 存储鼠标位置的状态
  const [mousePosition, setMousePosition] = useState<{
    mouseX: number;
    mouseY: number;
  } | null>(null);

  // 处理鼠标移动事件，更新鼠标位置
  const handleMouseEnter = (event: React.MouseEvent<HTMLElement>) => {
    setMousePosition({
      mouseX: event.clientX,
      mouseY: event.clientY,
    });
  };

  // 处理鼠标离开事件，清除鼠标位置
  const handleMouseLeave = () => {
    setMousePosition(null);
  };

  const handleChange = useMemoizedFn((v: string) => {
    if (onChange) {
      onChange(v);
    }
    if (onValueValidate) {
      onValueValidate(v);
    }
  });

  const content = useCreation(() => {
    if (children) {
      return children;
    }
    if (component === 'input') {
      return (
        <TextField
          variant="outlined"
          className="editable-field"
          value={value}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleChange(e.target.value)}
          sx={mergeSx(inputFieldStyle, !errorMsg ? commonInputStyle : {})}
          error={Boolean(errorMsg)}
          helperText={errorMsg}
          disabled={disabled}
          slotProps={{
            input: {
              sx: { backgroundColor: 'transparent' },
              placeholder,
            },
          }}
        />
      );
    }

    const isTooLong = value.length > (maxLength || 300);
    return (
      <Box position="relative">
        <TextField
          variant="outlined"
          sx={mergeSx(inputFieldStyle, !errorMsg ? commonInputStyle : {})}
          value={value}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleChange(e.target.value)}
          error={Boolean(errorMsg)}
          helperText={errorMsg}
          disabled={disabled}
          slotProps={{
            input: {
              multiline: true,
              minRows: rows,
              placeholder,
            },
          }}
        />
        {maxLength && maxLength > 0 ? (
          <Typography
            position="absolute"
            bottom={-22}
            right={2}
            variant="caption"
            fontSize="12px"
            component="span"
            color={isTooLong ? 'error' : 'text.secondary'}>
            {isTooLong ? `(${t('profile.maxInputLength')} ${maxLength}) ` : ''}
            {value.length} / {maxLength}
          </Typography>
        ) : null}
      </Box>
    );
  }, [value, handleChange, component, placeholder, rows, children]);

  if (!canEdit && editable) {
    return null;
  }

  if (!editable) {
    return value && !hidePreview ? (
      <Tooltip
        open={Boolean(mousePosition)}
        title={tooltip}
        placement="top"
        arrow
        slotProps={{
          popper: {
            // 使用虚拟锚点元素，基于鼠标位置
            anchorEl: mousePosition
              ? {
                  getBoundingClientRect: () => ({
                    top: mousePosition.mouseY,
                    left: mousePosition.mouseX,
                    right: mousePosition.mouseX,
                    bottom: mousePosition.mouseY,
                    width: 0,
                    height: 0,
                    x: mousePosition.mouseX,
                    y: mousePosition.mouseY,
                    toJSON: () => {},
                  }),
                }
              : null,
            // 设置偏移，使tooltip显示在鼠标上方
            modifiers: [
              {
                name: 'offset',
                options: {
                  offset: [0, 10],
                },
              },
            ],
          },
        }}>
        <Typography
          variant="subtitle1"
          component="div"
          gutterBottom
          sx={{
            width: '100%',
            mb: 0,
            lineHeight: 1.4,
            overflow: 'hidden',
          }}
          display="flex"
          alignItems="center"
          gap={1}>
          {icon
            ? React.cloneElement(icon as React.ReactElement<any>, {
                style: {
                  filter: isDark ? 'brightness(0) saturate(100%) invert(1)' : 'none',
                },
              })
            : null}
          <Box display="flex" flexDirection="row" alignItems="center" width="90%">
            <Typography
              sx={{
                whiteSpace: 'pre-wrap',
                ...(inline ? { whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } : {}),
              }}
              component="div"
              onMouseEnter={handleMouseEnter}
              onMouseLeave={handleMouseLeave}>
              {renderValue ? renderValue(value) : value}
            </Typography>
            {verified && (
              <VerifiedIcon color="success" style={{ fontSize: 16, width: 16, marginLeft: 4, flexShrink: 0 }} />
            )}
          </Box>
        </Typography>
      </Tooltip>
    ) : null;
  }

  return (
    <Box sx={{ width: '100%' }} style={style}>
      {label && (
        <Typography variant="subtitle1" gutterBottom sx={{ mb: 0.5, fontSize: '12px', color: 'text.primary' }}>
          {label}
        </Typography>
      )}
      {content}
    </Box>
  );
}

export default EditableField;
