// app/download/page.tsx
'use client';

import { useState } from 'react';
import useSWR from 'swr';
import SearchForm from './SearchForm';
import ApkList from './ApkList';

interface Project {
  name: string;
  displayName: string;
}

export default function DownloadPage() {
  const [searchParams, setSearchParams] = useState({
    project: '',
    version: '',
    commitId: '',
  });

  const { data: projects } = useSWR<Project[]>('/api/projects');

  const handleSearch = (project: string, version: string, commitId: string) => {
    setSearchParams({ project, version, commitId });
  };

  const getProjectDisplayName = (projectName: string): string => {
    const project = projects?.find(p => p.name === projectName);
    return project?.displayName || projectName;
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-8">资源下载</h1>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg shadow-md p-6 sticky top-8">
              <h2 className="text-xl font-semibold text-gray-800 mb-6">搜索</h2>
              <SearchForm onSearch={handleSearch} />
            </div>
          </div>

          <div className="lg:col-span-2">
            {searchParams.project && searchParams.version ? (
              <>
                <h2 className="text-xl font-semibold text-gray-800 mb-4">
                  {getProjectDisplayName(searchParams.project)} - {searchParams.version.replace('_', '.')}
                  {searchParams.commitId && ` (commit: ${searchParams.commitId})`}
                </h2>
                <ApkList
                  project={searchParams.project}
                  version={searchParams.version}
                  commitId={searchParams.commitId}
                />
              </>
            ) : (
              <div className="bg-white rounded-lg shadow-md p-12 text-center">
                <p className="text-gray-500">请选择项目和版本开始搜索</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
