import { Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getHomeData } from "../../api/home";
import { groupMediaAccounts, normalizeMediaAccounts, type NormalizedMediaAccount } from "../../utils/mediaMatrix";
import "./index.scss";

export default function MediaMatrixPage() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [accounts, setAccounts] = useState<NormalizedMediaAccount[]>([]);

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const data = await getHomeData();
        setAccounts(normalizeMediaAccounts(data?.mediaAccounts || []));
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const groups = useMemo(() => {
    return groupMediaAccounts(accounts);
  }, [accounts]);

  const openAccount = async (account: NormalizedMediaAccount) => {
    if (account.platformKey === "miniprogram") {
      if (account.qrCodeUrl) {
        await Taro.previewImage({ urls: [account.qrCodeUrl], current: account.qrCodeUrl });
        return;
      }
      Taro.showToast({ title: "暂无二维码", icon: "none" });
      return;
    }
    if (account.displayUrl) {
      await Taro.setClipboardData({ data: account.displayUrl });
      Taro.showToast({ title: "已复制链接", icon: "none" });
      return;
    }
    if (account.qrCodeUrl) {
      await Taro.previewImage({ urls: [account.qrCodeUrl], current: account.qrCodeUrl });
    }
  };

  const getActionText = (account: NormalizedMediaAccount) => {
    if (account.platformKey === "miniprogram") return "查看二维码";
    if (account.displayUrl && account.qrCodeUrl) return "复制链接 / 看码";
    return account.displayUrl ? "复制链接" : "查看二维码";
  };

  return (
    <View className="media-matrix-page">
      <View className="media-matrix-page__body">
        <View className="media-matrix-hero">
          <Text className="media-matrix-hero__title">新媒体矩阵</Text>
          <Text className="media-matrix-hero__desc">
            {accounts.length > 0 ? `已开通 ${accounts.length} 个官方渠道` : "官方账号配置后将在这里展示"}
          </Text>
        </View>

        {error ? (
          <View className="media-matrix-state is-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        {loading ? (
          <View className="media-matrix-state">
            <Text>加载中...</Text>
          </View>
        ) : null}

        {!loading && groups.length === 0 ? (
          <View className="media-matrix-state">
            <Text>暂无新媒体账号</Text>
          </View>
        ) : null}

        <View className="media-matrix-groups">
          {groups.map((group) => (
            <View key={group.key} className="media-matrix-group">
              <View className="media-matrix-group__head">
                <Text className="media-matrix-group__title">{group.title}</Text>
                <Text className="media-matrix-group__count">{group.rows.length} 个</Text>
              </View>
              <View className="media-matrix-group__grid">
                {group.rows.map((account) => (
                  <View key={account.id} className="media-matrix-account" onClick={() => void openAccount(account)}>
                    <View className="media-matrix-account__logo-wrap">
                      <Image className="media-matrix-account__logo" src={account.logoSrc} mode="aspectFit" />
                    </View>
                    <Text className="media-matrix-account__name">{account.name || "-"}</Text>
                    <Text className="media-matrix-account__platform">{getActionText(account)}</Text>
                  </View>
                ))}
              </View>
            </View>
          ))}
        </View>
      </View>
    </View>
  );
}
