import React, { useState, useEffect, useRef } from "react";
import "./u1.css";
import { useNavigate } from "react-router-dom";
// import { invoke } from "@tauri-apps/api/core";
// import { listen } from "@tauri-apps/api/event";
import idcard from "../../assets/idcard.png";
import semicircle from "../../assets/semicircle.png";
import LongButton from "../../components/LongButton";
import LongButtonLoading from "../../components/LongButtonLoading";
import DecorLine from "../../components/DecorLine";

const U1: React.FC = () => {
  const navigate = useNavigate();

  const [reading, setReading] = useState(false);
  const timerRef = useRef<number | null>(null);

  const handleStart = () => {
    // localStorage.setItem("lastIdCardNo", "31010919571209004X");
    // navigate("/u2");
    if (reading) return; // 避免重复点击
    setReading(true);
    // 启动后端监听；如果启动失败立即恢复 UI 状态
    window.electronAPI.startIdCardListen().catch((e: any) => {
      console.error("start_idcard_listen failed", e);
      window.electronAPI.log("error", `start_idcard_listen failed: ${e}`);
      setReading(false);
    });

    // 6 秒超时恢复
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    timerRef.current = window.setTimeout(() => {
      console.warn("未在 6 秒内读取到身份证信息，恢复初始状态");
      window.electronAPI.log(
        "warn",
        "未在 6 秒内读取到身份证信息，恢复初始状态"
      );
      setReading(false);
      window.electronAPI.stopIdCardListen().catch(() => {});
      timerRef.current = null;
    }, 6000);
  };

  useEffect(() => {
    if (!reading) return;

    // 监听数据
    window.electronAPI.onIdCardData((e: any) => {
      const payload = e.payload;
      // 保存到 localStorage，下一次刷卡时覆盖
      try {
        if (payload?.id_card_no) {
          localStorage.setItem("lastIdCardNo", payload.id_card_no);
        }
      } catch (err) {
        console.warn("localStorage.setItem failed", err);
      }
      console.log("[idcard-data]", payload);
      window.electronAPI.log("info", `[idcard-data] received`);
      window.electronAPI.log(
        "info",
        `Read IDCard success: ${payload.name} ${payload.id_card_no}`
      );
      // 成功：清理定时器，停止监听
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
      window.electronAPI.stopIdCardListen().catch(() => {});
      setReading(false);
      navigate("/u2");
    });

    // 监听错误 (可选)
    window.electronAPI.onIdCardError((e: any) => {
      console.error("[idcard-error]", e.payload);
      window.electronAPI.log("error", `[idcard-error] ${e.payload}`);
      // 发生错误时立即恢复 UI 状态
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
      setReading(false);
      window.electronAPI.stopIdCardListen().catch(() => {});
      alert(`读取身份证失败: ${e.payload}`);
    });

    return () => {
      window.electronAPI.removeIdCardListeners();
    };
  }, [reading, navigate]);

  return (
    <div className="u1-root">
      <span className="u1-title">
        欢迎使用圆和医疗
        <br />
        自助签到系统
      </span>
      <DecorLine />
      <img alt="card reader" src={idcard} />
      <span className="u1-instruction">请放置身份证在读卡区域</span>
      <img className="u1-semicircle" alt="start button" src={semicircle} />
      {!reading && <LongButton text="开始签到" onClick={handleStart} />}
      {reading && <LongButtonLoading text="身份信息读取中..." />}
    </div>
  );
};

export default U1;
