/**
 * LottiePlayer Component
 *
 * Universal Lottie animation player component
 */

'use client';

import React from 'react';
import Lottie from 'react-lottie-player';

import { LottiePlayerProps } from './types';
import { useLottie } from './useLottie';

// Size presets mapping
const SIZE_PRESETS = {
  xs: { width: 64, height: 64 },
  sm: { width: 128, height: 128 },
  md: { width: 256, height: 256 },
  lg: { width: 384, height: 384 },
  xl: { width: 512, height: 512 },
  full: { width: '100%', height: '100%' },
} as const;

/**
 * LottiePlayer component for displaying Lottie animations
 *
 * Features:
 * - Loads animations from URLs or objects
 * - Size presets or custom dimensions
 * - Playback controls (speed, direction, loop)
 * - Loading and error states
 * - Event callbacks
 *
 * Usage:
 * ```tsx
 * // From URL with size preset
 * <LottiePlayer
 *   src="https://example.com/animation.json"
 *   size="md"
 *   autoplay
 *   loop
 * />
 *
 * // From object with custom size
 * <LottiePlayer
 *   src={animationData}
 *   width={300}
 *   height={300}
 *   speed={1.5}
 *   controls
 * />
 *
 * // With callbacks
 * <LottiePlayer
 *   src="https://example.com/animation.json"
 *   onLoad={() => console.log('Animation loaded')}
 *   onComplete={() => console.log('Animation completed')}
 *   onError={(err) => console.error('Error:', err)}
 * />
 * ```
 */
export function LottiePlayer({
  src,
  size = 'md',
  width,
  height,
  autoplay = true,
  loop = true,
  speed = 1,
  direction = 1,
  controls = false,
  background,
  className,
  showLoading = true,
  onComplete,
  onLoad,
  onError,
}: LottiePlayerProps) {
  // Load animation data using our custom hook
  const { animationData, isLoading, error, retry } = useLottie({ src });

  // Notify parent about load state
  React.useEffect(() => {
    if (animationData && onLoad) {
      onLoad();
    }
  }, [animationData, onLoad]);

  // Notify parent about errors
  React.useEffect(() => {
    if (error && onError) {
      onError(error);
    }
  }, [error, onError]);

  // Determine dimensions
  const dimensions = React.useMemo(() => {
    // Custom dimensions override size preset
    if (width !== undefined || height !== undefined) {
      return {
        width: width ?? SIZE_PRESETS[size].width,
        height: height ?? SIZE_PRESETS[size].height,
      };
    }

    // Use size preset
    return SIZE_PRESETS[size];
  }, [size, width, height]);

  // Handle complete event
  const handleComplete = React.useCallback(() => {
    if (onComplete) {
      onComplete();
    }
  }, [onComplete]);

  // Loading state
  if (isLoading && showLoading) {
    return (
      <div
        className={`flex items-center justify-center ${className || ''}`}
        style={{
          width: dimensions.width,
          height: dimensions.height,
          background: background || 'transparent',
        }}
      >
        <div className="flex flex-col items-center gap-2">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-gray-900" />
          <span className="text-sm text-gray-500">Loading animation...</span>
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div
        className={`flex items-center justify-center ${className || ''}`}
        style={{
          width: dimensions.width,
          height: dimensions.height,
          background: background || 'transparent',
        }}
      >
        <div className="flex flex-col items-center gap-2 p-4 text-center">
          <svg
            className="h-8 w-8 text-red-500"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
          <div className="text-sm text-red-600">{error.message}</div>
          <button
            onClick={retry}
            className="rounded bg-red-100 px-3 py-1 text-sm text-red-700 hover:bg-red-200"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  // No animation data
  if (!animationData) {
    return null;
  }

  // Render the Lottie player
  return (
    <div
      className={className}
      style={{
        width: dimensions.width,
        height: dimensions.height,
        background: background || 'transparent',
      }}
    >
      <Lottie
        animationData={animationData}
        play={autoplay}
        loop={loop}
        speed={speed}
        direction={direction}
        style={{
          width: '100%',
          height: '100%',
        }}
        onComplete={handleComplete}
        rendererSettings={{
          preserveAspectRatio: 'xMidYMid meet',
        }}
      />
      {controls && (
        <div className="mt-2 flex items-center justify-center gap-2">
          <span className="text-xs text-gray-500">
            Speed: {speed}x | Direction: {direction === 1 ? 'Forward' : 'Reverse'}
          </span>
        </div>
      )}
    </div>
  );
}
