import { useCallback, useEffect, useMemo, useState } from 'react';
import { View, Text, Image, Swiper, SwiperItem } from '@tarojs/components';
import Taro, { useDidShow, usePullDownRefresh, useShareAppMessage, useShareTimeline } from '@tarojs/taro';
import PageShell from '../../components/PageShell';
import TabMainHeader from '../../components/TabMainHeader';
import CouponBadge from '../../components/CouponBadge';
import WechatShareReady from '../../components/WechatShareReady';
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
import { goLogin } from '../../lib/auth-nav';
import { isLoggedIn, request, toast } from '../../lib/api';
import { ensurePayReady } from '../../lib/pay-ready';
import { capturePromoSceneAndTouchScan } from '../../lib/promo';
import { getProductMainImage } from '../../lib/product-images';
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
import {
  DEFAULT_SHARE_DESC,
  DEFAULT_SHARE_TITLE,
  toWeappShareMessage,
} from '../../lib/wechat-share';

type Product = {
  id: string;
  name: string;
  subtitle?: string;
  spec?: string;
  price: number;
  benefitDisplay?: number;
  mainImageUrl?: string | null;
  carouselUrls?: string[] | null;
  aromaType: string;
  allowOnSitePickup?: boolean;
};

type MiniHomeConfig = {
  banners: string[];
  footerUrl: string | null;
};

const AROMA_TABS = [
  { key: 'QINGXIANG', label: '清香型' },
  { key: 'JIANGXIANG', label: '酱香型' },
  { key: 'NONGXIANG', label: '浓香型' },
] as const;

