import {
  CameraOutlined,
  IdcardOutlined,
  LoadingOutlined,
  LockOutlined,
  MailOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { useModel, useIntl } from '@umijs/max';
import { App, Avatar, Button, Form, Input, Spin, Upload } from 'antd';
import type { RcFile, UploadChangeParam } from 'antd/es/upload';
import React, { useState } from 'react';
import { updateProfile, uploadFile } from '@/services/auth/api';
import useStyles from './index.style';

const BaseView: React.FC = () => {
  const { styles, cx } = useStyles();
  const intl = useIntl();
  const { message } = App.useApp();
  const { initialState, setInitialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;

  const [uploading, setUploading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string>(currentUser?.avatar || '');
  const [submitting, setSubmitting] = useState(false);
  const [form] = Form.useForm();

  // Upload validation
  const beforeUpload = (file: RcFile) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error(
        intl.formatMessage({
          id: 'pages.account.settings.avatar.typeError',
          defaultMessage: '只能上传图片文件!',
        }),
      );
      return false;
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error(
        intl.formatMessage({
          id: 'pages.account.settings.avatar.sizeError',
          defaultMessage: '图片大小不能超过 10MB!',
        }),
      );
      return false;
    }
    return true;
  };

  // Handle upload
  const handleUpload = async (info: UploadChangeParam) => {
    const file = info.file.originFileObj;
    if (!file) return;

    setUploading(true);
    try {
      const response = await uploadFile(file);
      if (response.code === 200 && response.data) {
        const newAvatarUrl = response.data.url;
        setAvatarUrl(newAvatarUrl);

        // Auto update profile with new avatar
        const updateResponse = await updateProfile({ avatar: newAvatarUrl });
        if (updateResponse.success) {
          message.success(
            intl.formatMessage({
              id: 'pages.account.settings.avatar.uploadSuccess',
              defaultMessage: '头像上传成功',
            }),
          );
          // Update global user state
          if (initialState) {
            setInitialState({
              ...initialState,
              currentUser: {
                ...initialState.currentUser!,
                avatar: newAvatarUrl,
              },
            });
          }
        } else {
          message.error(
            updateResponse.message ||
              intl.formatMessage({
                id: 'pages.account.settings.avatar.uploadFailed',
                defaultMessage: '头像上传失败',
              }),
          );
        }
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.avatar.uploadFailed',
              defaultMessage: '头像上传失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.avatar.uploadFailed',
            defaultMessage: '头像上传失败',
          }),
      );
    } finally {
      setUploading(false);
    }
  };

  // Get avatar URL
  const getAvatarURL = () => {
    if (avatarUrl) return avatarUrl;
    if (currentUser?.avatar) return currentUser.avatar;
    return 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
  };

  // Submit form
  const handleFinish = async (values: { nickname: string }) => {
    setSubmitting(true);
    try {
      const response = await updateProfile({
        nickname: values.nickname,
        avatar: avatarUrl || undefined,
      });

      if (response.success && response.data) {
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.updateSuccess',
            defaultMessage: '更新基本信息成功',
          }),
        );
        // Update global user state
        if (initialState) {
          setInitialState({
            ...initialState,
            currentUser: {
              ...initialState.currentUser!,
              name: values.nickname,
              avatar: avatarUrl || initialState.currentUser?.avatar,
            },
          });
        }
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.updateFailed',
              defaultMessage: '更新基本信息失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.updateFailed',
            defaultMessage: '更新基本信息失败',
          }),
      );
    } finally {
      setSubmitting(false);
    }
  };

  if (!currentUser) {
    return (
      <div style={{ textAlign: 'center', padding: 40 }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className={styles.baseView}>
      {/* Profile Section */}
      <div className={styles.profileSection}>
        {/* Avatar Upload */}
        <div className={styles.avatarSection}>
          <Upload
            name="file"
            showUploadList={false}
            beforeUpload={beforeUpload}
            onChange={handleUpload}
            customRequest={() => {}}
            accept="image/*"
          >
            <div className={styles.avatarWrapper}>
              <Avatar size={120} src={getAvatarURL()} className={styles.avatar} />
              <div className={cx(styles.avatarOverlay, 'avatar-overlay')}>
                {uploading ? (
                  <LoadingOutlined className={styles.avatarIcon} />
                ) : (
                  <>
                    <CameraOutlined className={styles.avatarIcon} />
                    <span>
                      {intl.formatMessage({
                        id: 'pages.account.settings.avatar.change',
                        defaultMessage: '更换',
                      })}
                    </span>
                  </>
                )}
              </div>
            </div>
          </Upload>
          <div className={styles.avatarHint}>
            {intl.formatMessage({
              id: 'pages.account.settings.avatar.hint',
              defaultMessage: '支持 JPG、PNG 格式，最大 10MB',
            })}
          </div>
        </div>

        {/* Form Section */}
        <div className={styles.formSection}>
          {/* Account Info - Read Only */}
          <div className={styles.sectionTitle}>
            <LockOutlined />
            {intl.formatMessage({
              id: 'pages.account.settings.section.accountInfo',
              defaultMessage: '账户信息',
            })}
          </div>
          <div className={styles.formGrid}>
            <div className={styles.fieldGroup}>
              <div className={styles.fieldLabel}>
                <IdcardOutlined />
                {intl.formatMessage({
                  id: 'pages.account.settings.userId',
                  defaultMessage: '用户ID',
                })}
              </div>
              <div className={styles.fieldValue}>{currentUser.userId}</div>
            </div>

            <div className={styles.fieldGroup}>
              <div className={styles.fieldLabel}>
                <UserOutlined />
                {intl.formatMessage({
                  id: 'pages.account.settings.username',
                  defaultMessage: '用户名',
                })}
              </div>
              <div className={styles.fieldValue}>{currentUser.username}</div>
            </div>

            <div className={styles.fieldGroup}>
              <div className={styles.fieldLabel}>
                <MailOutlined />
                {intl.formatMessage({
                  id: 'pages.account.settings.email',
                  defaultMessage: '邮箱',
                })}
              </div>
              <div className={styles.fieldValue}>{currentUser.email}</div>
              <div className={styles.fieldHint}>
                {intl.formatMessage({
                  id: 'pages.account.settings.email.hint',
                  defaultMessage: '邮箱请在安全设置中修改',
                })}
              </div>
            </div>
          </div>

          {/* Editable Info */}
          <div className={styles.sectionTitle} style={{ marginTop: 32 }}>
            <UserOutlined />
            {intl.formatMessage({
              id: 'pages.account.settings.section.personalInfo',
              defaultMessage: '个人信息',
            })}
          </div>

          <Form
            form={form}
            layout="vertical"
            onFinish={handleFinish}
            initialValues={{
              nickname: currentUser.name,
            }}
          >
            <Form.Item
              name="nickname"
              label={intl.formatMessage({
                id: 'pages.account.settings.nickname',
                defaultMessage: '昵称',
              })}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.nickname.required',
                    defaultMessage: '请输入您的昵称!',
                  }),
                },
                {
                  max: 50,
                  message: intl.formatMessage({
                    id: 'pages.account.settings.nickname.maxLength',
                    defaultMessage: '昵称最长50个字符',
                  }),
                },
              ]}
            >
              <Input
                size="large"
                prefix={<UserOutlined style={{ color: 'rgba(0,0,0,0.25)' }} />}
                placeholder={intl.formatMessage({
                  id: 'pages.account.settings.nickname.placeholder',
                  defaultMessage: '请输入昵称',
                })}
                style={{ borderRadius: 10 }}
              />
            </Form.Item>

            <Form.Item style={{ marginBottom: 0, marginTop: 24 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={submitting}
                className={styles.submitButton}
              >
                {intl.formatMessage({
                  id: 'pages.account.settings.submit',
                  defaultMessage: '保存修改',
                })}
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default BaseView;
