import { useCallback, useEffect, useState } from 'react';
import { View, Text, Image, Input } from '@tarojs/components';
import Taro, { useDidShow, usePullDownRefresh } from '@tarojs/taro';
import PageShell from '../../components/PageShell';
import TabMainHeader from '../../components/TabMainHeader';
import RegionPicker from '../../components/RegionPicker';
import {
  DEFAULT_REGION,
  formatRegionLabel,
  matchesRegionFilter,
  type RegionSelection,
} from '../../lib/region-data';
import UserTabBar, { shouldRenderPageTabBar, syncTabBarSelected } from '../../components/UserTabBar';
import { getCityCodeForCatalog, resolveUserCity } from '../../lib/user-location';
import { FALLBACK_CITY_CODE } from '../../lib/product-images';
import { request, toast } from '../../lib/api';

type Store = {
  id: string;
  name: string;
  address?: string;
  province?: string;
  cityName?: string;
  district?: string;
  coverUrl?: string | null;
  openTime?: string | null;
  closeTime?: string | null;
  status?: string;
};

const CATEGORY_TABS = ['全部', '火锅', '地方菜', '高端餐饮', '烧烤烤肉', '西餐'] as const;
const MOCK_DISTANCES = ['800m', '1.2km', '3.5km', '1.5km', '2.0km'];

export default function StoresPage() {
  const [stores, setStores] = useState<Store[]>([]);
  const [loading, setLoading] = useState(true);
  const [categoryTab, setCategoryTab] = useState<string>('全部');
  const [keyword, setKeyword] = useState('');
  const [region, setRegion] = useState<RegionSelection>(DEFAULT_REGION);
  const [regionOpen, setRegionOpen] = useState(false);
  const [cityCode, setCityCode] = useState<string>(FALLBACK_CITY_CODE);
  const regionLabel = formatRegionLabel(region);

  useDidShow(() => {
    syncTabBarSelected(1);
    void resolveUserCity().then((resolved) => {
      setRegion(resolved.region);
      setCityCode(getCityCodeForCatalog(resolved));
    });
  });

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

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

  usePullDownRefresh(() => {
    void (async () => {
      try {
        const resolved = await resolveUserCity();
        setRegion(resolved.region);
        const nextCode = getCityCodeForCatalog(resolved);
        setCityCode(nextCode);
        setLoading(true);
        const path = nextCode ? `/stores?cityCode=${encodeURIComponent(nextCode)}` : '/stores';
        const list = await request<Store[]>(path);
        setStores(Array.isArray(list) ? list : []);
      } catch (e) {
        toast(e instanceof Error ? e.message : '加载失败');
      } finally {
        setLoading(false);
        Taro.stopPullDownRefresh();
      }
    })();
  });

  const filtered = stores.filter((s) => {
    if (!matchesRegionFilter(s, region)) return false;
    if (!keyword.trim()) return true;
    const q = keyword.trim();
    return s.name.includes(q) || (s.address ?? '').includes(q) || (s.district ?? '').includes(q);
  });

  function formatHours(store: Store) {
    if (store.openTime && store.closeTime) {
      return `营业时间: ${store.openTime}-${store.closeTime}`;
    }
    return '营业时间: 10:00-22:00';
  }

  return (
    <PageShell variant="tab" className="store-page no-tab-header">
      <TabMainHeader title="门店" />
      <View className="store-toolbar">
        <View className="store-location" onClick={() => setRegionOpen(true)}>
          <View className="store-location-pin" />
          <Text className="store-location-text">{regionLabel} ▾</Text>
        </View>
        <Input
          className="store-search"
          placeholder="搜索门店"
          value={keyword}
          onInput={(e) => setKeyword(e.detail.value)}
        />
      </View>

      <View className="store-category-tabs">
        {CATEGORY_TABS.map((tab) => (
          <Text
            key={tab}
            className={`store-category-tab${categoryTab === tab ? ' store-category-tab--active' : ''}`}
            onClick={() => setCategoryTab(tab)}
          >
            {tab}
          </Text>
        ))}
      </View>

      <View className="store-list">
        {loading ? <View className="u-empty">加载中…</View> : null}
        {!loading && filtered.length === 0 ? <View className="u-empty">暂无营业中门店</View> : null}
        {!loading &&
          filtered.map((s, index) => (
            <View
              key={s.id}
              className="store-card"
              onClick={() => Taro.navigateTo({ url: `/pages/store-detail/index?id=${s.id}` })}
            >
              {s.coverUrl ? (
                <Image className="store-card-cover" src={s.coverUrl} mode="aspectFill" />
              ) : (
                <View className="store-card-cover--empty" />
              )}
              <View className="store-card-body">
                <Text className="store-card-name">{s.name}</Text>
                <Text className="store-card-meta">
                  {s.district ? `${s.district} · ` : ''}
                  {s.address || '地址待完善'}
                </Text>
                <Text className="store-card-meta">{formatHours(s)}</Text>
                <View className="store-card-footer">
                  <Text className="store-card-distance">{MOCK_DISTANCES[index % MOCK_DISTANCES.length]}</Text>
                  <Text
                    className="store-card-cta"
                    onClick={(e) => {
                      e.stopPropagation();
                      Taro.navigateTo({ url: '/pages/redeem/index' });
                    }}
                  >
                    去核销
                  </Text>
                </View>
              </View>
            </View>
          ))}
      </View>

      {shouldRenderPageTabBar() ? <UserTabBar selected={1} /> : null}
      <RegionPicker
        open={regionOpen}
        value={region}
        levels={3}
        onClose={() => setRegionOpen(false)}
        onConfirm={(next) => setRegion(next)}
      />
    </PageShell>
  );
}