export default function HomePage() {
  const [tab, setTab] = useState('QINGXIANG');
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [displayCity, setDisplayCity] = useState('郑州市');
  const [cityCode, setCityCode] = useState('410100');
  const [miniHome, setMiniHome] = useState<MiniHomeConfig>({ banners: [], footerUrl: null });

  const loadMiniHome = useCallback(() => {
    return request<{ miniHome?: MiniHomeConfig }>('/common/client-config')
      .then((cfg) => {
        const banners = Array.isArray(cfg.miniHome?.banners)
          ? cfg.miniHome!.banners.filter((u) => typeof u === 'string' && !!u.trim())
          : [];
        const footerUrl =
          typeof cfg.miniHome?.footerUrl === 'string' && cfg.miniHome.footerUrl.trim()
            ? cfg.miniHome.footerUrl.trim()
            : null;
        setMiniHome({ banners, footerUrl });
      })
      .catch(() => {
        /* 首页装饰图失败不阻断商品列表 */
      });
  }, []);

  useDidShow(() => {
    syncTabBarSelected(0);
    void capturePromoSceneAndTouchScan();
    void loadMiniHome();
    void resolveUserCity().then((resolved) => {
      setDisplayCity(resolved.displayCity);
      setCityCode(getCityCodeForCatalog(resolved));
    });
  });

  const loadProducts = useCallback(() => {
    setLoading(true);
    return request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(cityCode)}`)
      .then((list) => setProducts(Array.isArray(list) ? list : []))
      .catch((e) => toast(e instanceof Error ? e.message : '加载失败'))
      .finally(() => setLoading(false));
  }, [cityCode]);

  useEffect(() => {
    void loadProducts();
  }, [loadProducts]);

  usePullDownRefresh(() => {
    void (async () => {
      try {
        const resolved = await resolveUserCity();
        setDisplayCity(resolved.displayCity);
        const nextCode = getCityCodeForCatalog(resolved);
        setCityCode(nextCode);
        setLoading(true);
        const [list] = await Promise.all([
          request<Product[]>(`/catalog/products?cityCode=${encodeURIComponent(nextCode)}`),
          loadMiniHome(),
        ]);
        setProducts(Array.isArray(list) ? list : []);
      } catch (e) {
        toast(e instanceof Error ? e.message : '加载失败');
      } finally {
        setLoading(false);
        Taro.stopPullDownRefresh();
      }
    })();
  });

  function openProductDetail(id: string) {
    Taro.navigateTo({ url: `/pages/product-detail/index?id=${id}` });
  }

  async function goOnSitePickup(productId: string) {
    const returnPath = `/pages/order-confirm-pickup/index?productId=${productId}&qty=1`;
    if (!isLoggedIn()) {
      goLogin(returnPath);
      return;
    }
    const ready = await ensurePayReady(returnPath);
    if (!ready) return;
    Taro.navigateTo({ url: returnPath });
  }

  const filtered = products.filter((p) => p.aromaType === tab);
  const banners = miniHome.banners;
  const footerUrl = miniHome.footerUrl;

  const sharePayload = useMemo(
    () => ({
      title: DEFAULT_SHARE_TITLE,
      desc: DEFAULT_SHARE_DESC,
      path: '/pages/home/index',
      imgUrl: banners[0] || undefined,
    }),
    [banners],
  );

  useShareAppMessage(() => toWeappShareMessage(sharePayload));
  useShareTimeline(() => ({
    title: sharePayload.title || DEFAULT_SHARE_TITLE,
    query: '',
    imageUrl: sharePayload.imgUrl,
  }));

  return (
    <PageShell variant="tab" className="home-page no-tab-header">
      <WechatShareReady payload={sharePayload} />
      <TabMainHeader title="杜康好客" />

      {banners.length > 0 ? (
        <View className="home-promo-banner">
          <Swiper
            className="home-promo-banner-swiper"
            indicatorDots={banners.length > 1}
            autoplay={banners.length > 1}
            circular={banners.length > 1}
            interval={2500}
          >
            {banners.map((url) => (
              <SwiperItem key={url}>
                <Image className="home-promo-banner-img" src={url} mode="aspectFill" />
              </SwiperItem>
            ))}
          </Swiper>
        </View>
      ) : null}

      <View className="home-aroma-nav">
        <View className="home-aroma-tabs">
          {AROMA_TABS.map((t) => (
            <Text
              key={t.key}
              className={`home-aroma-tab${tab === t.key ? ' home-aroma-tab--active' : ''}`}
              onClick={() => setTab(t.key)}
            >
              {t.label}
            </Text>
          ))}
        </View>
        <Text className="home-aroma-city">{displayCity}</Text>
      </View>

      <View className="home-product-list">
        {loading ? <View className="home-empty">加载中…</View> : null}
        {!loading && products.length === 0 ? (
          <View className="home-empty">当前城市暂无在售商品</View>
        ) : null}
        {!loading && products.length > 0 && filtered.length === 0 ? (
          <View className="home-empty">该香型暂未上线</View>
        ) : null}
        {!loading &&
          filtered.map((p) => {
            const thumb = getProductMainImage(p);
            const spec = p.subtitle || p.spec || '';
            return (
              <View key={p.id} className="home-product-card">
                <View
                  className="home-product-card-inner"
                  onClick={() => openProductDetail(p.id)}
                >
                  <View className="home-product-thumb-wrap">
                    {thumb ? (
                      <Image className="home-product-thumb" src={thumb} mode="aspectFill" />
                    ) : (
                      <View className="home-product-thumb home-product-thumb--empty" />
                    )}
                  </View>
                  <View className="home-product-main">
                    <View className="home-product-row">
                      <Text className="home-product-name">{p.name}</Text>
                      <Text className="home-product-price">¥{Number(p.price).toFixed(0)}</Text>
                    </View>
                    {spec ? <Text className="home-product-sub">{spec}</Text> : null}
                    <View className="home-product-footer">
                      <CouponBadge amount={p.benefitDisplay ?? p.price} label="好客权益" />
                    </View>
                    <View className="home-product-actions">
                      {p.allowOnSitePickup ? (
                        <Text
                          className="home-pickup-btn"
                          onClick={(e) => {
                            e.stopPropagation?.();
                            void goOnSitePickup(p.id);
                          }}
                        >
                          现场取货
                        </Text>
                      ) : null}
                      <Text
                        className="home-buy-btn"
                        onClick={(e) => {
                          e.stopPropagation?.();
                          openProductDetail(p.id);
                        }}
                      >
                        立即购买
                      </Text>
                    </View>
                  </View>
                </View>
              </View>
            );
          })}
      </View>

      {footerUrl ? (
        <View className="home-promo-footer">
          <Image className="home-promo-footer-img" src={footerUrl} mode="aspectFill" />
        </View>
      ) : null}

      {shouldRenderPageTabBar() ? <UserTabBar selected={0} /> : null}
    </PageShell>
  );
}
