import React, { useState, useRef, forwardRef, useImperativeHandle } from 'react';
import {
  Box,
  TextField,
  Button,
  Avatar,
  Typography,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Grid,
  Paper,
  IconButton,
  Tooltip
} from '@mui/material';
import { PhotoCamera, Edit } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useProfileSetting } from '@/hooks/setting-hooks';
import { useMessage } from '@/hooks/useSnackbar';
import type { IUserInfo } from '@/interfaces/database/user-setting';
import { TimezoneList } from '@/constants/setting';
import { LanguageList, LanguageMap } from '@/constants/common';

// 语言选项
const languageOptions = LanguageList.map(x => ({ value: x, label: LanguageMap[x as keyof typeof LanguageMap] }));

// 时区选项
const timezoneOptions = TimezoneList.map(x => ({ value: x, label: x }));

export interface ProfileFormProps {
  userInfo: IUserInfo | null;
  onSubmit: (data: Partial<IUserInfo>) => Promise<void>;
  showSaveButton?: boolean;
  onSave?: () => void | Promise<void>;
}

export type ProfileFormHandle = {
  submit: () => Promise<void>;
};


/**
 * 个人信息表单
 */
const ProfileFormInner = (
  { userInfo, onSubmit, showSaveButton = true, onSave }: ProfileFormProps,
  ref: React.ForwardedRef<ProfileFormHandle>
) => {
  const { t } = useTranslation();
  const showMessage = useMessage();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [formData, setFormData] = useState<Partial<IUserInfo>>({
    nickname: userInfo?.nickname || '',
    avatar: userInfo?.avatar || null,
    language: userInfo?.language || 'Chinese',
    timezone: userInfo?.timezone || 'UTC+8\tAsia/Shanghai',
    email: userInfo?.email || ''
  });

  // 更新表单数据
  React.useEffect(() => {
    if (userInfo) {
      setFormData({
        nickname: userInfo.nickname || '',
        avatar: userInfo.avatar || null,
        language: userInfo.language || 'Chinese',
        timezone: userInfo.timezone || 'UTC+8\tAsia/Shanghai',
        email: userInfo.email || ''
      });
    }
  }, [userInfo]);

  // 处理输入变化
  const handleInputChange = (field: keyof IUserInfo) => (event: React.ChangeEvent<HTMLInputElement>) => {
    setFormData(prev => ({
      ...prev,
      [field]: event.target.value
    }));
  };

  // 处理选择变化
  const handleSelectChange = (field: keyof IUserInfo) => (event: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: event.target.value
    }));
  };

  // 处理头像上传
  const handleAvatarUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        showMessage.error(t('setting.pleaseSelectImageFile'));
        return;
      }

      // 检查文件大小 (限制为2MB)
      if (file.size > 2 * 1024 * 1024) {
        showMessage.error(t('setting.imageSizeLimit'));
        return;
      }

      // 转换为base64
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64String = e.target?.result as string;
        setFormData(prev => ({
          ...prev,
          avatar: base64String
        }));
      };
      reader.readAsDataURL(file);
    }
  };

  // 触发文件选择
  const triggerFileSelect = () => {
    fileInputRef.current?.click();
  };

  // 保存用户信息
  const handleSave = async () => {
    try {
      if (!formData.nickname?.trim()) {
        showMessage.error(t('setting.usernameRequired'));
        return;
      }

      const updateData: Partial<IUserInfo> = {
        nickname: formData.nickname,
        avatar: formData.avatar,
        language: formData.language,
        timezone: formData.timezone,
        email: formData.email
      };

      await onSubmit(updateData);
      showMessage.success(t('setting.profileUpdateSuccess'));
    } catch (error) {
      console.error('更新用户信息失败:', error);
      showMessage.error(t('setting.updateFailed'));
    }
  };

  // 向父级暴露提交方法
  useImperativeHandle(ref, () => ({
    submit: handleSave,
  }));

  return (
    <Paper elevation={0} sx={{ p: 3, backgroundColor: 'transparent' }}>
      <Typography variant="h6" gutterBottom sx={{ mb: 3, fontWeight: 600 }}>
        {t('setting.personalProfile')}
      </Typography>

      <Grid container spacing={3}>
        {/* 头像部分 */}
        <Grid size={12}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Avatar
              src={formData.avatar}
              sx={{
                width: 80,
                height: 80,
                border: '2px solid',
                borderColor: 'divider'
              }}
            >
              {formData.nickname?.charAt(0)?.toUpperCase()}
            </Avatar>
            <Box>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                {t('setting.avatar')}
              </Typography>
              <Tooltip title={t('setting.uploadAvatar')}>
                <IconButton
                  color="primary"
                  onClick={triggerFileSelect}
                  sx={{
                    border: '1px solid',
                    borderColor: 'primary.main',
                    '&:hover': {
                      backgroundColor: 'primary.main',
                      color: 'white'
                    }
                  }}
                >
                  <PhotoCamera />
                </IconButton>
              </Tooltip>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                onChange={handleAvatarUpload}
                style={{ display: 'none' }}
              />
              <Typography variant="caption" display="block" color="text.secondary" sx={{ mt: 1 }}>
                {t('setting.avatarFormatTip')}
              </Typography>
            </Box>
          </Box>
        </Grid>

        {/* 用户名 */}
        <Grid size={{ xs: 12, sm: 6 }}>
          <TextField
            fullWidth
            label={t('setting.username')}
            value={formData.nickname}
            onChange={handleInputChange('nickname')}
            variant="outlined"
            required
          />
        </Grid>

        {/* 邮箱 (只读) */}
        <Grid size={{ xs: 12, sm: 6 }}>
          <TextField
            fullWidth
            label={t('setting.email')}
            value={formData.email}
            variant="outlined"
            disabled
            helperText={t('setting.emailNotEditable')}
          />
        </Grid>

        {/* 语言 */}
        <Grid size={{ xs: 12, sm: 6 }}>
          <FormControl fullWidth>
            <InputLabel>{t('setting.language')}</InputLabel>
            <Select
              value={formData.language}
              label={t('setting.language')}
              onChange={handleSelectChange('language')}
            >
              {languageOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>

        {/* 时区 */}
        <Grid size={{ xs: 12, sm: 6 }}>
          <FormControl fullWidth>
            <InputLabel>{t('setting.timezone')}</InputLabel>
            <Select
              value={formData.timezone}
              label={t('setting.timezone')}
              onChange={handleSelectChange('timezone')}
            >
              {timezoneOptions.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>

        {/* 保存按钮（可选） */}
        {showSaveButton && (
          <Grid size={12}>
            <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 2 }}>
              <Button
                variant="contained"
                onClick={async () => {
                  if (onSave) {
                    await onSave();
                  } else {
                    await handleSave();
                  }
                }}
                sx={{ minWidth: 120 }}
              >
                {t('setting.save')}
              </Button>
            </Box>
          </Grid>
        )}
      </Grid>
    </Paper>
  );
};

const ProfileForm = forwardRef<ProfileFormHandle, ProfileFormProps>(ProfileFormInner);

ProfileForm.displayName = 'ProfileForm';

export default ProfileForm;