import { useEffect, useState } from "react";
import { Button, Image, Input, Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import {
  onboardingComplete,
  onboardingEmail,
  onboardingInterests,
  onboardingProfile,
  onboardingSetPassword,
  onboardingStatus,
  onboardingUploadFile,
  pcQrCompleteOnboarding
} from "../../api/auth";
import { getLabelDictionary } from "../../api/labels";
import { saveLoginTokens } from "../../utils/auth";
import { interestItems, MAX_INTEREST_LABELS, type DictItem } from "../../utils/labels";
import { clearOnboardingSession, getOnboardingPcLoginId, getOnboardingToken } from "../../utils/onboarding";
import { useUserStore } from "../../store/user";
import "./index.scss";

const stepKeys = ["email", "password", "profile", "interests", "complete"];
const stepTitles = ["绑定邮箱", "设置密码", "完善资料", "兴趣选择", "完成注册"];

export default function OnboardingPage() {
  const bootstrap = useUserStore((state) => state.bootstrap);
  const [token, setToken] = useState("");
  const [pcLoginId, setPcLoginId] = useState("");
  const [steps, setSteps] = useState<Record<string, boolean>>({});
  const [stepIndex, setStepIndex] = useState(0);
  const [loading, setLoading] = useState(false);
  const [interestOptions, setInterestOptions] = useState<DictItem[]>([]);
  const [selectedInterestIds, setSelectedInterestIds] = useState<number[]>([]);
  const [form, setForm] = useState({
    email: "",
    password: "",
    passwordConfirm: "",
    realName: "",
    unit: "",
    position: "",
    avatarUrl: ""
  });

  useEffect(() => {
    const storedToken = getOnboardingToken();
    const storedPcLoginId = getOnboardingPcLoginId();
    setToken(storedToken);
    setPcLoginId(storedPcLoginId);
    if (!storedToken) {
      Taro.redirectTo({ url: "/pages/login/index" });
      return;
    }
    void load(storedToken);
  }, []);

  const allDone = Boolean(steps.email && steps.password && (steps.profile || steps.basicProfile));

  async function load(activeToken = token) {
    try {
      const [data, dict]: any[] = await Promise.all([
        onboardingStatus(activeToken),
        getLabelDictionary().catch(() => null)
      ]);
      const next = data?.steps || {};
      const profile = data?.profile || {};
      setSteps(next);
      setStepIndex(firstIncomplete(next));
      setInterestOptions(interestItems(dict));
      setForm((prev) => ({
        ...prev,
        email: firstNonBlank(profile.email, prev.email),
        realName: firstNonBlank(profile.realName, profile.real_name, profile.displayName, profile.name, prev.realName),
        unit: firstNonBlank(profile.unit, prev.unit),
        position: firstNonBlank(profile.position, prev.position),
        avatarUrl: firstNonBlank(profile.avatarUrl, profile.avatar_url, profile.avatar, prev.avatarUrl)
      }));
    } catch {
      clearOnboardingSession();
      Taro.showToast({ title: "注册补全已失效，请重新登录", icon: "none" });
      await Taro.redirectTo({ url: "/pages/login/index" });
    }
  }

  async function run(action: () => Promise<any>, success: string) {
    if (!token || loading) return;
    setLoading(true);
    try {
      const data = await action();
      if (data?.steps) {
        setSteps(data.steps);
        setStepIndex(firstIncomplete(data.steps));
      }
      Taro.showToast({ title: success, icon: "none" });
    } finally {
      setLoading(false);
    }
  }

  async function finish() {
    if (!token || !allDone || loading) return;
    setLoading(true);
    try {
      const data: any = pcLoginId
        ? await pcQrCompleteOnboarding(pcLoginId, token)
        : await onboardingComplete(token);
      if (data?.accessToken) {
        saveLoginTokens({ accessToken: data.accessToken, refreshToken: data.refreshToken });
        clearOnboardingSession();
        await bootstrap();
        Taro.showToast({ title: "注册完成", icon: "none" });
        await Taro.reLaunch({ url: "/pages/home/index" });
      }
    } finally {
      setLoading(false);
    }
  }

  function setField(key: string, value: string) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  function toggleInterest(id: number) {
    setSelectedInterestIds((prev) => {
      if (prev.includes(id)) return prev.filter((item) => item !== id);
      if (prev.length >= MAX_INTEREST_LABELS) {
        Taro.showToast({ title: `最多选择${MAX_INTEREST_LABELS}个`, icon: "none" });
        return prev;
      }
      return [...prev, id];
    });
  }

  async function uploadAvatar() {
    if (!token || loading) return;
    try {
      const picked = await Taro.chooseImage({ count: 1, sizeType: ["compressed"], sourceType: ["album", "camera"] });
      const filePath = picked.tempFilePaths?.[0] || "";
      if (!filePath) return;
      setLoading(true);
      Taro.showLoading({ title: "上传中..." });
      const uploaded = await onboardingUploadFile(token, filePath, "file", {
        visibility: "public",
        businessType: "user_avatar"
      });
      const url = firstNonBlank(uploaded?.url, uploaded?.publicUrl, uploaded?.public_url);
      if (!url) {
        Taro.showToast({ title: "头像上传失败", icon: "none" });
        return;
      }
      setForm((prev) => ({ ...prev, avatarUrl: url }));
      Taro.showToast({ title: "头像已上传", icon: "none" });
    } catch (e: any) {
      if (!String(e?.errMsg || "").includes("cancel")) {
        Taro.showToast({ title: e?.message || "头像上传失败", icon: "none" });
      }
    } finally {
      Taro.hideLoading();
      setLoading(false);
    }
  }

  async function saveInterests() {
    await run(() => onboardingInterests(token, selectedInterestIds), selectedInterestIds.length ? "兴趣已保存" : "已跳过");
  }

  return (
    <View className="onboarding-page">
      <View className="onboarding-page__header">
        <Text className="onboarding-page__title">注册补全</Text>
        <Text className="onboarding-page__desc">请按步骤完成邮箱、密码和基础资料，兴趣可跳过。</Text>
      </View>

      <View className="onboarding-steps">
        {stepTitles.map((title, index) => {
          const key = stepKeys[index];
          const optional = key === "interests";
          const done = key === "complete" ? allDone : !!steps[key] || (key === "profile" && !!steps.basicProfile) || optional;
          return (
            <View key={key} className={`onboarding-steps__item ${stepIndex === index ? "is-active" : ""} ${done ? "is-done" : ""}`} onClick={() => setStepIndex(index)}>
              <Text>{index + 1}</Text>
              <Text>{title}</Text>
            </View>
          );
        })}
      </View>

      <View className="onboarding-card">
        <Text className="onboarding-card__title">{stepTitles[stepIndex]}</Text>
        {renderStep()}
      </View>

      <View className="onboarding-actions">
        <Button disabled={stepIndex === 0 || loading} onClick={() => setStepIndex((value) => Math.max(0, value - 1))}>上一步</Button>
        {stepIndex < stepKeys.length - 1 ? (
          <Button type="primary" disabled={loading} onClick={() => setStepIndex((value) => Math.min(stepKeys.length - 1, value + 1))}>下一步</Button>
        ) : (
          <Button type="primary" loading={loading} disabled={!allDone} onClick={finish}>完成注册</Button>
        )}
      </View>
    </View>
  );

  function renderStep() {
    if (stepIndex === 0) {
      return (
        <View className="onboarding-form">
          <Input value={form.email} placeholder="邮箱地址" onInput={(e) => setField("email", e.detail.value)} />
          <Button type="primary" disabled={loading || !emailPattern.test(form.email.trim())} onClick={() => run(() => onboardingEmail(token, form.email.trim()), "邮箱已绑定")}>绑定邮箱</Button>
        </View>
      );
    }
    if (stepIndex === 1) {
      return (
        <View className="onboarding-form">
          <Input value={form.password} password placeholder="密码，至少8位含字母和数字" onInput={(e) => setField("password", e.detail.value)} />
          <Input value={form.passwordConfirm} password placeholder="确认密码" onInput={(e) => setField("passwordConfirm", e.detail.value)} />
          <Button type="primary" disabled={loading || form.password.length < 8 || form.password !== form.passwordConfirm} onClick={() => run(() => onboardingSetPassword(token, form.password), "密码已设置")}>保存密码</Button>
        </View>
      );
    }
    if (stepIndex === 2) {
      return (
        <View className="onboarding-form">
          <Input value={form.realName} placeholder="真实姓名" onInput={(e) => setField("realName", e.detail.value)} />
          <Input value={form.unit} placeholder="所在单位" onInput={(e) => setField("unit", e.detail.value)} />
          <Input value={form.position} placeholder="职务" onInput={(e) => setField("position", e.detail.value)} />
          <View className="onboarding-avatar" onClick={() => void uploadAvatar()}>
            {form.avatarUrl ? (
              <Image className="onboarding-avatar__image" src={form.avatarUrl} mode="aspectFill" />
            ) : (
              <View className="onboarding-avatar__empty">
                <Text className="onboarding-avatar__plus">+</Text>
              </View>
            )}
            <View className="onboarding-avatar__copy">
              <Text className="onboarding-avatar__title">{form.avatarUrl ? "更换头像" : "上传头像"}</Text>
              <Text className="onboarding-avatar__hint">头像为注册基础资料必填项</Text>
            </View>
          </View>
          <Button
            type="primary"
            disabled={loading || !form.realName || !form.unit || !form.position || !form.avatarUrl}
            onClick={() => run(() => onboardingProfile(token, { realName: form.realName, unit: form.unit, position: form.position, avatarUrl: form.avatarUrl }), "资料已保存")}
          >
            保存资料
          </Button>
        </View>
      );
    }
    if (stepIndex === 3) {
      return (
        <View className="onboarding-form">
          <Text className="onboarding-interest-count">已选 {selectedInterestIds.length}/{MAX_INTEREST_LABELS}</Text>
          <View className="onboarding-interest-cloud">
            {interestOptions.map((item) => (
              <View key={item.id} className={`onboarding-interest-pill ${selectedInterestIds.includes(item.id) ? "is-active" : ""}`} onClick={() => toggleInterest(item.id)}>
                <Text>{item.name}</Text>
              </View>
            ))}
            {!interestOptions.length ? <Text className="onboarding-interest-empty">暂无兴趣选项，可直接跳过。</Text> : null}
          </View>
          <Button type="primary" disabled={loading} onClick={() => void saveInterests()}>{selectedInterestIds.length ? "保存兴趣" : "跳过兴趣"}</Button>
        </View>
      );
    }
    return (
      <View className="onboarding-summary">
        {["email", "password", "profile", "interests"].map((key, index) => {
          const optional = key === "interests";
          return (
            <View key={key} className="onboarding-summary__row">
              <Text>{stepTitles[index]}</Text>
              <Text className={steps[key] || (key === "profile" && steps.basicProfile) || optional ? "is-done" : ""}>{steps[key] || (key === "profile" && steps.basicProfile) ? "已完成" : optional ? "可跳过" : "未完成"}</Text>
            </View>
          );
        })}
      </View>
    );
  }
}

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function firstIncomplete(steps: Record<string, boolean>) {
  if (!steps.email) return 0;
  if (!steps.password) return 1;
  if (!steps.profile && !steps.basicProfile) return 2;
  if (!steps.interests) return 3;
  return 4;
}

function firstNonBlank(...values: any[]) {
  const value = values.find((item) => item !== undefined && item !== null && String(item).trim() !== "");
  return value === undefined || value === null ? "" : String(value).trim();
}
