import { Button, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getLabelDictionary, getMyLabels, saveMyLabels } from "../../api/labels";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import {
  dedupe,
  interestItems,
  MAX_INTEREST_LABELS,
  professionalCategories,
  selectedCustomLabels as selectedCustomLabelsOf,
  selectedInterestIds as selectedInterestIdsOf,
  selectedProfessionalIds
} from "../../utils/labels";
import "./index.scss";

type DictItem = { id: number; name: string; code?: string };
type DictCategory = { id: number; name: string; code?: string; items: DictItem[] };

type ProfessionalPayload = {
  selectedItemIds: number[];
  selectedCustomLabels: string[];
};

export default function TagSelectPage() {
  useAuthGuard();
  const [categories, setCategories] = useState<DictCategory[]>([]);
  const [interestTags, setInterestTags] = useState<DictItem[]>([]);
  const [selectedInterestIds, setSelectedInterestIds] = useState<number[]>([]);
  const [selectedItemIds, setSelectedItemIds] = useState<number[]>([]);
  const [selectedCustomLabels, setSelectedCustomLabels] = useState<string[]>([]);
  const [saving, setSaving] = useState(false);

  useDidShow(() => {
    void (async () => {
      try {
        const [dict, mine] = await Promise.all([getLabelDictionary(), getMyLabels()]);
        const cats = professionalCategories(dict);
        setCategories(cats);
        setInterestTags(interestItems(dict));

        setSelectedInterestIds(selectedInterestIdsOf(mine));
        setSelectedItemIds(selectedProfessionalIds(mine));
        setSelectedCustomLabels(dedupe(selectedCustomLabelsOf(mine)));
      } catch (e: any) {
        Taro.showToast({ title: e?.message || "标签加载失败", icon: "none" });
      }
    })();
  });

  const professionalNames = useMemo(() => {
    const map = new Map<number, string>();
    categories.forEach((cat) => cat.items.forEach((item) => map.set(item.id, item.name)));
    const fromDict = selectedItemIds.map((id) => map.get(id) || "").filter(Boolean);
    return dedupe([...fromDict, ...selectedCustomLabels]);
  }, [categories, selectedItemIds, selectedCustomLabels]);

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

  const openProfessionalPage = async () => {
    const draftKey = `tag_prof_draft_${Date.now()}`;
    Taro.setStorageSync(draftKey, {
      categories,
      selectedItemIds,
      selectedCustomLabels
    });
    await Taro.navigateTo({
      url: `/pages/tag-professional/index?draftKey=${encodeURIComponent(draftKey)}`,
      success: (res) => {
        res.eventChannel.on("professionalSelectionSaved", (payload: ProfessionalPayload) => {
          setSelectedItemIds(Array.isArray(payload?.selectedItemIds) ? payload.selectedItemIds : []);
          setSelectedCustomLabels(Array.isArray(payload?.selectedCustomLabels) ? dedupe(payload.selectedCustomLabels) : []);
        });
      }
    });
  };

  const onSaveAll = async () => {
    if (saving) return;
    setSaving(true);
    try {
      await saveMyLabels(selectedInterestIds, [], "interest");
      await saveMyLabels(selectedItemIds, dedupe(selectedCustomLabels), "professional");
      Taro.showToast({ title: "保存成功", icon: "success" });
      setTimeout(() => {
        Taro.navigateBack();
      }, 300);
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "保存失败", icon: "none" });
    } finally {
      setSaving(false);
    }
  };

  return (
    <View className="page-shell tag-select-page">
      <View className="page-body">
        <Text className="tag-select-title">选择标签</Text>

        <View className="tag-section">
          <Text className="tag-section__title">请选择兴趣标签（{selectedInterestIds.length}/{MAX_INTEREST_LABELS}）</Text>
          <View className="tag-cloud">
            {interestTags.map((item) => (
              <View key={item.id} className={`tag-pill ${selectedInterestIds.includes(item.id) ? "tag-pill--active" : ""}`} onClick={() => toggleInterest(item.id)}>
                <Text>{item.name}</Text>
              </View>
            ))}
            {!interestTags.length ? <Text className="tag-selected-preview__empty">暂无兴趣选项</Text> : null}
          </View>
        </View>

        <View className="tag-section">
          <Text className="tag-section__title tag-section__title--spaced">请选择专业标签</Text>
          <View className="tag-prof-entry" onClick={() => void openProfessionalPage()}>
            <View className="tag-prof-entry__left">
              <Text className="tag-prof-entry__label">专业标签</Text>
              <Text className="tag-prof-entry__hint">{professionalNames.length > 0 ? `已选 ${professionalNames.length} 项` : "请选择"}</Text>
            </View>
            <Text className="tag-prof-entry__arrow">&gt;</Text>
          </View>
          <View className="tag-selected-preview">
            {professionalNames.length > 0 ? (
              professionalNames.slice(0, 12).map((name) => (
                <Text key={name} className="tag-selected-preview__pill">
                  {name}
                </Text>
              ))
            ) : (
              <Text className="tag-selected-preview__empty">暂无专业标签</Text>
            )}
          </View>
        </View>
      </View>

      <View className="tag-select-bottom">
        <Button className="tag-select-save" loading={saving} onClick={onSaveAll}>
          保存
        </Button>
      </View>
    </View>
  );
}
