import React from 'react';

import Button from '@/components/button/Button';
import { ButtonSize, ButtonVariant } from '@/components/button/Button';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { useAllRemasters, useRemastersForClip } from '@/hooks/useRemasters';
import { Clip } from '@/state/clipStore';

interface RemasterListProps {
  parentClipId?: string;
  workspaceId?: string | null;
  pageLimit?: number;
}

/**
 * Component to display a list of remasters with pagination
 */
export function RemasterList({
  parentClipId,
  workspaceId,
  pageLimit = 20,
}: RemasterListProps) {
  // Use different hooks based on whether we're filtering by parent clip
  const allRemastersQuery = useAllRemasters({
    pageLimit,
    workspaceId,
    enabled: !parentClipId,
  });

  const clipRemastersQuery = useRemastersForClip({
    parentClipId: parentClipId || '',
    pageLimit,
    workspaceId,
    enabled: !!parentClipId,
  });

  const query = parentClipId ? clipRemastersQuery : allRemastersQuery;

  if (query.isLoading) {
    return (
      <div className='flex justify-center p-4'>
        <SpinnerSVG />
      </div>
    );
  }

  if (query.isError) {
    return (
      <div className='p-4'>
        <p className='text-accent-error'>
          Error loading remasters: {query.error?.message}
        </p>
      </div>
    );
  }

  const allClips = query.clips || [];

  return (
    <div className='flex flex-col gap-4'>
      <p className='text-lg font-bold'>
        {parentClipId ? 'Remasters of this clip' : 'All Remasters'}(
        {allClips.length})
      </p>

      {allClips.length === 0 ? (
        <p className='p-4 text-center text-gray-500'>No remasters found</p>
      ) : (
        <div className='flex flex-col gap-2'>
          {allClips.map((clip: Clip) => (
            <div
              key={clip.id}
              className='rounded-md border border-gray-200 bg-white p-3'
            >
              <p>Clip ID: {clip.id}</p>
            </div>
          ))}
        </div>
      )}

      {query.hasMore && (
        <Button
          onClick={() => query.loadMore()}
          size={ButtonSize.Medium}
          variant={ButtonVariant.Tertiary}
          icon={query.isLoadingMore ? <SpinnerSVG /> : undefined}
        >
          {query.isLoadingMore ? 'Loading more...' : 'Load More'}
        </Button>
      )}
    </div>
  );
}

export default RemasterList;
