/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

import React, { useMemo, useState } from 'react';
import { ImagePreview } from '@douyinfe/semi-ui';
import HorizontalFilterRow from '../../components/common/ui/HorizontalFilterRow';
import PricingCardView from '../../components/table/model-pricing/view/card/PricingCardView';
import ModelDetailSideSheet from '../../components/table/model-pricing/modal/ModelDetailSideSheet';
import { useModelPricingData } from '../../hooks/model-pricing/useModelPricingData';
import { usePricingFilterCounts } from '../../hooks/model-pricing/usePricingFilterCounts';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { getLobeHubIcon } from '../../helpers';

// 与 model_meta.go ModelType 常量一致：1=Chat, 2=Image, 3=Audio, 4=Video, 5=Embedding, 6=Rerank, 7=Vision, 8=Other
const MODEL_TYPE_LIST = [
  { value: 1, labelKey: '文本' },
  { value: 2, labelKey: '图像' },
  { value: 3, labelKey: '音频' },
  { value: 4, labelKey: '视频' },
  { value: 5, labelKey: '嵌入' },
  { value: 6, labelKey: '重排序' },
  { value: 7, labelKey: '视觉' },
  { value: 8, labelKey: '其他' },
];

// 首页定价区域分页大小配置
// 与 gridColsClass 网格布局配合：移动端1列、平板2列、桌面3列
const HOME_PAGE_SIZE = {
  mobile: 6,   // 1列 × 6行
  tablet: 8,   // 2列 × 4行
  desktop: 9,  // 3列 × 3行
};

const HomePricingFilters = ({ t }) => {
  const [showRatio, setShowRatio] = useState(false);
  const isMobile = useIsMobile();
  const pricingData = useModelPricingData();

  // 根据屏幕尺寸动态计算分页大小
  const pageSize = useMemo(() => {
    if (isMobile) return HOME_PAGE_SIZE.mobile;
    // 通过窗口宽度判断平板（768px-1024px 为 md 范围）
    if (typeof window !== 'undefined' && window.innerWidth < 1024) {
      return HOME_PAGE_SIZE.tablet;
    }
    return HOME_PAGE_SIZE.desktop;
  }, [isMobile]);
  const {
    vendorModels,
    typeModels,
  } = usePricingFilterCounts({
    models: pricingData.models,
    filterGroup: pricingData.filterGroup,
    filterQuotaType: pricingData.filterQuotaType,
    filterEndpointType: pricingData.filterEndpointType,
    filterVendor: pricingData.filterVendor,
    filterTag: pricingData.filterTag,
    filterType: pricingData.filterType,
    searchValue: pricingData.searchValue,
  });

  const vendorItems = useMemo(() => {
    const models = pricingData.models;
    const vendorSet = new Set();
    const vendorIcons = new Map();
    let hasUnknown = false;
    (models || []).forEach((m) => {
      if (m.vendor_name) {
        vendorSet.add(m.vendor_name);
        if (m.vendor_icon && !vendorIcons.has(m.vendor_name)) {
          vendorIcons.set(m.vendor_name, m.vendor_icon);
        }
      } else {
        hasUnknown = true;
      }
    });
    const vendors = Array.from(vendorSet).sort();
    const getVendorCount = () => {
      // 计算供应商数量（包含未知供应商）
      const count = vendorSet.size + (hasUnknown ? 1 : 0);
      return count;
    };
    const getModelCount = (v) => {
      if (v === 'all') return vendorModels.length;
      if (v === 'unknown') return vendorModels.filter((m) => !m.vendor_name).length;
      return vendorModels.filter((m) => m.vendor_name === v).length;
    };
    const items = [
      { value: 'all', label: t('全部供应商'), tagCount: getVendorCount(), disabled: (models || []).length === 0 },
    ];
    vendors.forEach((v) => {
      const count = getModelCount(v);
      items.push({
        value: v,
        label: v,
        icon: vendorIcons.get(v) ? getLobeHubIcon(vendorIcons.get(v), 16) : null,
        tagCount: count,
        disabled: count === 0,
      });
    });
    if (hasUnknown) {
      items.push({
        value: 'unknown',
        label: t('未知供应商'),
        tagCount: getModelCount('unknown'),
        disabled: getModelCount('unknown') === 0,
      });
    }
    return items;
  }, [pricingData.models, vendorModels, t]);

  const typeItems = useMemo(() => {
    const models = pricingData.models;
    const getCount = (typeVal) => {
      if (typeVal === 'all') return typeModels.length;
      const n = Number(typeVal);
      return typeModels.filter((m) => m.type === n).length;
    };
    const items = [
      { value: 'all', label: t('全部类型'), tagCount: getCount('all'), disabled: (models || []).length === 0 },
    ];
    MODEL_TYPE_LIST.forEach(({ value, labelKey }) => {
      const count = getCount(value);
      // 数量为0时不显示
      if (count === 0) return;
      items.push({
        value: String(value),
        label: t(labelKey),
        tagCount: count,
      });
    });
    return items;
  }, [pricingData.models, typeModels, t]);

  return (
    <div className='w-full mt-8 md:mt-12'>
      <div className='rounded-xl border border-semi-color-border bg-semi-color-bg-0 p-4'>
        <HorizontalFilterRow
          title={t('供应商')}
          items={vendorItems}
          activeValue={pricingData.filterVendor}
          onChange={pricingData.setFilterVendor}
          loading={pricingData.loading}
          t={t}
        />
        <HorizontalFilterRow
          title={t('模型类型')}
          items={typeItems}
          activeValue={pricingData.filterType}
          onChange={pricingData.setFilterType}
          loading={pricingData.loading}
          t={t}
        />
      </div>

      <div className='mt-6'>
        <PricingCardView
          filteredModels={pricingData.filteredModels}
          loading={pricingData.loading}
          rowSelection={null}
          pageSize={pageSize}
          setPageSize={pricingData.setPageSize}
          currentPage={pricingData.currentPage}
          setCurrentPage={pricingData.setCurrentPage}
          copyText={pricingData.copyText}
          setModalImageUrl={pricingData.setModalImageUrl}
          setIsModalOpenurl={pricingData.setIsModalOpenurl}
          showRatio={showRatio}
          t={t}
          selectedRowKeys={[]}
          openModelDetail={pricingData.openModelDetail}
          gridColsClass='grid-cols-1 md:grid-cols-2 lg:grid-cols-3'
          showPagination={true}
          showTryButton={true}
        />
      </div>

      <ImagePreview
        src={pricingData.modalImageUrl}
        visible={pricingData.isModalOpenurl}
        onVisibleChange={(visible) => pricingData.setIsModalOpenurl(visible)}
      />

      <ModelDetailSideSheet
        visible={pricingData.showModelDetail}
        onClose={pricingData.closeModelDetail}
        modelData={pricingData.selectedModel}
        groupRatio={pricingData.groupRatio}
        usableGroup={pricingData.usableGroup}
        currency={pricingData.currency}
        tokenUnit={pricingData.tokenUnit}
        displayPrice={pricingData.displayPrice}
        showRatio={showRatio}
        vendorsMap={pricingData.vendorsMap}
        endpointMap={pricingData.endpointMap}
        autoGroups={pricingData.autoGroups}
        t={t}
      />
    </div>
  );
};

export default HomePricingFilters;
