import { Box, Text } from "ink";
import { Spinner } from "@inkjs/ui";
import { UnifiedProjectItem } from "./UnifiedProjectItem.tsx";
import { ColumnHeader, ColumnSeparator } from "./ColumnHeader.tsx";
import { useStore, useFilteredUnifiedRepos } from "../state/store.tsx";

interface ProjectListProps {
  height?: number;
}

export function ProjectList({ height = 20 }: ProjectListProps) {
  const { state } = useStore();
  const { cursorIndex, selectedIndices, isLoading, sortBy, sortDirection } = state;
  const filteredRepos = useFilteredUnifiedRepos();

  if (isLoading) {
    return (
      <Box flexDirection="column" alignItems="center" justifyContent="center" height={height}>
        <Spinner label="Scanning projects..." />
      </Box>
    );
  }

  if (filteredRepos.length === 0) {
    return (
      <Box flexDirection="column">
        {/* Always show headers */}
        <ColumnHeader sortBy={sortBy} sortDirection={sortDirection} />
        <ColumnSeparator />
        <Box flexDirection="column" alignItems="center" justifyContent="center" height={height - 2}>
          <Text color="gray">No repositories found</Text>
          {state.filterText && (
            <Text color="gray">Try a different filter</Text>
          )}
          {state.viewMode === "github" && !state.githubRepos.length && (
            <>
              {state.githubError ? (
                <Text color="red">GitHub error: {state.githubError}</Text>
              ) : (
                <Text color="yellow">Set GITHUB_TOKEN to see GitHub repos</Text>
              )}
            </>
          )}
        </Box>
      </Box>
    );
  }

  // Reserve space for header (2 lines: header + separator)
  const listHeight = height - 2;
  
  // Calculate visible range with scroll offset
  const visibleCount = Math.min(listHeight, filteredRepos.length);
  let startIndex = Math.max(0, cursorIndex - Math.floor(visibleCount / 2));

  // Adjust if we're near the end
  if (startIndex + visibleCount > filteredRepos.length) {
    startIndex = Math.max(0, filteredRepos.length - visibleCount);
  }

  const visibleRepos = filteredRepos.slice(startIndex, startIndex + visibleCount);

  return (
    <Box flexDirection="column">
      {/* Persistent column headers */}
      <ColumnHeader sortBy={sortBy} sortDirection={sortDirection} />
      <ColumnSeparator />
      
      {/* Repository list */}
      {visibleRepos.map((repo, idx) => {
        const realIndex = startIndex + idx;
        return (
          <UnifiedProjectItem
            key={repo.id}
            repo={repo}
            isSelected={selectedIndices.has(realIndex)}
            isCursor={realIndex === cursorIndex}
          />
        );
      })}

      {/* Scroll indicator at bottom */}
      {startIndex + visibleCount < filteredRepos.length && (
        <Box>
          <Text color="gray">    ↓ {filteredRepos.length - startIndex - visibleCount} more below</Text>
        </Box>
      )}
    </Box>
  );
}
