import { Button, Card, Form, Input, Layout, Typography, message } from "antd";
import { LockOutlined, LogoutOutlined } from "@ant-design/icons";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { getCurrentUser, updateMyPassword } from "@/api";

const { Title, Text } = Typography;

type ResetPasswordFormValues = {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
};

export default function ResetPassword() {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm<ResetPasswordFormValues>();

  const goToLogin = () => {
    localStorage.removeItem("accessToken");
    localStorage.removeItem("refreshToken");
    localStorage.removeItem("displayName");
    localStorage.removeItem("username");
    localStorage.removeItem("availableTenants");
    localStorage.removeItem("activeTenantId");
    sessionStorage.removeItem("userProfile");
    navigate("/login", { replace: true });
  };

  const onFinish = async (values: ResetPasswordFormValues) => {
    setLoading(true);
    try {
      await updateMyPassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword
      });
      const profile = await getCurrentUser();
      sessionStorage.setItem("userProfile", JSON.stringify(profile));
      window.dispatchEvent(new Event("user-profile-updated"));
      message.success("密码已更新");
      navigate("/", { replace: true });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout style={{ minHeight: "100vh", background: "#f0f2f5", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <Card style={{ width: 420, borderRadius: 8, boxShadow: "0 4px 12px rgba(0,0,0,0.1)" }}>
        <div className="text-center mb-6">
          <LockOutlined style={{ fontSize: 40, color: "#1890ff" }} />
          <Title level={3} style={{ marginTop: 16 }}>
            首次登录请修改密码
          </Title>
          <Text type="secondary">当前账号需要先更新初始密码，提交成功后会直接进入系统。</Text>
        </div>

        <Form form={form} layout="vertical" onFinish={onFinish}>
          <Form.Item label="当前密码" name="oldPassword" rules={[{ required: true, message: "请输入当前密码" }]}>
            <Input.Password prefix={<LockOutlined />} />
          </Form.Item>

          <Form.Item label="新密码" name="newPassword" rules={[{ required: true, min: 6, message: "新密码至少 6 位" }]}>
            <Input.Password prefix={<LockOutlined />} />
          </Form.Item>

          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={["newPassword"]}
            rules={[
              { required: true, message: "请再次输入新密码" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("newPassword") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("两次输入的新密码不一致"));
                }
              })
            ]}
          >
            <Input.Password prefix={<LockOutlined />} />
          </Form.Item>

          <Button type="primary" htmlType="submit" block size="large" loading={loading} style={{ marginTop: 8 }}>
            提交并保持登录
          </Button>

          <Button type="link" block icon={<LogoutOutlined />} onClick={goToLogin} style={{ marginTop: 8 }}>
            退出登录
          </Button>
        </Form>
      </Card>
    </Layout>
  );
}
