import { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import { useDidShow } from '@tarojs/taro';
import HqHeader from '../../components/HqHeader';
import { request, type Paginated } from '../../lib/api';
import { useHqSession } from '../../lib/session';
import { CITY_STATUS_LABELS, badgeClass } from '../../lib/constants';

type CityRow = {
  id: string;
  code: string;
  name: string;
  province?: string;
  status: string;
  storeCount?: number;
  orderCount?: number;
  partner?: { companyName: string };
};

export default function CitiesPage() {
  useHqSession();
  const [rows, setRows] = useState<CityRow[]>([]);
  const [loading, setLoading] = useState(true);

  function load() {
    setLoading(true);
    request<Paginated<CityRow>>('/admin/cities?pageSize=100')
      .then((d) => setRows(d.items))
      .catch(() => setRows([]))
      .finally(() => setLoading(false));
  }

  useEffect(load, []);
  useDidShow(load);

  return (
    <View className="hq-page">
      <HqHeader title="开城管理" back />

      <Text className="hq-section-title">
        <Text>开城城市</Text>
        <Text className="hq-muted" style="font-size:12px;font-weight:400">共 {rows.length} 城</Text>
      </Text>

      {loading && <View className="hq-empty">加载中…</View>}
      {!loading && rows.length === 0 && <View className="hq-empty">暂无开城城市</View>}

      {rows.map((c) => (
        <View key={c.id} className="hq-card" style="margin-top:8px;margin-bottom:0">
          <View className="hq-row">
            <Text style="font-size:16px;font-weight:700">{c.name}<Text className="hq-muted" style="font-size:12px;font-weight:400"> · {c.code}</Text></Text>
            <Text className={`hq-badge ${badgeClass(c.status)}`}>{CITY_STATUS_LABELS[c.status] || c.status}</Text>
          </View>
          <Text className="hq-muted" style="display:block;margin-top:6px;font-size:13px">
            {c.province || ''} · 合伙人：{c.partner?.companyName || '—'}
          </Text>
          <View className="hq-row" style="margin-top:10px">
            <Text className="hq-muted" style="font-size:13px">门店 <Text style="color:var(--hq-red);font-weight:700">{c.storeCount ?? 0}</Text></Text>
            <Text className="hq-muted" style="font-size:13px">订单 <Text style="color:var(--hq-red);font-weight:700">{c.orderCount ?? 0}</Text></Text>
          </View>
        </View>
      ))}
    </View>
  );
}
