import { useStream } from '@/hooks/useStream';
import { useUIStore } from '@/stores/uiStore';
import type { CameraConfig } from '@/types/config';

interface CameraGridCellProps {
  camera: CameraConfig;
  delayMs: number;
}

export function CameraGridCell({ camera, delayMs }: CameraGridCellProps) {
  const setFullscreen = useUIStore((s) => s.setFullscreenCamera);

  const { videoRef, isConnecting, error, retry } = useStream({
    streamName: camera.name,
    delayMs,
  });

  return (
    <div
      className="relative bg-dark-tertiary rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-accent/50 transition-all"
      onClick={() => setFullscreen(camera.name)}
    >
      <video
        ref={videoRef}
        autoPlay
        muted
        playsInline
        className="w-full h-full object-cover"
      />

      {/* Loading */}
      {isConnecting && (
        <div className="absolute inset-0 flex items-center justify-center bg-dark-primary/80">
          <div className="flex flex-col items-center gap-2">
            <div className="w-6 h-6 border-2 border-accent border-t-transparent rounded-full animate-spin" />
            <span className="text-xs text-gray-400">{camera.display_name}</span>
          </div>
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="absolute inset-0 flex items-center justify-center bg-dark-primary/80">
          <div className="flex flex-col items-center gap-2 p-2">
            <svg className="w-6 h-6 text-status-error" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <span className="text-xs text-gray-400">{camera.display_name}</span>
            <span className="text-xs text-status-error">{error}</span>
            <button onClick={(e) => { e.stopPropagation(); retry(); }} className="text-xs text-accent hover:underline">
              Retry
            </button>
          </div>
        </div>
      )}

      {/* Label */}
      {!isConnecting && !error && (
        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent px-2 py-1.5">
          <span className="text-xs font-medium text-white/90 truncate block">
            {camera.display_name}
          </span>
        </div>
      )}
    </div>
  );
}
