import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { GitFork } from 'lucide-react';

import { Pagination } from '@/components/repo/Pagination';
import { Spinner } from '@/components/ui/spinner';
import { useRepoForks } from '@/hooks/repo/useRepoForks';
import { timeAgo } from '@/lib/utils';

const LIMIT = 20;

export function RepoForksPage() {
  const { workspaceName = '', repoName = '' } = useParams();
  const [offset, setOffset] = useState(0);

  const { data: forks, isLoading } = useRepoForks(workspaceName, repoName, LIMIT, offset);

  return (
    <div className="space-y-4">
      <p className="text-[12px] text-muted-foreground">
        {(forks ?? []).length} fork{(forks ?? []).length !== 1 ? 's' : ''}
      </p>

      <div className="overflow-hidden rounded-lg border border-border">
        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <Spinner />
          </div>
        ) : (forks ?? []).length > 0 ? (
          <>
            <div className="divide-y divide-border">
              {(forks ?? []).map((fork) => (
                <div
                  key={fork.id}
                  className="flex items-center gap-3 px-4 py-2.5 transition-colors hover:bg-muted/40"
                >
                  <GitFork className="size-4 shrink-0 text-muted-foreground" />
                  <div className="min-w-0 flex-1">
                    <span className="text-[13px] font-medium text-foreground">
                      {fork.fork_repo_id}
                    </span>
                    <div className="mt-0.5 text-[11px] text-muted-foreground">
                      Forked by {fork.forked_by} · {timeAgo(fork.created_at)}
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <Pagination
              offset={offset}
              limit={LIMIT}
              hasMore={(forks ?? []).length >= LIMIT}
              onPrev={() => setOffset(Math.max(0, offset - LIMIT))}
              onNext={() => setOffset(offset + LIMIT)}
            />
          </>
        ) : (
          <div className="flex flex-col items-center justify-center py-16 text-center">
            <GitFork className="size-6 text-muted-foreground/30" />
            <p className="mt-3 text-[13px] text-muted-foreground">No forks yet</p>
          </div>
        )}
      </div>
    </div>
  );
}
