import { BookOpen, ChevronDown, ExternalLink, Play, RefreshCw, Star, X } from 'lucide-react';

import { useSignLanguageVideoModalState } from '@/business/sign-language/hooks';
import { buildSignLanguageYoutubeSearchUrl } from '@/business/sign-language/selectors';
import { Button } from '@/components/ui/button';
import {
  DEFAULT_SIGN_LANGUAGE_CATEGORY,
  SIGN_LANGUAGE_CATEGORY_COLORS,
  SIGN_LANGUAGE_LIFEPRINT_URL,
} from '@/shared/constants/signLanguage';
import type { SignItem } from '@/shared/types/app';
import { cn } from '@/lib/utils';

interface SignLanguageVideoModalProps {
  readonly sign: SignItem;
  readonly isLearned: boolean;
  readonly isSaving: boolean;
  readonly onClose: () => void;
  readonly onToggleLearned: (id: string) => Promise<void>;
}

export function SignLanguageVideoModal({
  sign,
  isLearned,
  isSaving,
  onClose,
  onToggleLearned,
}: SignLanguageVideoModalProps) {
  const state = useSignLanguageVideoModalState();
  const categoryColor =
    SIGN_LANGUAGE_CATEGORY_COLORS[sign.category] ?? SIGN_LANGUAGE_CATEGORY_COLORS[DEFAULT_SIGN_LANGUAGE_CATEGORY];
  const youtubeSearchUrl = buildSignLanguageYoutubeSearchUrl(sign.word);

  return (
    <div
      className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4"
      onClick={onClose}
      role="presentation"
    >
      <div
        className="bg-white rounded-2xl max-w-2xl w-full shadow-2xl overflow-hidden max-h-[90vh] flex flex-col"
        onClick={(event) => event.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-labelledby="sign-language-video-title"
      >
        <div className="flex items-center bg-gray-50 border-b border-gray-100 px-4 py-2">
          <div className="flex bg-gray-200 rounded-lg p-0.5 gap-0.5">
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => state.setViewMode('gif')}
              className={cn(
                'px-3 py-1.5 rounded-md text-xs font-semibold transition-all h-auto',
                state.viewMode === 'gif'
                  ? 'bg-white text-indigo-700 shadow-sm hover:bg-white'
                  : 'text-gray-500 hover:text-gray-700',
              )}
            >
              <RefreshCw size={10} />
              Animated Demo
            </Button>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => state.setViewMode('video')}
              className={cn(
                'px-3 py-1.5 rounded-md text-xs font-semibold transition-all h-auto',
                state.viewMode === 'video'
                  ? 'bg-white text-red-600 shadow-sm hover:bg-white'
                  : 'text-gray-500 hover:text-gray-700',
              )}
            >
              <Play size={10} />
              YouTube Video
            </Button>
          </div>
          <div className="ml-auto">
            <span className={cn(
              'inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold',
              categoryColor.bg,
              categoryColor.text,
            )}
            >
              {sign.category.replace('-', ' ')}
            </span>
          </div>
        </div>

        <div className="relative bg-gradient-to-br from-slate-900 to-slate-800 flex-shrink-0 min-h-[300px]">
          {state.viewMode === 'gif' ? (
            <div className="flex items-center justify-center p-6 min-h-[300px]">
              {!state.gifLoaded && !state.gifError && (
                <div className="absolute inset-0 flex items-center justify-center z-10">
                  <div className="text-center space-y-3">
                    <RefreshCw size={28} className="animate-spin text-indigo-400 mx-auto" />
                    <p className="text-white/60 text-sm">Loading demonstration...</p>
                  </div>
                </div>
              )}

              {!state.gifError ? (
                <img
                  src={sign.gifUrl}
                  alt={`Animated demonstration of ASL sign for "${sign.word}"`}
                  className={cn(
                    'max-h-[280px] object-contain rounded-lg transition-opacity duration-300',
                    state.gifLoaded ? 'opacity-100' : 'opacity-0',
                  )}
                  onLoad={state.markGifLoaded}
                  onError={state.markGifFailed}
                />
              ) : (
                <div className="flex flex-col items-center justify-center space-y-4">
                  <img
                    src={sign.image}
                    alt={`Sign for ${sign.word}`}
                    className="max-h-[240px] object-contain rounded-lg"
                  />
                  <p className="text-white/50 text-xs">Animated demo unavailable. Showing reference image.</p>
                </div>
              )}

              {state.gifLoaded && !state.gifError && (
                <div className="absolute bottom-3 left-3 flex items-center gap-1.5 px-2.5 py-1 bg-black/50 backdrop-blur-sm rounded-lg">
                  <RefreshCw size={10} className="text-emerald-400 animate-spin [animation-duration:3s]" />
                  <span className="text-[10px] text-white/80 font-medium">Looping</span>
                </div>
              )}
            </div>
          ) : (
            <div className="aspect-video w-full">
              <iframe
                src={`${sign.videoUrl}?autoplay=1&rel=0&modestbranding=1&playsinline=1`}
                title={`ASL Sign: ${sign.word}`}
                className="w-full h-full"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
              />
            </div>
          )}

          <Button
            type="button"
            variant="ghost"
            size="icon"
            onClick={onClose}
            aria-label="Close sign language video"
            className="absolute top-3 right-3 w-9 h-9 bg-black/50 hover:bg-black/70 rounded-full z-20"
          >
            <X size={18} className="text-white" />
          </Button>
        </div>

        <div className="p-5 space-y-4 overflow-y-auto">
          <div className="flex items-start justify-between gap-3">
            <div>
              <h3 id="sign-language-video-title" className="text-2xl font-bold text-gray-800">
                "{sign.word}"
              </h3>
              <p className="text-sm text-gray-500 mt-0.5">{sign.description}</p>
            </div>
            <div className="flex items-center gap-2 flex-wrap justify-end">
              {isLearned && (
                <span className="inline-flex items-center gap-1 px-3 py-1 bg-emerald-100 text-emerald-700 rounded-full text-xs font-semibold">
                  <Star size={12} className="fill-emerald-600" />
                  Learned
                </span>
              )}
              <Button asChild variant="ghost" size="sm" className="bg-red-50 text-red-600 hover:bg-red-100 rounded-full text-xs font-semibold h-auto px-3 py-1">
                <a href={youtubeSearchUrl} target="_blank" rel="noopener noreferrer">
                  <ExternalLink size={10} />
                  More on YouTube
                </a>
              </Button>
            </div>
          </div>

          {state.viewMode === 'gif' && (
            <div className="flex items-center gap-2 text-[10px] text-gray-400">
              <span>Animated demonstrations courtesy of</span>
              <a
                href={SIGN_LANGUAGE_LIFEPRINT_URL}
                target="_blank"
                rel="noopener noreferrer"
                className="text-indigo-500 hover:underline font-medium"
              >
                ASL University / Lifeprint.com
              </a>
              <span>Dr. Bill Vicars</span>
            </div>
          )}

          <Button
            type="button"
            variant="ghost"
            onClick={state.toggleStepGuide}
            className="w-full h-auto text-left justify-start bg-gray-50 hover:bg-gray-100 rounded-xl p-4 transition-colors"
            aria-expanded={state.showSteps}
          >
            <span className="w-full">
              <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider flex items-center justify-between">
                Step-by-Step Guide
                <ChevronDown className={cn('w-4 h-4 transition-transform', state.showSteps ? 'rotate-180' : '')} />
              </span>
              {state.showSteps && (
                <span className="block space-y-2 mt-3">
                  {sign.videoSteps.map((step) => (
                    <span
                      key={step.step}
                      className="flex items-start gap-3 p-2.5 rounded-lg bg-white border border-gray-100"
                    >
                      <span className="flex-shrink-0 w-7 h-7 rounded-full bg-indigo-500 text-white flex items-center justify-center text-xs font-bold">
                        {step.step}
                      </span>
                      <span className="text-sm text-gray-700 leading-snug">{step.instruction}</span>
                    </span>
                  ))}
                </span>
              )}
            </span>
          </Button>

          <div className="bg-amber-50 rounded-xl p-4 border border-amber-100">
            <h4 className="font-semibold text-amber-800 text-sm mb-1 flex items-center gap-2">
              <BookOpen size={14} />
              Teaching Tip
            </h4>
            <p className="text-sm text-amber-700">{sign.tip}</p>
          </div>

          <Button
            type="button"
            onClick={() => onToggleLearned(sign.id)}
            loading={isSaving}
            className={cn(
              'w-full flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-medium text-sm transition-all h-auto',
              isLearned
                ? 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                : 'bg-gradient-to-r from-emerald-500 to-emerald-600 text-white hover:shadow-lg hover:shadow-emerald-200',
            )}
          >
            <Star size={16} className={isLearned ? '' : 'fill-white'} />
            {isLearned ? 'Remove from Learned' : 'Mark as Learned'}
          </Button>
        </div>
      </div>
    </div>
  );
}
