'use client';

import { LoaderCircle, Pause, Play, RotateCcw } from 'lucide-react';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@djangocfg/ui-core/components';
import { usePlayerControls, usePlayerState } from '../../context/selectors';

type Props = { size?: 'default' | 'compact' };

export function PlayButton({ size = 'default' }: Props) {
  const state = usePlayerState();
  const { toggle, play } = usePlayerControls();

  const dim = size === 'compact' ? 28 : 36;
  const icon = size === 'compact' ? 14 : 16;

  let label = 'Play';
  let Icon: React.ComponentType<{ size?: number; strokeWidth?: number; className?: string }> = Play;
  let onClick: () => void = () => void toggle();
  let disabled = false;

  switch (state.kind) {
    case 'idle':
      Icon = Play;
      disabled = true;
      break;
    case 'loading':
    case 'decoding':
      Icon = LoaderCircle;
      label = 'Loading';
      disabled = true;
      break;
    case 'playing':
      Icon = Pause;
      label = 'Pause';
      break;
    case 'paused':
      Icon = Play;
      label = 'Play';
      break;
    case 'ended':
      Icon = RotateCcw;
      label = 'Replay';
      onClick = () => void play();
      break;
    case 'error':
      Icon = Play;
      label = 'Retry';
      onClick = () => void play();
      break;
  }

  const button = (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      aria-label={label}
      className="audioplayer-press grid place-items-center rounded-full bg-foreground text-background transition-colors hover:bg-foreground/90 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
      style={{ width: dim, height: dim }}
    >
      <Icon
        size={icon}
        strokeWidth={2}
        className={state.kind === 'loading' || state.kind === 'decoding' ? 'animate-spin' : ''}
      />
    </button>
  );

  return (
    <Tooltip>
      <TooltipTrigger asChild>{button}</TooltipTrigger>
      <TooltipContent side="top">
        <span className="flex items-center gap-1.5">
          {label}
          <kbd className="rounded border border-border/40 bg-muted px-1 font-mono text-[10px] text-muted-foreground">
            Space
          </kbd>
        </span>
      </TooltipContent>
    </Tooltip>
  );
}
