import { useEffect } from 'react'
import { useRepoStore } from './store/index'
import { RepoCard } from './components/RepoCard'
import { EditRepoDialog } from './modules/EditRepoDialog'
import { WorkspaceDetailDialog } from './modules/WorkspaceDetailDialog'
import { SyncRepoDialog } from './modules/SyncRepoDialog'

export const App = () => {
  const { list, getList, loading, editRepo, setEditRepo, showEditDialog, setShowEditDialog, startWorkspace, getWorkspaceList, deleteItem, setSelectedSyncRepo, setSyncDialogOpen } = useRepoStore()

  useEffect(() => {
    getList()
    getWorkspaceList()
  }, [])

  const handleEdit = (repo: any) => {
    setEditRepo(repo)
    setShowEditDialog(true)
  }

  const handleIssue = (repo: any) => {
    window.open(`https://cnb.cool/${repo.path}/-/issues`)
  }

  const handleSettings = (repo: any) => {
    window.open(`https://cnb.cool/${repo.path}/-/settings`)
  }

  const handleDelete = (repo: any) => {
    if (repo.path)
      deleteItem(repo.path)
  }

  const handleSync = (repo: any) => {
    setSelectedSyncRepo(repo)
    setSyncDialogOpen(true)
  }

  return (
    <div className="min-h-screen bg-neutral-50 flex flex-col">
      <div className="container mx-auto p-6 max-w-7xl flex-1">
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-neutral-900 mb-2">仓库列表</h1>
          <p className="text-neutral-600">共 {list.length} 个仓库</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {list.map((repo) => (
            <RepoCard
              key={repo.id}
              repo={repo}
              onStartWorkspace={startWorkspace}
              onEdit={handleEdit}
              onIssue={handleIssue}
              onSettings={handleSettings}
              onDelete={handleDelete}
              onSync={handleSync}
            />
          ))}
        </div>

        {list.length === 0 && !loading && (
          <div className="text-center py-20">
            <div className="text-neutral-400 text-lg">暂无仓库数据</div>
          </div>
        )}
      </div>

      <footer className="border-t border-neutral-200 bg-white py-6 mt-auto">
        <div className="container mx-auto px-6 max-w-7xl">
          <div className="flex items-center justify-between text-sm text-neutral-500">
            <div>© 2026 仓库管理系统</div>
            <div className="flex items-center gap-4">
              <a href="#" className="hover:text-neutral-900 transition-colors">关于</a>
              <a href="#" className="hover:text-neutral-900 transition-colors">帮助</a>
              <a href="#" className="hover:text-neutral-900 transition-colors">联系我们</a>
            </div>
          </div>
        </div>
      </footer>

      <EditRepoDialog
        open={showEditDialog}
        onOpenChange={setShowEditDialog}
        repo={editRepo}
      />
      <WorkspaceDetailDialog />
      <SyncRepoDialog />
    </div>
  )
}

export default App;