import React from "react";
import "./u4.css";
import { useNavigate } from "react-router-dom";
import { useLocation } from "react-router-dom";
import DecorLine from "../../components/DecorLine";
import LongButton from "../../components/LongButton";
import radio0 from "../../assets/radio-0.png";
import radio1 from "../../assets/radio-1.png";
interface testType {
  id: number;
  title: string;
  desc: string;
  taboo: string;
  exam_id: number;
}

const U4: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const optionalData = (location.state as any)?.optionalData;
  const [test, setTest] = React.useState<testType[]>([]);
  const handleConfirm = () => {
    navigate("/UI6");
  };
  React.useEffect(() => {
    if (
      optionalData &&
      optionalData.listOptionalItem &&
      optionalData.listOptionalItem.length
    ) {
      const items = optionalData.listOptionalItem.map((it: any) => ({
        id: it.combination_code,
        title: it.combination_name,
        desc: "",
        taboo: "",
        exam_id: it.physical_exam_id,
      }));
      setTest(items);
    } else {
      navigate("/UI6");
    }
  }, []);
  const [selectedId, setSelectedId] = React.useState<number | null>(null);

  // 当 test 更新后，如果没有选择项则默认选择第一个
  React.useEffect(() => {
    if (test && test.length && selectedId === null) {
      setSelectedId(test[0].id);
    }
  }, [test]);

  React.useEffect(() => {
    console.log("选择的项目", selectedId);
  }, [selectedId]);
  return (
    <div className="u4-root">
      <span className="u4-title">请确认体检选项</span>
      <DecorLine />

      <div className="u4-card-grid">
        {test.map((t, index) => (
          <div
            key={`${t.id}-${t.exam_id}-${index}`}
            className="u4-card"
            onClick={() => {
              setSelectedId(t.id);
            }}
          >
            <div className="u4-card-header">
              <img
                className={
                  "u4-radio " + (selectedId === t.id ? "selected" : "")
                }
                src={selectedId === t.id ? radio1 : radio0}
                alt={selectedId === t.id ? "已选" : "未选"}
              />
              <div className="u4-card-title">{t.title}</div>
            </div>
          </div>
        ))}
      </div>
      <div className="u4-footer">
        <span className="u4-subtitle">请根据自身状态选择合适的项目</span>

        <div className="u4-confirm-wrapper">
          <LongButton text="确认选择" onClick={handleConfirm} />
        </div>
      </div>
    </div>
  );
};

export default U4;
