import { Button, Image, Input, ScrollView, Text, View } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import { useState } from "react";
import { searchAll } from "../../api/search";
import { firstText, resolveMediaUrl } from "../../utils/media";
import "./index.scss";

const FILTERS = [
  { label: "全部", value: "contents,activities,services,mutual_aid,members,surveys" },
  { label: "内容", value: "contents" },
  { label: "活动", value: "activities" },
  { label: "服务", value: "services" },
  { label: "互助", value: "mutual_aid" },
  { label: "会员", value: "members" },
  { label: "问卷", value: "surveys" }
];

function typeLabel(item: any) {
  const type = String(item?.type || "").toLowerCase();
  if (type === "activity") return "活动";
  if (type === "service") return item?.service_kind === "service_team" || item?.serviceKind === "service_team" ? "服务团" : "服务项目";
  if (type === "mutual_aid") return "企业互助";
  if (type === "member") return "会员";
  if (type === "survey") return "调查问卷";
  return "内容";
}

function targetUrl(item: any) {
  const type = String(item?.type || "").toLowerCase();
  const id = Number(item?.id || 0);
  if (!id) return "";
  if (type === "activity") return `/pages/activity-detail/index?id=${id}`;
  if (type === "service") {
    const kind = String(item?.service_kind || item?.serviceKind || "").toLowerCase();
    return kind === "service_team" ? `/pages/service-team-detail/index?id=${id}` : `/pages/service-detail/index?id=${id}`;
  }
  if (type === "mutual_aid") return `/pages/mutual-aid-detail/index?id=${id}`;
  if (type === "survey") return `/pages/my-survey-detail/index?id=${id}`;
  if (type === "member") return `/pages/social/index?focusUserId=${id}`;
  return `/pages/content-detail/index?id=${id}`;
}

export default function SearchPage() {
  const [keyword, setKeyword] = useState("");
  const [filter, setFilter] = useState(FILTERS[0].value);
  const [items, setItems] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [searched, setSearched] = useState(false);
  const [error, setError] = useState("");

  const doSearch = async (nextKeyword = keyword, nextFilter = filter) => {
    const q = nextKeyword.trim();
    if (!q) {
      Taro.showToast({ title: "请输入搜索关键词", icon: "none" });
      return;
    }
    setLoading(true);
    setSearched(true);
    try {
      const result = await searchAll({ q, types: nextFilter, page: 1, pageSize: 30 });
      setItems(result.items || []);
      setTotal(Number(result.total || 0));
      setError("");
    } catch (e: any) {
      setError(e?.message || "搜索失败");
      setItems([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  useLoad((params) => {
    const q = String(params?.q || params?.keyword || "").trim();
    if (q) {
      setKeyword(q);
      void doSearch(q, filter);
    }
  });

  const openItem = async (item: any) => {
    const url = targetUrl(item);
    if (!url) {
      Taro.showToast({ title: "暂无可查看详情", icon: "none" });
      return;
    }
    if (url.startsWith("/pages/social/index")) {
      await Taro.switchTab({ url: "/pages/social/index" });
      return;
    }
    await Taro.navigateTo({ url });
  };

  return (
    <View className="search-page">
      <View className="search-page__body">
        <View className="search-box">
          <Input
            className="search-box__input"
            value={keyword}
            onInput={(event) => setKeyword(event.detail.value)}
            confirmType="search"
            onConfirm={() => void doSearch()}
            placeholder="搜索新闻、学习、活动、服务、会员"
            placeholderStyle="color:#9ca3af;"
          />
          <Button className="search-box__button" loading={loading} onClick={() => void doSearch()}>
            搜索
          </Button>
        </View>

        <ScrollView scrollX className="search-filter">
          {FILTERS.map((item) => (
            <View
              key={item.value}
              className={`search-filter__chip ${filter === item.value ? "is-active" : ""}`}
              onClick={() => {
                setFilter(item.value);
                if (keyword.trim()) void doSearch(keyword, item.value);
              }}
            >
              <Text>{item.label}</Text>
            </View>
          ))}
        </ScrollView>

        {error ? <Text className="search-state is-error">{error}</Text> : null}
        {loading ? <Text className="search-state">搜索中...</Text> : null}
        {!loading && searched ? <Text className="search-count">共找到 {total || items.length} 条结果</Text> : null}
        {!loading && searched && items.length === 0 && !error ? <Text className="search-state">暂无匹配结果</Text> : null}

        <View className="search-list">
          {items.map((item, index) => {
            const cover = resolveMediaUrl(firstText(item?.cover_image_url, item?.coverImageUrl, item?.imageUrl, item?.avatar_url));
            return (
              <View key={`${item?.type}-${item?.id}-${index}`} className="search-card" onClick={() => void openItem(item)}>
                {cover ? <Image className="search-card__cover" src={cover} mode="aspectFill" /> : null}
                <View className="search-card__main">
                  <View className="search-card__top">
                    <Text className="search-card__type">{typeLabel(item)}</Text>
                    {item?.matched_field || item?.matchedField ? <Text className="search-card__match">命中：{item.matched_field || item.matchedField}</Text> : null}
                  </View>
                  <Text className="search-card__title">{item?.title || "未命名"}</Text>
                  <Text className="search-card__summary">{item?.summary || item?.meta || "暂无摘要"}</Text>
                  {item?.meta ? <Text className="search-card__meta">{item.meta}</Text> : null}
                </View>
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}
