import React, { useEffect, useState } from "react";
import "./u2.css";
import { useNavigate } from "react-router-dom";
import DecorLine from "../../components/DecorLine";
import avatar from "../../assets/avatar.png";
import semicircle from "../../assets/semicircle.png";
import BackButton from "../../components/BackButton";
import ConfirmButton from "../../components/ConfirmButton";
import { getPatientInfo, getVipStatus, PatientInfo } from "../../api/hisApi";

const U2: React.FC = () => {
  const navigate = useNavigate();
  // 不再通过路由传参，直接从 localStorage 读取上次保存的身份证号
  const idCardNo = localStorage.getItem("lastIdCardNo");
  const [patientInfo, setPatientInfo] = useState<PatientInfo | null>(null);
  const [loading, setLoading] = useState(false);
  const [isVip, setIsVip] = useState<number | null>(null);
  const vipCalledRef = React.useRef(false);

  useEffect(() => {
    if (idCardNo) {
      setLoading(true);
      getPatientInfo(idCardNo)
        .then((res) => {
          if (res.Status === 200) {
            setPatientInfo(res.Data);
          } else {
            alert(`获取用户信息失败: ${res.Message}`);
          }
        })
        .catch((err) => {
          console.error(err);
          alert("获取用户信息出错，请重试");
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [idCardNo]);

  // 获取 VIP 状态，避免重复请求（用 ref 保护）
  useEffect(() => {
    if (!idCardNo) return;
    if (vipCalledRef.current) return;
    vipCalledRef.current = true;
    getVipStatus(idCardNo)
      .then((res) => {
        if (res.Status === 200) {
          setIsVip(res.Data?.is_vip ?? 0);
        } else {
          console.warn("获取 VIP 状态失败:", res.Message);
          setIsVip(0);
        }
      })
      .catch((err) => {
        console.error("getVipStatus error", err);
        setIsVip(0);
      });
  }, [idCardNo]);

  const handleBack = () => {
    navigate(-1);
  };

  const handleConfirm = () => {
    // 判断是否为 VIP 客户（0 否，1 是）
    if (isVip === 1) {
      navigate("/u3");
      return;
    } else {
      // 是否套餐待定
      const isPackageUndecided = false; // 这里可以替换为实际的判断逻辑
      if (isPackageUndecided) {
        navigate("/u4");
      } else {
        navigate("/u5");
      }
    }
  };

  return (
    <div className="u2-root">
      <span className="u2-title">尊敬的张先生/女士，欢迎您的到来：</span>
      <DecorLine />
      <div className="u2-info-card">
        <img className="u2-avatar" src={avatar} alt="avatar" />
        <div className="u2-details-list">
          <div className="u2-detail-row">
            <div className="u2-detail-bar" />
            <div className="u2-detail-text">
              姓名：{loading ? "" : patientInfo?.name || "---"}
            </div>
          </div>

          <div className="u2-detail-row">
            <div className="u2-detail-bar" />
            <div className="u2-detail-text">
              性别：{loading ? "" : patientInfo?.gender_name || "---"}
            </div>
          </div>

          <div className="u2-detail-row">
            <div className="u2-detail-bar" />
            <div className="u2-detail-text">
              年龄：{loading ? "" : patientInfo?.age || "---"}
            </div>
          </div>

          <div className="u2-detail-row">
            <div className="u2-detail-bar" />
            <div className="u2-detail-text">
              证件号：{idCardNo || patientInfo?.IdCard || "---"}
            </div>
          </div>

          <div className="u2-detail-row">
            <div className="u2-detail-bar" />
            <div className="u2-detail-text">
              手机号：{loading ? "" : patientInfo?.phone || "---"}
            </div>
          </div>

          <div className="u2-detail-row">
            <div className="u2-detail-bar" />
            <div className="u2-detail-text">
              婚姻状况：{loading ? "" : patientInfo?.marital_name || "---"}
            </div>
          </div>
        </div>
      </div>
      <span className="u2-instruction">
        <span className="u2-asterisk">*</span> 如信息有误，请联系前台
      </span>
      <img className="u2-semicircle" alt="start button" src={semicircle} />
      <div className="u2-confirm-section">
        <BackButton text="返回" onClick={handleBack} />
        <ConfirmButton text="确认" onClick={handleConfirm} />
      </div>
    </div>
  );
};

export default U2;
