
import React, { useEffect, useState } from 'react';
import { Model } from '../types/models';
import { modelApi } from '../services/modelApi';
import ModelCard from './ModelCard';

interface PopularModelsHomeProps {}

const PopularModelsHome: React.FC<PopularModelsHomeProps> = () => {
  const [models, setModels] = useState<Model[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  // 从后端 API 加载精选模型数据
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        setError(null);

        // 使用精选模型接口获取数据
        const response = await modelApi.getFeaturedModels(3);
        const data = response.data.items || [];

        if (data.length === 0) {
          setError('未找到精选模型数据');
          setLoading(false);
          return;
        }

        setModels(data);
        setLoading(false);
      } catch (err) {
        console.error('Failed to load featured models from API:', err);
        setError('加载精选模型数据失败: ' + (err instanceof Error ? err.message : '未知错误'));
        setLoading(false);
      }
    };

    loadData();
  }, []);

  return (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
      {loading && (
        <>
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="bg-white px-6 pt-6 pb-0 rounded-2xl border border-gray-100 shadow-sm animate-pulse h-[300px]"
            >
              <div className="flex items-center space-x-3">
                <div className="w-14 h-14 bg-gray-100 rounded-xl" />
                <div className="flex-1 space-y-2">
                  <div className="h-4 bg-gray-100 rounded w-2/3" />
                  <div className="h-3 bg-gray-100 rounded w-full" />
                </div>
              </div>
            </div>
          ))}
        </>
      )}

      {error && (
        <div className="col-span-full bg-red-50 border border-red-200 rounded-xl p-4 text-center">
          <p className="text-red-600 text-sm">{error}</p>
        </div>
      )}

      {!loading && !error && models.length === 0 && (
        <div className="col-span-full py-10 text-center text-gray-500 text-sm">
          暂无精选模型
        </div>
      )}

      {!loading && !error && models.map((m) => (
        <ModelCard
          key={m.id}
          model={m}
          versionDisplayMode="standard"
        />
      ))}
    </div>
  );
};

export default PopularModelsHome;
