/**
 * KRA - Personal Center Page
 * User profile display and editing
 */
import React, { useState } from 'react';
import {
  Card,
  Row,
  Col,
  Avatar,
  Button,
  Form,
  Input,
  Modal,
  Tag,
  Timeline,
  Tabs,
  Statistic,
  message,
  Space,
} from 'antd';
import {
  UserOutlined,
  EditOutlined,
  PhoneOutlined,
  MailOutlined,
  LockOutlined,
  EnvironmentOutlined,
  BankOutlined,
  TeamOutlined,
  TrophyOutlined,
  CodeOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { Helmet } from '@umijs/max';
import { useUserStore } from '@/models/user';
import { setSelfInfo, changePassword } from '@/services/kratos/user';
import { createStyles } from 'antd-style';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    minHeight: '100vh',
    background: '#f5f5f5',
  },
  profileCard: {
    borderRadius: '16px',
    overflow: 'hidden',
    marginBottom: '24px',
  },
  coverBg: {
    height: '180px',
    background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    position: 'relative',
  },
  profileInfo: {
    padding: '0 32px 32px',
    marginTop: '-60px',
    position: 'relative',
  },
  avatarWrapper: {
    display: 'inline-block',
    padding: '4px',
    background: '#fff',
    borderRadius: '50%',
    boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
  },
  userName: {
    fontSize: '24px',
    fontWeight: 600,
    marginTop: '16px',
    marginBottom: '8px',
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
  },
  userMeta: {
    display: 'flex',
    flexWrap: 'wrap',
    gap: '24px',
    color: token.colorTextSecondary,
    marginTop: '12px',
  },
  metaItem: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  infoCard: {
    borderRadius: '12px',
    marginBottom: '16px',
  },
  infoTitle: {
    fontSize: '16px',
    fontWeight: 600,
    marginBottom: '16px',
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  infoItem: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '12px 0',
    borderBottom: `1px solid ${token.colorBorderSecondary}`,
    '&:last-child': {
      borderBottom: 'none',
    },
  },
  infoLabel: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    color: token.colorTextSecondary,
  },
  statCard: {
    textAlign: 'center',
    padding: '24px',
    background: '#fafafa',
    borderRadius: '12px',
  },
}));

