import { Button, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getMyPassport } from "../../api/me";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import "./index.scss";

export default function PassportPage() {
  useAuthGuard();
  useMemberGuard("新联会通行证仅面向正式会员开放");

  const [passport, setPassport] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      const data = await getMyPassport();
      setPassport(data || null);
      setError("");
    } catch (e: any) {
      setError(e?.message || "通行证加载失败");
    } finally {
      setLoading(false);
    }
  };

  useDidShow(() => {
    void load();
  });

  const passportId = String(passport?.passportId || passport?.passport_id || "");
  const qrText = String(passport?.qrText || passport?.webUrl || passport?.miniPath || passportId);

  const copy = async (text: string) => {
    if (!text) return;
    await Taro.setClipboardData({ data: text });
  };

  const scan = async () => {
    try {
      const result = await Taro.scanCode({ onlyFromCamera: false });
      const raw = String(result?.result || "");
      if (!raw) return;
      await Taro.navigateTo({ url: `/pages/passport-detail/index?passportId=${encodeURIComponent(raw)}` });
    } catch {
      // User cancelled scan.
    }
  };

  return (
    <View className="passport-page">
      <View className="passport-page__body">
        {error ? <Text className="passport-state is-error">{error}</Text> : null}
        {loading ? <Text className="passport-state">加载中...</Text> : null}
        <View className="passport-card">
          <Text className="passport-card__label">新联会通行证</Text>
          <Text className="passport-card__id">{passportId || "-"}</Text>
          <Text className="passport-card__hint">活动签到、会员互加好友和身份识别均使用同一通行证。</Text>
          <View className="passport-code">
            <Text>{qrText || "暂无通行证内容"}</Text>
          </View>
          <View className="passport-actions">
            <Button className="passport-btn passport-btn--ghost" onClick={() => void copy(qrText)}>复制</Button>
            <Button className="passport-btn" onClick={() => void scan()}>扫码添加</Button>
          </View>
        </View>
        {passportId ? (
          <View className="passport-link" onClick={() => Taro.navigateTo({ url: `/pages/passport-detail/index?passportId=${encodeURIComponent(passportId)}` })}>
            <Text>预览我的通行证名片</Text>
          </View>
        ) : null}
      </View>
    </View>
  );
}
