// app/download/ApkList.tsx
import useSWR from 'swr';
import ApkCard from './ApkCard';

const fetcher = (url: string) => fetch(url).then((res) => res.json());

interface ApkListProps {
  project: string;
  version: string;
  commitId: string;
}

interface Apk {
  name: string;
  commit: string | null;
  size: number;
  modifiedAt: string;
  downloadUrl: string;
}

export default function ApkList({ project, version, commitId }: ApkListProps) {
  const { data: apks, isLoading, error } = useSWR<Apk[]>(
    `/api/apks?project=${project}&version=${version}&commit=${commitId}`,
    fetcher
  );

  if (isLoading) {
    return (
      <div className="text-center py-8 text-gray-500">
        加载中...
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8 text-red-600">
        加载失败，请重试
      </div>
    );
  }

  if (!apks || apks.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        未找到匹配的 APK 文件
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      {apks.map((apk) => (
        <ApkCard
          key={apk.name}
          name={apk.name}
          commit={apk.commit}
          size={apk.size}
          modifiedAt={apk.modifiedAt}
          downloadUrl={apk.downloadUrl}
          highlightCommit={commitId}
        />
      ))}
    </div>
  );
}
