import { useSearch } from "@tanstack/react-router";
import { useRepoStore } from "../store";
import { useEffect, useState } from "react";
import { useShallow } from "zustand/shallow";
import BuildConfig from "../components/BuildConfig";
import { CommonRepoDialog } from "../page";
import { RepoCard } from "../components/RepoCard";

export const App = () => {
  const params = useSearch({ strict: false }) as { repo?: string, tab?: string };
  const repoStore = useRepoStore(useShallow((state) => ({
    getItem: state.getItem,
    editRepo: state.editRepo,
    refresh: state.refresh,
    loading: state.loading,
  })));
  const [activeTab, setActiveTab] = useState(params.tab || "build");
  const tabs = [
    { key: "build", label: "构建配置" },
    { key: "info", label: "基本信息" },
  ]
  useEffect(() => {
    if (params.repo) {
      repoStore.getItem(params.repo);
      repoStore.refresh({ search: params.repo, showTips: false });
    } else {
      console.log('no repo param')
    }
  }, [params])
  if (!repoStore.editRepo) {
    return <div>Loading...</div>
  }
  return (
    <div className="p-2 md:p-4 flex-col flex gap-2 md:gap-4 h-full">
      <div className="px-2 md:px-4 h-full scrollbar flex-col flex gap-3 md:gap-4 overflow-hidden">
        <div className="flex border-b overflow-x-auto">
          {tabs.map(tab => (
            <div
              key={tab.key}
              className={`px-3 md:px-4 py-2 cursor-pointer whitespace-nowrap text-sm md:text-base ${activeTab === tab.key ? 'border-b-2 border-gray-500 font-medium' : ''}`}
              onClick={() => {
                setActiveTab(tab.key)
                history.replaceState(null, '', `?repo=${params.repo}&tab=${tab.key}`)
              }}
            >
              {tab.label}
            </div>
          ))}
        </div>
        {activeTab === 'build' && <BuildConfig />}
        {activeTab === 'info' && (
          <div className="flex flex-col gap-3 md:gap-4 h-full">
            <RepoCard repo={repoStore.editRepo} showReturn />
            <div className="p-3 md:p-4 border rounded bg-white h-full overflow-auto scrollbar">
              <pre className="whitespace-pre-wrap break-all text-xs md:text-sm">{JSON.stringify(repoStore.editRepo, null, 2)}</pre>
            </div>
          </div>
        )}
      </div>
      <CommonRepoDialog />
    </div>
  )
}

export default App;