import { Button, Input, Picker, Text, View } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import "./index.scss";

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

function dedupe(values: string[]) {
  const seen = new Set<string>();
  return values.filter((v) => {
    const key = v.trim();
    if (!key || seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

export default function TagProfessionalPage() {
  useAuthGuard();
  const eventChannel = Taro.getCurrentInstance().page?.getOpenerEventChannel?.();
  const [categories, setCategories] = useState<DictCategory[]>([]);
  const [categoryIndex, setCategoryIndex] = useState(0);
  const [selectedItemIds, setSelectedItemIds] = useState<number[]>([]);
  const [selectedCustomLabels, setSelectedCustomLabels] = useState<string[]>([]);
  const [customInput, setCustomInput] = useState("");

  useLoad((params) => {
    const draftKey = String(params?.draftKey || "");
    const payload = draftKey ? Taro.getStorageSync(draftKey) : null;
    if (draftKey) Taro.removeStorageSync(draftKey);

    const cats = Array.isArray(payload?.categories) ? payload.categories : [];
    setCategories(cats);
    setCategoryIndex(0);
    setSelectedItemIds(Array.isArray(payload?.selectedItemIds) ? payload.selectedItemIds : []);
    setSelectedCustomLabels(dedupe(Array.isArray(payload?.selectedCustomLabels) ? payload.selectedCustomLabels : []));
  });

  const activeCategory = categories[categoryIndex];

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

  const toggleItem = (itemId: number) => {
    setSelectedItemIds((prev) => (prev.includes(itemId) ? prev.filter((id) => id !== itemId) : [...prev, itemId]));
  };

  const addCustom = () => {
    const value = customInput.trim();
    if (!value) return;
    if (selectedLabels.includes(value)) {
      setCustomInput("");
      return;
    }
    setSelectedCustomLabels((prev) => [...prev, value]);
    setCustomInput("");
  };

  const removeSelectedLabel = (name: string) => {
    setSelectedCustomLabels((prev) => prev.filter((x) => x !== name));
    const id = categories.flatMap((c) => c.items).find((i) => i.name === name)?.id;
    if (id) {
      setSelectedItemIds((prev) => prev.filter((x) => x !== id));
    }
  };

  const onSave = async () => {
    eventChannel?.emit("professionalSelectionSaved", {
      selectedItemIds,
      selectedCustomLabels: dedupe(selectedCustomLabels)
    });
    await Taro.navigateBack();
  };

  return (
    <View className="page-shell tag-prof-page">
      <View className="page-body">
        <Text className="tag-prof-title">选择专业标签</Text>
        <View className="tag-prof-picker-row">
          <Text className="tag-prof-picker-row__label">标签分类</Text>
          <Picker mode="selector" range={categories.map((cat) => cat.name)} value={categoryIndex} onChange={(e) => setCategoryIndex(Number(e.detail.value || 0))}>
            <View className="tag-prof-picker-row__picker">
              <Text>{activeCategory?.name || "请选择分类"}</Text>
            </View>
          </Picker>
        </View>

        <View className="tag-prof-list">
          {(activeCategory?.items || []).map((item, index) => {
            const selected = selectedItemIds.includes(item.id);
            return (
              <View key={item.id} className={`tag-prof-row ${selected ? "tag-prof-row--active" : ""}`} onClick={() => toggleItem(item.id)}>
                <Text className="tag-prof-row__text">{`${String(index + 1).padStart(2, "0")}. ${item.name}`}</Text>
              </View>
            );
          })}
        </View>

        <View className="tag-prof-custom">
          <Text className="tag-prof-custom__label">自定义标签</Text>
          <View className="tag-prof-custom__row">
            <Input className="tag-prof-custom__input" placeholder="输入后点击添加" maxlength={30} value={customInput} onInput={(e) => setCustomInput(e.detail.value)} />
            <Button className="tag-prof-custom__btn" size="mini" onClick={addCustom}>
              添加
            </Button>
          </View>
        </View>

        <View className="tag-prof-selected">
          <Text className="tag-prof-selected__label">已选标签</Text>
          <View className="tag-prof-selected__items">
            {selectedLabels.length > 0 ? (
              selectedLabels.map((name) => (
                <View key={name} className="tag-prof-selected__pill" onClick={() => removeSelectedLabel(name)}>
                  <Text>{name}</Text>
                </View>
              ))
            ) : (
              <Text className="tag-prof-selected__empty">暂无已选标签</Text>
            )}
          </View>
        </View>
      </View>

      <View className="tag-prof-bottom">
        <Button className="tag-prof-save" onClick={onSave}>
          保存
        </Button>
      </View>
    </View>
  );
}
