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

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

const LIMIT = 20;

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

  const { data: stars, isLoading } = useRepoStars(workspaceName, repoName, LIMIT, offset);

  return (
    <div className="space-y-4">
      <p className="text-[12px] text-muted-foreground">
        {(stars ?? []).length} stargazer{(stars ?? []).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>
        ) : (stars ?? []).length > 0 ? (
          <>
            <div className="divide-y divide-border">
              {(stars ?? []).map((star) => (
                <div
                  key={star.id}
                  className="flex items-center gap-3 px-4 py-2.5 transition-colors hover:bg-muted/40"
                >
                  <div className="flex size-8 items-center justify-center rounded-full bg-muted text-[11px] font-semibold text-muted-foreground">
                    {star.user_id.slice(0, 2).toUpperCase()}
                  </div>
                  <div className="min-w-0 flex-1">
                    <span className="text-[13px] font-medium text-foreground">
                      {star.user_id}
                    </span>
                    <div className="text-[11px] text-muted-foreground">
                      Starred {timeAgo(star.created_at)}
                    </div>
                  </div>
                  <Star className="size-4 text-amber-500" />
                </div>
              ))}
            </div>
            <Pagination
              offset={offset}
              limit={LIMIT}
              hasMore={(stars ?? []).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">
            <Star className="size-6 text-muted-foreground/30" />
            <p className="mt-3 text-[13px] text-muted-foreground">No stars yet</p>
          </div>
        )}
      </div>
    </div>
  );
}
