'use client';

import type { ReactNode, RefObject } from 'react';

import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';

import CreatorIdentityRow, {
  type CreatorIdentityRowSize,
  type CreatorIdentityRowTone,
} from '@/components/creators/CreatorIdentityRow';
import { cn } from '@/lib/utils';

import type { CreatorIdentity } from '@/types/Creator';

export interface CreatorResultListItemState<TCreator extends CreatorIdentity> {
  creator: TCreator;
  index: number;
  active: boolean;
  disabled: boolean;
  selected: boolean;
}

export type CreatorResultListItemClassName<TCreator extends CreatorIdentity> =
  | string
  | ((state: CreatorResultListItemState<TCreator>) => string | false | null | undefined);

export interface CreatorResultListProps<TCreator extends CreatorIdentity> {
  creators: TCreator[];
  onSelect: (creator: TCreator, index: number) => void;
  loading?: boolean;
  loadingLabel?: ReactNode;
  emptyLabel: ReactNode;
  className?: string;
  itemClassName?: CreatorResultListItemClassName<TCreator>;
  getKey?: (creator: TCreator, index: number) => string | number;
  getOptionId?: (index: number) => string;
  isDisabled?: (creator: TCreator, index: number) => boolean;
  isSelected?: (creator: TCreator, index: number) => boolean;
  activeIndex?: number;
  preventMouseDown?: boolean;
  rowClassName?: string;
  rowSize?: CreatorIdentityRowSize;
  rowTone?: CreatorIdentityRowTone;
  virtualized?: boolean;
  virtuosoRef?: RefObject<VirtuosoHandle | null>;
  height?: number | string;
}

const CreatorResultList = <TCreator extends CreatorIdentity>({
  creators,
  onSelect,
  loading = false,
  loadingLabel = '...',
  emptyLabel,
  className,
  itemClassName,
  getKey = (creator, index) => creator.alkotoAzonosito || index,
  getOptionId,
  isDisabled = () => false,
  isSelected = () => false,
  activeIndex = -1,
  preventMouseDown = false,
  rowClassName,
  rowSize = 'md',
  rowTone = 'default',
  virtualized = false,
  virtuosoRef,
  height,
}: CreatorResultListProps<TCreator>) => {
  const renderItem = (index: number) => {
    const creator = creators[index];
    if (!creator) return null;

    const active = index === activeIndex;
    const disabled = isDisabled(creator, index);
    const selected = isSelected(creator, index);
    const state = { creator, index, active, disabled, selected };

    return (
      <button
        key={getKey(creator, index)}
        id={getOptionId?.(index)}
        type="button"
        role="option"
        aria-selected={active || selected}
        aria-disabled={disabled || undefined}
        disabled={disabled}
        onMouseDown={
          preventMouseDown
            ? (event) => {
                event.preventDefault();
              }
            : undefined
        }
        onClick={() => {
          if (disabled) return;
          onSelect(creator, index);
        }}
        className={cn(
          'block w-full overflow-hidden px-3 py-2 text-left transition',
          disabled && 'cursor-not-allowed opacity-40',
          typeof itemClassName === 'function' ? itemClassName(state) : itemClassName
        )}
      >
        <CreatorIdentityRow
          creator={creator}
          size={rowSize}
          tone={rowTone}
          className={rowClassName}
        />
      </button>
    );
  };

  if (loading) {
    return <div className={cn('p-3 text-sm text-[#151720]/60', className)}>{loadingLabel}</div>;
  }

  if (creators.length === 0) {
    return <div className={cn('p-3 text-sm text-[#151720]/60', className)}>{emptyLabel}</div>;
  }

  if (virtualized) {
    return (
      <Virtuoso
        ref={virtuosoRef}
        className={className}
        style={{ height }}
        totalCount={creators.length}
        computeItemKey={(index) => getKey(creators[index], index)}
        itemContent={renderItem}
      />
    );
  }

  return <div className={className}>{creators.map((_, index) => renderItem(index))}</div>;
};

export default CreatorResultList;
