'use client';

import clsx from 'clsx';
import React, { useState } from 'react';

import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { Clip } from '@/state/clipStore';

interface MobileLyricsContainerProps {
  clip: Clip;
  className?: string;
}

export const MobileLyricsContainer: React.FC<MobileLyricsContainerProps> = ({
  clip,
  className,
}) => {
  const [copyStatus, setCopyStatus] = useState<
    'idle' | 'copying' | 'success' | 'error'
  >('idle');

  // Get lyrics from clip metadata
  const lyricsText = clip?.metadata?.prompt || '';

  const copyLyricsToClipboard = async (lyrics: string) => {
    setCopyStatus('copying');

    try {
      // Check if Clipboard API is available
      if (!navigator.clipboard) {
        throw new Error('Clipboard API not supported');
      }

      // Check if we're in a secure context (HTTPS or localhost)
      if (!window.isSecureContext) {
        throw new Error(
          'Clipboard API requires secure context (HTTPS or localhost)'
        );
      }

      await navigator.clipboard.writeText(lyrics);
      setCopyStatus('success');

      // Reset status after 2 seconds
      setTimeout(() => setCopyStatus('idle'), 2000);
    } catch (error) {
      console.error('Failed to copy lyrics to clipboard:', error);

      // Fallback: try using document.execCommand for older browsers
      try {
        const textArea = document.createElement('textarea');
        textArea.value = lyrics;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        const successful = document.execCommand('copy');
        document.body.removeChild(textArea);

        if (successful) {
          setCopyStatus('success');
          setTimeout(() => setCopyStatus('idle'), 2000);
          return;
        }
      } catch (fallbackError) {
        console.error('Fallback copy method also failed:', fallbackError);
      }

      setCopyStatus('error');

      // Reset status after 3 seconds
      setTimeout(() => setCopyStatus('idle'), 3000);
    }
  };

  if (!lyricsText?.trim()) {
    return (
      <div
        className={clsx(
          'mx-4 mb-6 rounded-xl p-6',
          'border-[0.5px] border-white/10 bg-[rgba(255,255,255,0.10)] text-foreground-primary backdrop-blur-sm',
          className
        )}
      >
        <div className='text-center text-sm text-gray-400'>
          No lyrics available
        </div>
      </div>
    );
  }

  return (
    <div
      className={clsx(
        'mx-4 overflow-hidden rounded-xl',
        'border-[0.5px] border-white/10 bg-[rgba(255,255,255,0.10)] text-foreground-primary backdrop-blur-sm',
        className
      )}
      style={{
        position: 'relative',
        zIndex: 0,
      }}
    >
      {/* Header */}
      <div className='flex items-center justify-between px-4 py-3'>
        <h3 className='text-base font-medium text-white'>Lyrics</h3>
        <button
          className='text-white opacity-50 transition-colors disabled:cursor-not-allowed'
          onClick={() => {
            if (lyricsText && copyStatus === 'idle') {
              copyLyricsToClipboard(lyricsText);
            }
          }}
          disabled={copyStatus !== 'idle'}
          title={
            copyStatus === 'copying'
              ? 'Copying...'
              : copyStatus === 'success'
                ? 'Copied!'
                : copyStatus === 'error'
                  ? 'Failed to copy'
                  : 'Copy lyrics'
          }
        >
          {copyStatus === 'copying' ? (
            <SpinnerSVG className='h-6 w-6 text-white' />
          ) : copyStatus === 'success' ? (
            <svg
              width='16'
              height='16'
              viewBox='0 0 24 24'
              fill='currentColor'
              className='text-white'
            >
              <path d='M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z' />
            </svg>
          ) : copyStatus === 'error' ? (
            <svg
              width='16'
              height='16'
              viewBox='0 0 24 24'
              fill='currentColor'
              className='text-white'
            >
              <path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z' />
            </svg>
          ) : (
            <svg width='16' height='16' viewBox='0 0 24 24' fill='currentColor'>
              <path d='M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z' />
            </svg>
          )}
        </button>
      </div>

      {/* Lyrics Content */}
      <div className='space-y-0 px-4 py-4'>
        <div className='text-sm leading-6 whitespace-pre-line text-white'>
          {lyricsText}
        </div>
      </div>
    </div>
  );
};

export default MobileLyricsContainer;
