import { Navigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { Loader2 } from 'lucide-react';
import Sidebar from './Sidebar';
import TopBar from './TopBar';
import { getRepoStatus } from '../../api/client';
import { useRepoStore } from '../../store/useRepoStore';

export default function PageWrapper({ title, subtitle, children, requireRepo = true, action }) {
  const { repoId, resetAll } = useRepoStore();
  const [checkingRepo, setCheckingRepo] = useState(Boolean(requireRepo && repoId));

  useEffect(() => {
    if (!requireRepo || !repoId) {
      setCheckingRepo(false);
      return undefined;
    }

    let cancelled = false;
    setCheckingRepo(true);
    getRepoStatus(repoId)
      .catch((error) => {
        if (!cancelled && error?.response?.status === 404) {
          resetAll();
        }
      })
      .finally(() => {
        if (!cancelled) setCheckingRepo(false);
      });

    return () => {
      cancelled = true;
    };
  }, [repoId, requireRepo, resetAll]);

  if (requireRepo && !repoId) {
    return <Navigate to="/ingest" replace />;
  }

  if (checkingRepo) {
    return (
      <div className="min-h-screen">
        <Sidebar />
        <main className="min-h-screen px-4 py-6 lg:ml-64 lg:px-8">
          <TopBar title={title} subtitle={subtitle} action={action} />
          <div className="flex min-h-[60vh] items-center justify-center">
            <div className="flex items-center gap-3 rounded-lg border border-cyan-400/20 bg-cyan-500/10 px-4 py-3 text-sm text-cyan-100">
              <Loader2 className="h-4 w-4 animate-spin" />
              Checking repository session
            </div>
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className="min-h-screen">
      <Sidebar />
      <main className="min-h-screen px-4 py-6 lg:ml-64 lg:px-8">
        <TopBar title={title} subtitle={subtitle} action={action} />
        {children}
      </main>
    </div>
  );
}