const PersonPage: React.FC = () => {
  const { styles } = useStyles();
  const { userInfo, setUserInfo } = useUserStore();
  const [editNickName, setEditNickName] = useState(false);
  const [nickName, setNickName] = useState('');
  const [passwordModal, setPasswordModal] = useState(false);
  const [phoneModal, setPhoneModal] = useState(false);
  const [emailModal, setEmailModal] = useState(false);
  const [passwordForm] = Form.useForm();
  const [phoneForm] = Form.useForm();
  const [emailForm] = Form.useForm();

  // 修改昵称
  const handleEditNickName = () => {
    setNickName(userInfo.nickName);
    setEditNickName(true);
  };

  const handleSaveNickName = async () => {
    try {
      const res = await setSelfInfo({ nickName });
      if (res.code === 0) {
        setUserInfo({ nickName });
        message.success('修改成功');
        setEditNickName(false);
      }
    } catch (error) {
      message.error('修改失败');
    }
  };

  // 修改密码
  const handleChangePassword = async () => {
    try {
      const values = await passwordForm.validateFields();
      if (values.newPassword !== values.confirmPassword) {
        message.error('两次密码不一致');
        return;
      }
      const res = await changePassword({
        password: values.password,
        newPassword: values.newPassword,
      });
      if (res.code === 0) {
        message.success('修改密码成功');
        setPasswordModal(false);
        passwordForm.resetFields();
      }
    } catch (error) {
      message.error('修改失败');
    }
  };

  // 修改手机号
  const handleChangePhone = async () => {
    try {
      const values = await phoneForm.validateFields();
      const res = await setSelfInfo({ phone: values.phone });
      if (res.code === 0) {
        setUserInfo({ phone: values.phone });
        message.success('修改成功');
        setPhoneModal(false);
        phoneForm.resetFields();
      }
    } catch (error) {
      message.error('修改失败');
    }
  };

  // 修改邮箱
  const handleChangeEmail = async () => {
    try {
      const values = await emailForm.validateFields();
      const res = await setSelfInfo({ email: values.email });
      if (res.code === 0) {
        setUserInfo({ email: values.email });
        message.success('修改成功');
        setEmailModal(false);
        emailForm.resetFields();
      }
    } catch (error) {
      message.error('修改失败');
    }
  };

  const activities = [
    { time: '2024-01-10', title: '完成项目里程碑', content: '成功完成主要项目开发任务', color: 'blue' },
    { time: '2024-01-11', title: '代码审核完成', content: '完成核心模块代码审核', color: 'green' },
    { time: '2024-01-12', title: '技术分享会', content: '主持团队技术分享会', color: 'orange' },
    { time: '2024-01-13', title: '新功能上线', content: '成功上线用户反馈的新特性', color: 'red' },
  ];

  const tabItems = [
    {
      key: 'stats',
      label: (
        <span>
          <CodeOutlined /> 数据统计
        </span>
      ),
      children: (
        <Row gutter={[16, 16]} style={{ padding: '24px 0' }}>
          <Col xs={12} md={6}>
            <div className={styles.statCard}>
              <Statistic title="项目参与" value={138} styles={{ content: { color: '#1890ff' } }} />
            </div>
          </Col>
          <Col xs={12} md={6}>
            <div className={styles.statCard}>
              <Statistic title="代码提交" value={2300} suffix="+" styles={{ content: { color: '#52c41a' } }} />
            </div>
          </Col>
          <Col xs={12} md={6}>
            <div className={styles.statCard}>
              <Statistic title="任务完成" value={95} suffix="%" styles={{ content: { color: '#722ed1' } }} />
            </div>
          </Col>
          <Col xs={12} md={6}>
            <div className={styles.statCard}>
              <Statistic title="获得勋章" value={12} styles={{ content: { color: '#faad14' } }} />
            </div>
          </Col>
        </Row>
      ),
    },
    {
      key: 'timeline',
      label: (
        <span>
          <ClockCircleOutlined /> 近期动态
        </span>
      ),
      children: (
        <div style={{ padding: '24px 0' }}>
          <Timeline
            items={activities.map((item) => ({
              color: item.color,
              children: (
                <>
                  <p style={{ fontWeight: 500, marginBottom: '4px' }}>{item.title}</p>
                  <p style={{ color: '#999', fontSize: '13px' }}>{item.content}</p>
                  <p style={{ color: '#bbb', fontSize: '12px' }}>{item.time}</p>
                </>
              ),
            }))}
          />
        </div>
      ),
    },
  ];

  return (
    <div className={styles.container}>
      <Helmet>
        <title>个人中心 - Kratos Admin</title>
      </Helmet>

      {/* 顶部个人信息卡片 */}
      <Card className={styles.profileCard} variant="borderless" styles={{ body: { padding: 0 } }}>
        <div className={styles.coverBg} />
        <div className={styles.profileInfo}>
          <div className={styles.avatarWrapper}>
            <Avatar size={100} src={userInfo.headerImg} icon={<UserOutlined />} />
          </div>
          <div className={styles.userName}>
            {editNickName ? (
              <Space>
                <Input
                  value={nickName}
                  onChange={(e) => setNickName(e.target.value)}
                  style={{ width: 200 }}
                />
                <Button type="primary" size="small" onClick={handleSaveNickName}>
                  确认
                </Button>
                <Button size="small" onClick={() => setEditNickName(false)}>
                  取消
                </Button>
              </Space>
            ) : (
              <>
                {userInfo.nickName || '未设置昵称'}
                <EditOutlined
                  style={{ cursor: 'pointer', color: '#999' }}
                  onClick={handleEditNickName}
                />
              </>
            )}
          </div>
          <div className={styles.userMeta}>
            <span className={styles.metaItem}>
              <EnvironmentOutlined /> 中国·北京市
            </span>
            <span className={styles.metaItem}>
              <BankOutlined /> Kratos Admin Team
            </span>
            <span className={styles.metaItem}>
              <TeamOutlined /> 技术部
            </span>
          </div>
        </div>
      </Card>

      <Row gutter={24}>
        {/* 左侧信息栏 */}
        <Col xs={24} lg={8}>
          <Card className={styles.infoCard} variant="borderless">
            <div className={styles.infoTitle}>
              <UserOutlined style={{ color: '#1890ff' }} /> 基本信息
            </div>
            <div className={styles.infoItem}>
              <span className={styles.infoLabel}>
                <PhoneOutlined style={{ color: '#1890ff' }} /> 手机号码
              </span>
              <Space>
                <span>{(userInfo as any).phone || '未设置'}</span>
                <Button type="link" size="small" onClick={() => setPhoneModal(true)}>
                  修改
                </Button>
              </Space>
            </div>
            <div className={styles.infoItem}>
              <span className={styles.infoLabel}>
                <MailOutlined style={{ color: '#52c41a' }} /> 邮箱地址
              </span>
              <Space>
                <span>{(userInfo as any).email || '未设置'}</span>
                <Button type="link" size="small" onClick={() => setEmailModal(true)}>
                  修改
                </Button>
              </Space>
            </div>
            <div className={styles.infoItem}>
              <span className={styles.infoLabel}>
                <LockOutlined style={{ color: '#722ed1' }} /> 账号密码
              </span>
              <Space>
                <span>已设置</span>
                <Button type="link" size="small" onClick={() => setPasswordModal(true)}>
                  修改
                </Button>
              </Space>
            </div>
          </Card>

          <Card className={styles.infoCard} variant="borderless">
            <div className={styles.infoTitle}>
              <TrophyOutlined style={{ color: '#faad14' }} /> 技能特长
            </div>
            <Space wrap>
              <Tag color="success">GoLang</Tag>
              <Tag color="warning">TypeScript</Tag>
              <Tag color="error">React</Tag>
              <Tag color="processing">Kratos</Tag>
            </Space>
          </Card>
        </Col>

        {/* 右侧内容区 */}
        <Col xs={24} lg={16}>
          <Card className={styles.infoCard} variant="borderless">
            <Tabs items={tabItems} />
          </Card>
        </Col>
      </Row>

      {/* 修改密码弹窗 */}
      <Modal
        title="修改密码"
        open={passwordModal}
        onOk={handleChangePassword}
        onCancel={() => {
          setPasswordModal(false);
          passwordForm.resetFields();
        }}
      >
        <Form form={passwordForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="password"
            label="原密码"
            rules={[
              { required: true, message: '请输入原密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="确认密码"
            rules={[
              { required: true, message: '请确认新密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改手机号弹窗 */}
      <Modal
        title="修改手机号"
        open={phoneModal}
        onOk={handleChangePhone}
        onCancel={() => {
          setPhoneModal(false);
          phoneForm.resetFields();
        }}
      >
        <Form form={phoneForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="phone"
            label="手机号"
            rules={[{ required: true, message: '请输入手机号' }]}
          >
            <Input prefix={<PhoneOutlined />} placeholder="请输入新的手机号码" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改邮箱弹窗 */}
      <Modal
        title="修改邮箱"
        open={emailModal}
        onOk={handleChangeEmail}
        onCancel={() => {
          setEmailModal(false);
          emailForm.resetFields();
        }}
      >
        <Form form={emailForm} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input prefix={<MailOutlined />} placeholder="请输入新的邮箱地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PersonPage;
