/**
 * 门店筛选器组件 + useSiteFilter hook。
 *
 * - 数据源：当前管理员的 managed_site_ids（从 useAuth 获取）
 * - Ant Design Select，支持多选/全选
 * - useSiteFilter hook 供各页面使用，管理选中状态
 */

import React, { useState, useCallback, useMemo } from "react";
import { Select, Space } from "antd";
import { useAuth } from "@/hooks/useAuth";

/* ------------------------------------------------------------------ */
/*  Hook：门店筛选状态管理                                              */
/* ------------------------------------------------------------------ */

export interface SiteFilterState {
  /** 当前选中的 site_id 列表（空 = 全选） */
  selectedSiteIds: number[];
  /** 设置选中的 site_id */
  setSelectedSiteIds: (ids: number[]) => void;
  /** 管理员管辖的全部 site_id */
  allSiteIds: number[];
  /** 用于 API 请求的 site_id 列表（空选时返回全部） */
  effectiveSiteIds: number[];
}

export function useSiteFilter(): SiteFilterState {
  const { user } = useAuth();
  const allSiteIds = useMemo(() => user?.managedSiteIds ?? [], [user]);
  const [selectedSiteIds, setSelectedSiteIds] = useState<number[]>([]);

  const effectiveSiteIds = useMemo(
    () => (selectedSiteIds.length > 0 ? selectedSiteIds : allSiteIds),
    [selectedSiteIds, allSiteIds],
  );

  return { selectedSiteIds, setSelectedSiteIds, allSiteIds, effectiveSiteIds };
}

/* ------------------------------------------------------------------ */
/*  组件                                                               */
/* ------------------------------------------------------------------ */

interface SiteSelectorProps {
  value: number[];
  onChange: (ids: number[]) => void;
  allSiteIds: number[];
}

const SiteSelector: React.FC<SiteSelectorProps> = ({ value, onChange, allSiteIds }) => {
  const isAllSelected = value.length === 0 || value.length === allSiteIds.length;

  const handleChange = useCallback(
    (selected: number[]) => {
      // 如果选了全部，清空表示"全选"
      if (selected.length === allSiteIds.length) {
        onChange([]);
      } else {
        onChange(selected);
      }
    },
    [allSiteIds, onChange],
  );

  const handleSelectAll = useCallback(() => {
    onChange([]);
  }, [onChange]);

  const options = useMemo(
    () => allSiteIds.map((id) => ({ label: `门店 ${id}`, value: id })),
    [allSiteIds],
  );

  return (
    <Space>
      <Select
        mode="multiple"
        placeholder="选择门店（默认全部）"
        value={isAllSelected ? [] : value}
        onChange={handleChange}
        options={options}
        style={{ minWidth: 240 }}
        allowClear
        maxTagCount="responsive"
      />
      {!isAllSelected && (
        <a onClick={handleSelectAll} style={{ whiteSpace: "nowrap" }}>
          全选
        </a>
      )}
    </Space>
  );
};

export default SiteSelector;
