import { useEffect, useState } from 'react';
import { Button, Form, Input, Message } from '@arco-design/web-react';
import { useNavigate } from 'react-router-dom';
import { authApi } from '../api';
import { Panel } from '../components/Panel';
import { ProfileInfoList } from './components/ProfileInfoList';
import { ProfileSummary } from './components/ProfileSummary';
import type { AdminProfile, ChangePasswordFormValues, ProfileFormValues } from './interface';

function ProfilePage() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [changingPassword, setChangingPassword] = useState(false);
  const [profile, setProfile] = useState<AdminProfile | null>(null);

  const loadProfile = async () => {
    setLoading(true);
    try {
      const data = await authApi.getProfile();
      setProfile(data);
      form.setFieldsValue({
        nickname: data.nickname,
        email: data.email,
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void loadProfile();
  }, []);

  const updateProfile = async (values: ProfileFormValues) => {
    setSaving(true);
    try {
      const data = await authApi.updateProfile(values);
      setProfile(data);
      Message.success('个人信息已更新');
    } finally {
      setSaving(false);
    }
  };

  const changePassword = async (values: ChangePasswordFormValues) => {
    if (values.newPassword !== values.confirmPassword) {
      Message.error('两次输入的新密码不一致');
      return;
    }
    setChangingPassword(true);
    try {
      await authApi.changePassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword,
      });
      Message.success('密码修改成功，请重新登录');
      passwordForm.resetFields();
      authApi.clearAuthToken();
      navigate('/login', { replace: true });
    } finally {
      setChangingPassword(false);
    }
  };

  return (
    <div className="page-stack">
      <div className="grid items-start gap-5 min-[901px]:grid-cols-[minmax(0,1fr)_420px]">
        <Panel title="个人中心" className="min-[901px]:row-span-2">
          {loading ? (
            <div className="py-12 text-center text-muted">加载中...</div>
          ) : (
            <>
              <ProfileSummary profile={profile} />
              <ProfileInfoList profile={profile} />
            </>
          )}
        </Panel>
        <Panel title="修改个人信息">
          <Form form={form} layout="vertical" onSubmit={updateProfile}>
            <Form.Item label="姓名" field="nickname">
              <Input placeholder="请输入姓名" />
            </Form.Item>
            <Form.Item label="邮箱" field="email" rules={[{ type: 'email', message: '请输入正确的邮箱地址' }]}>
              <Input placeholder="请输入邮箱" />
            </Form.Item>
            <Button type="primary" htmlType="submit" loading={saving}>保存修改</Button>
          </Form>
        </Panel>
        <Panel title="修改密码">
          <Form form={passwordForm} layout="vertical" onSubmit={changePassword}>
            <Form.Item label="旧密码" field="oldPassword" rules={[{ required: true }]}>
              <Input.Password placeholder="请输入旧密码" />
            </Form.Item>
            <Form.Item label="新密码" field="newPassword" rules={[{ required: true }, { minLength: 6, message: '新密码至少 6 位' }]}>
              <Input.Password placeholder="请输入新密码" />
            </Form.Item>
            <Form.Item label="确认新密码" field="confirmPassword" rules={[{ required: true }]}>
              <Input.Password placeholder="请再次输入新密码" />
            </Form.Item>
            <Button type="primary" htmlType="submit" loading={changingPassword}>确认修改</Button>
          </Form>
        </Panel>
      </div>
    </div>
  );
}

export default ProfilePage;
