import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
import { useStoreSession } from '../contexts/StoreSessionContext';
import {
  needsStoreSelection,
  request,
  selectStore,
  type ShopSessionPayload,
  type ShopStoreOption,
} from '../lib/api';
import { goShopPath } from '../lib/shop-nav';
import { consumeShopReturnTo, peekShopReturnTo } from '../lib/shop-redeem-return';

function goAfterSelectStore(navigate: (path: string, opts?: { replace?: boolean }) => void) {
  goShopPath(consumeShopReturnTo() || '/', navigate);
}

export default function SelectStorePage() {
  const navigate = useNavigate();
  const { applySession, store, authenticated } = useStoreSession();
  const [stores, setStores] = useState<ShopStoreOption[]>(store?.stores ?? []);
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [msg, setMsg] = useState('');

  const currentStoreId = store?.storeId || '';
  const canGoBack = Boolean(currentStoreId);

  const loadStores = useCallback(() => {
    return request<ShopStoreOption[]>('SHOP_H5', '/shop/auth/stores')
      .then((list) => setStores(list))
      .catch((e) => setMsg(e instanceof Error ? e.message : '加载门店失败'));
  }, []);

  useEffect(() => {
    if (!authenticated) {
      navigate('/login', { replace: true });
      return;
    }
    void loadStores();
  }, [authenticated, navigate, loadStores]);

  async function onSelect(storeId: string) {
    if (loadingId) return;
    if (storeId === currentStoreId) {
      goAfterSelectStore(navigate);
      return;
    }
    setLoadingId(storeId);
    setMsg('');
    try {
      const session = await selectStore(storeId);
      applySession(session);
      goAfterSelectStore(navigate);
    } catch (e) {
      setMsg(e instanceof Error ? e.message : '选店失败');
    } finally {
      setLoadingId(null);
    }
  }

  // 仅一家店时自动选
  useEffect(() => {
    if (stores.length === 1 && needsStoreSelection({ store, stores })) {
      void onSelect(stores[0].storeId);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [stores.length]);

  function statusLabel(status: string) {
    if (status === 'OPEN') return '营业中';
    if (status === 'PAUSED') return '临时闭店';
    if (status === 'CLOSED') return '永久关闭';
    return status || '门店';
  }

  return (
    <PullToRefresh onRefresh={loadStores} className="shop-select-store-page">
      <header className="shop-subpage-header">
        {canGoBack ? (
          <button
            type="button"
            className="shop-subpage-back"
            onClick={() => navigate('/mine')}
            aria-label="返回"
          >
            <span className="material-symbols-outlined">arrow_back</span>
          </button>
        ) : (
          <span className="shop-subpage-header-spacer" />
        )}
        <h1 className="app-page-title">切换门店</h1>
        <span className="shop-subpage-header-spacer" />
      </header>

      <div className="shop-subpage-content">
        <section className="shop-subpage-hero">
          <div className="shop-subpage-hero-icon">
            <span className="material-symbols-outlined shop-fill-icon">store</span>
          </div>
          <div>
            <h2 className="shop-subpage-hero-title">选择要进入的门店</h2>
            <p className="shop-subpage-hero-desc">
              该账号绑定了 {stores.length || '多'} 家门店，进入后可直接核销与查看营业数据
            </p>
          </div>
        </section>

        {msg ? (
          <p className="shop-subpage-msg" role="alert">
            {msg}
          </p>
        ) : null}

        <section>
          <h3 className="shop-subpage-section-title">我的门店</h3>
          <ul className="shop-select-store-list">
            {stores.map((item) => {
              const active = item.storeId === currentStoreId;
              const busy = loadingId === item.storeId;
              return (
                <li key={item.storeId}>
                  <button
                    type="button"
                    className={`shop-select-store-item${active ? ' is-active' : ''}`}
                    disabled={Boolean(loadingId)}
                    onClick={() => void onSelect(item.storeId)}
                  >
                    <div className="shop-select-store-item-icon">
                      <span className="material-symbols-outlined shop-fill-icon">storefront</span>
                    </div>
                    <div className="shop-select-store-item-body">
                      <div className="shop-select-store-item-top">
                        <span className="shop-select-store-name">{item.name}</span>
                        {active ? (
                          <span className="shop-select-store-badge">当前</span>
                        ) : (
                          <span className="shop-select-store-status">{statusLabel(item.status)}</span>
                        )}
                      </div>
                      <span className="shop-select-store-meta">
                        {[item.district, item.address].filter(Boolean).join(' · ') ||
                          statusLabel(item.status)}
                      </span>
                    </div>
                    <span className="shop-select-store-item-action">
                      {busy ? (
                        '进入中…'
                      ) : (
                        <span className="material-symbols-outlined">chevron_right</span>
                      )}
                    </span>
                  </button>
                </li>
              );
            })}
          </ul>
          {!stores.length && !msg ? (
            <div className="shop-subpage-empty">
              <span className="material-symbols-outlined">store</span>
              <p>暂无绑定门店</p>
            </div>
          ) : null}
        </section>
      </div>
    </PullToRefresh>
  );
}

/** After login/wechat: route to select-store, redeem return, or home */
export function routeAfterShopLogin(
  session: ShopSessionPayload,
  navigate: (path: string, opts?: { replace?: boolean }) => void,
) {
  if (needsStoreSelection(session)) {
    goShopPath('/select-store', navigate);
    return;
  }
  goShopPath(peekShopReturnTo() || '/', navigate);
}
