import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, ChevronLeft, ChevronRight, Eye, Trash2, MoreHorizontal, Send, Smile, UserIcon, Volume2, VolumeX } from 'lucide-react';
import EmojiOnlyPicker from './EmojiOnlyPicker';
import { useAuthStore } from '../../../auth/application/authStore';
import { StoryApi } from '../../infrastructure/storyApi';
import { getSocket } from '../../../../core/infrastructure/socket';
import { useLang } from '../../../../core/infrastructure/i18n';
import Avatar from '../../../../core/presentation/components/ui/Avatar';
import { StoryGroup } from '../../../../core/domain/types';
import { getMediaUrl } from '../../../../core/utils/utils';

const STORY_REACTIONS = [
  { emoji: '🔥', label: 'fire' },
  { emoji: '❤️', label: 'heart' },
  { emoji: '😂', label: 'laugh' },
  { emoji: '😮', label: 'wow' },
  { emoji: '🙌', label: 'praise' },
];

interface StoryViewerProps {
  stories: StoryGroup[];
  initialUserIndex: number;
  initialStoryIndex?: number;
  onClose: () => void;
  onRefresh: () => void;
}

export default function StoryViewer({ stories, initialUserIndex, initialStoryIndex, onClose, onRefresh }: StoryViewerProps) {
  const { user } = useAuthStore();
  const { t } = useLang();
  const [userIndex, setUserIndex] = useState(initialUserIndex);
  const [storyIndex, setStoryIndex] = useState(initialStoryIndex || 0);
  const [progress, setProgress] = useState(0);
  const [paused, setPaused] = useState(false);
  const [isInputFocused, setIsInputFocused] = useState(false);
  const [lastPressTime, setLastPressTime] = useState(0);
  const timerRef = useRef<ReturnType<typeof setInterval>>(undefined);
  const viewedRef = useRef<Set<string>>(new Set());
  const [viewOverrides, setViewOverrides] = useState<Record<string, { viewCount: number; viewed: boolean }>>({});
  const videoRef = useRef<HTMLVideoElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const [isMuted, setIsMuted] = useState(true);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  
  // Scroll Lock implementation
  useEffect(() => {
    const originalStyle = window.getComputedStyle(document.body).overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = originalStyle;
    };
  }, []);

  const STORY_DURATION = 5000;
  const TICK = 50;

  const [viewers, setViewers] = useState<Array<{ userId: string; username: string; displayName: string; avatar: string | null; viewedAt: string }>>([]);
  const [viewersLoading, setViewersLoading] = useState(false);
  const [quickReply, setQuickReply] = useState('');
  const [isSendingReply, setIsSendingReply] = useState(false);

  const currentUser = stories[userIndex];
  const currentStoryRaw = currentUser?.stories?.[storyIndex];
  const currentStory = currentStoryRaw ? {
    ...currentStoryRaw,
    ...viewOverrides[currentStoryRaw.id]
  } : null;

  const storyTypeStr = String(currentStory?.type || '').toLowerCase();
  const isVideo = storyTypeStr === 'video' || storyTypeStr === '1';
  const isImage = storyTypeStr === 'image' || storyTypeStr === '0';
  
  // If author muted the video, we force mute it for everyone
  const forceMute = currentStory?.isMuted || false;
  const effectiveMuted = forceMute || isMuted;

  const metadata = useMemo(() => {
    if (!currentStory?.content) return null;
    try {
      return JSON.parse(currentStory.content);
    } catch {
      return null;
    }
  }, [currentStory?.content]);

  const trim = useMemo(() => metadata?.trim || null, [metadata]);

  useEffect(() => {
    if (currentUser?.user.id === user?.id) {
       setIsMuted(false);
       // Load viewers for own story
       if (currentStory) {
          setViewersLoading(true);
          StoryApi.getStoryViewers(currentStory.id).then(setViewers).finally(() => setViewersLoading(false));
       }
    } else {
       setIsMuted(true);
       setViewers([]);
    }
  }, [currentUser?.user.id, currentStory?.id, user?.id]);
  
  // Auto-resize textarea
  useEffect(() => {
    const el = inputRef.current;
    if (el) {
      el.style.height = '24px'; // Reset/Min height
      if (quickReply) {
        const newHeight = Math.max(24, Math.min(el.scrollHeight, 120));
        el.style.height = newHeight + 'px';
        el.style.overflowY = el.scrollHeight > 120 ? 'auto' : 'hidden';
      } else {
        el.style.overflowY = 'hidden';
      }
    }
  }, [quickReply]);

  const goNext = useCallback(() => {
    if (!currentUser) return;
    if (storyIndex < currentUser.stories.length - 1) {
      setStoryIndex(s => s + 1);
      setProgress(0);
    } else if (userIndex < stories.length - 1) {
      setUserIndex(u => u + 1);
      setStoryIndex(0);
      setProgress(0);
    } else {
      onClose();
    }
  }, [storyIndex, userIndex, currentUser, stories.length, onClose]);

  const goPrev = useCallback(() => {
    if (storyIndex > 0) {
      setStoryIndex(s => s - 1);
      setProgress(0);
    } else if (userIndex > 0) {
      setUserIndex(u => u - 1);
      const prevUser = stories[userIndex - 1];
      setStoryIndex(prevUser.stories.length - 1);
      setProgress(0);
    }
  }, [storyIndex, userIndex, stories]);

  useEffect(() => {
    if (paused || !currentStory || isVideo) return;
    
    const duration = STORY_DURATION;
    const step = (TICK / duration) * 100;
    
    timerRef.current = setInterval(() => {
      setProgress(prev => {
        if (prev >= 100) {
          goNext();
          return 0;
        }
        return prev + step;
      });
    }, TICK);

    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [storyIndex, userIndex, paused, goNext, isVideo, currentStory]);

  useEffect(() => {
    const video = videoRef.current;
    if (!video || !isVideo) return;

    if (trim && Math.abs(video.currentTime - trim.start) > 0.5 && video.currentTime < trim.start) {
        video.currentTime = trim.start;
    }

    if (paused) {
      video.pause();
    } else {
      video.play().catch(console.error);
    }

    const interval = setInterval(() => {
      if (video.duration) {
        if (trim) {
            const start = trim.start || 0;
            const end = trim.end || video.duration;
            const current = video.currentTime;
            
            setProgress(Math.min(100, Math.max(0, ((current - start) / (end - start)) * 100)));
            
            if (current >= end) {
                goNext();
            }
        } else {
            setProgress((video.currentTime / video.duration) * 100);
        }
      }
    }, TICK);

    return () => clearInterval(interval);
  }, [isVideo, paused, storyIndex, userIndex, trim, goNext]);

  useEffect(() => {
    if (!currentStory || currentUser.user.id === user?.id) return;
    if (viewedRef.current.has(currentStory.id)) return;

    viewedRef.current.add(currentStory.id);
    StoryApi.viewStory(currentStory.id).then(() => {
      setViewOverrides(prev => ({
        ...prev,
        [currentStory.id]: {
          viewCount: (currentStory.viewCount || 0) + 1,
          viewed: true,
        },
      }));
    }).catch(console.error);
  }, [currentStory?.id, currentUser?.user.id, user?.id]);

  const handleReaction = async (emoji: string) => {
    if (!currentStory) return;
    try {
      await StoryApi.addStoryReaction(currentStory.id, emoji);
    } catch (e) {
      console.error(e);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendReply();
    }
  };

  const insertEmoji = (emoji: string) => {
    const el = inputRef.current;
    if (!el) return;
    const start = el.selectionStart;
    const end = el.selectionEnd;
    const text = quickReply;
    const newText = text.substring(0, start) + emoji + text.substring(end);
    setQuickReply(newText);
    setShowEmojiPicker(false);
    setTimeout(() => {
      el.focus();
      const pos = start + emoji.length;
      el.setSelectionRange(pos, pos);
    }, 0);
  };

  const handleSendReply = async () => {
    if (!currentStory || !quickReply.trim() || isSendingReply) return;
    setIsSendingReply(true);
    try {
      await StoryApi.addStoryReply(currentStory.id, quickReply.trim());
      setQuickReply('');
    } catch (e) {
      console.error(e);
    } finally {
      setIsSendingReply(false);
    }
  };

  const handleDelete = async () => {
    if (!currentStory) return;
    try {
      await StoryApi.deleteStory(currentStory.id);
      onRefresh();
      goNext();
    } catch (e) {
      console.error(e);
    }
  };

  if (!currentUser || !currentStory) return null;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-[100] bg-surface-container-lowest/90 backdrop-blur-3xl flex items-center justify-center font-body selection:bg-primary/30"
    >
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Dancing+Script:wght@700&family=Playfair+Display:ital,wght@1,900&family=Fira+Code:wght@700&family=Archivo+Black&display=swap');
      `}</style>
      {/* Background Shell Decoration */}
      <div className="fixed inset-0 pointer-events-none overflow-hidden -z-10 opacity-30">
        <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-primary/20 rounded-full blur-[120px]"></div>
        <div className="absolute bottom-1/4 right-1/4 w-[500px] h-[500px] bg-primary-container/20 rounded-full blur-[160px]"></div>
      </div>

      {/* Close Button Top Right */}
      <button 
        onClick={onClose}
        className="absolute top-8 right-12 p-4 rounded-full bg-surface-container-high/40 text-on-surface hover:bg-surface-variant transition-all active:scale-95 z-50 border border-white/5"
      >
        <X size={28} />
      </button>

      <div className="flex flex-row items-center gap-12 z-10 max-w-full px-4 w-full justify-center">
        <div 
          className="relative w-full aspect-[9/16] max-w-[500px] bg-surface-container-highest shadow-[20px_60px_100px_rgba(0,0,0,0.8)] overflow-hidden rounded-[3rem] ring-1 ring-white/10 flex flex-col group transition-transform duration-500"
        >
          {/* Navigation Overlay - Split into Left/Right Zones */}
          <div 
            className="absolute inset-0 z-20 flex cursor-pointer"
            onMouseDown={() => { setPaused(true); setLastPressTime(Date.now()); }}
            onMouseUp={() => { if (!isInputFocused) setPaused(false); }}
            onMouseLeave={() => { if (!isInputFocused) setPaused(false); }}
            onTouchStart={() => { setPaused(true); setLastPressTime(Date.now()); }}
            onTouchEnd={() => { if (!isInputFocused) setPaused(false); }}
          >
             <div className="w-1/3 h-full" onClick={(e) => { 
               e.stopPropagation(); 
               if (Date.now() - lastPressTime < 250) goPrev(); 
             }} />
             <div className="w-2/3 h-full" onClick={(e) => { 
               e.stopPropagation(); 
               if (Date.now() - lastPressTime < 250) goNext(); 
             }} />
          </div>
          {/* Progress Bars */}
          <div className="absolute top-6 inset-x-6 flex gap-1.5 z-40">
            {currentUser.stories.map((_, i) => (
              <div key={i} className="h-1 flex-1 bg-white/10 rounded-full overflow-hidden backdrop-blur-md">
                <div 
                  className="h-full bg-white rounded-full transition-none shadow-[0_0_8px_rgba(255,255,255,0.5)]"
                  style={{ width: i < storyIndex ? '100%' : i === storyIndex ? `${progress}%` : '0%' }}
                />
              </div>
            ))}
          </div>

          {/* Story Header */}
          <div className="absolute top-10 inset-x-6 flex items-center justify-between z-40 pointer-events-none">
            <div className="flex items-center gap-4">
              <Avatar 
                src={currentUser.user.avatarUrl || currentUser.user.avatar ? getMediaUrl(currentUser.user.avatarUrl || currentUser.user.avatar) : null}
                name={currentUser.user.displayName || currentUser.user.username || '?'}
                size="md"
                className="ring-2 ring-white/20 rounded-[1.25rem] shadow-xl"
              />
              <div className="flex flex-col">
                <p className="font-bold text-white text-base tracking-tight drop-shadow-md">
                  {currentUser.user.displayName || currentUser.user.username || ''}
                </p>
                <p className="text-[10px] text-white/60 font-black uppercase tracking-widest drop-shadow-sm">
                  {new Date(currentStory.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                </p>
              </div>
            </div>
            
            <div className="flex items-center gap-2 pointer-events-auto">
               {isVideo && !forceMute && (
                  <button 
                    onClick={(e) => { e.stopPropagation(); setIsMuted(!isMuted); }} 
                    className="p-2 text-white/60 hover:text-white transition-colors"
                    title={isMuted ? "Включить звук" : "Выключить звук"}
                  >
                    {isMuted ? <VolumeX size={20} /> : <Volume2 size={20} />}
                  </button>
               )}
               {currentUser.user.id === user?.id && (
                  <button onClick={handleDelete} className="p-2 text-white/40 hover:text-red-400 transition-colors">
                     <Trash2 size={20} />
                  </button>
               )}
            </div>
          </div>

          {/* Content Media */}
          <div className="relative flex-1 bg-surface-container-low overflow-hidden">
             {isVideo && currentStory.mediaUrl ? (
                <div className="w-full h-full flex items-center justify-center pointer-events-none" style={{ background: currentStory.bgColor || '#000' }}>
                  <video 
                    ref={videoRef}
                    src={getMediaUrl(currentStory.mediaUrl)}
                    className="w-full h-full object-contain"
                    autoPlay
                    muted={effectiveMuted}
                    playsInline
                  />
                </div>
             ) : (
                <img 
                  src={getMediaUrl(currentStory.mediaUrl!)}
                  alt="story"
                  className="w-full h-full object-cover transition-transform duration-1000 group-hover:scale-105 pointer-events-none"
                />
             )}
              {/* Overlays Layer */}
              {metadata && (
                <div className="absolute inset-0 pointer-events-none z-30">
                  {metadata.stickers?.map((s: any) => (
                    <div key={s.id} className="absolute" style={{ left: `${s.x}%`, top: `${s.y}%`, fontSize: `${s.scale * 40}px` }}>
                      {s.emoji}
                    </div>
                  ))}
                  {metadata.textObjects?.map((t: any) => (
                    <div key={t.id} className="absolute" style={{ left: `${t.x}%`, top: `${t.y}%`, color: t.color, fontFamily: t.font, fontSize: `${t.size}px`, transform: `scale(${t.scale})`, whiteSpace: 'nowrap', fontWeight: 'bold' }}>
                      {t.text}
                    </div>
                  ))}
                </div>
              )}

              {/* Legibility Gradient */}
              <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-black/40 pointer-events-none transition-opacity duration-300 group-hover:opacity-80" />
          </div>

             {/* Interactions Layer (Mobile-First Bottom) */}
             {currentUser.user.id !== user?.id && (
                <div className="absolute bottom-0 inset-x-0 p-8 space-y-8 z-30 translate-y-4 group-hover:translate-y-0 transition-transform duration-300">
                    {/* Reactions Row */}
                    <div className="flex items-center justify-center gap-5 translate-y-2 group-hover:translate-y-0 transition-all duration-500 delay-75">
                        {STORY_REACTIONS.map(({ emoji, label }) => (
                            <button 
                                key={label}
                                onClick={(e) => { e.stopPropagation(); handleReaction(emoji); }}
                                className="w-12 h-12 flex items-center justify-center bg-white/10 backdrop-blur-xl rounded-2xl hover:scale-125 hover:bg-white/20 transition-all duration-300 text-2xl shadow-xl border border-white/5 active:scale-90"
                            >
                                {emoji}
                            </button>
                        ))}
                    </div>

                    {/* Quick Reply Row */}
                    <div className="flex items-end gap-4 opacity-0 group-hover:opacity-100 transition-all duration-300 delay-150">
                        <div className="flex-1 min-h-[56px] flex items-center gap-2 bg-white/5 border border-white/10 rounded-2xl px-4 py-2 focus-within:bg-white/10 transition-all backdrop-blur-md relative">
                            <button
                                onClick={() => { 
                                    if (showEmojiPicker) {
                                        setShowEmojiPicker(false);
                                        inputRef.current?.focus();
                                    } else {
                                        setShowEmojiPicker(true);
                                        setPaused(true);
                                    }
                                }}
                                className="p-2 text-white/50 hover:text-white transition-colors flex-shrink-0"
                            >
                                <Smile size={20} />
                            </button>

                            <textarea
                                ref={inputRef}
                                value={quickReply}
                                onChange={(e) => setQuickReply(e.target.value)}
                                onKeyDown={handleKeyDown}
                                onFocus={() => { setPaused(true); setIsInputFocused(true); }}
                                onBlur={() => { setPaused(false); setIsInputFocused(false); }}
                                placeholder={(t('replyToStory') as string) || 'Ответить на историю...'}
                                className="flex-1 bg-transparent border-none text-sm text-white placeholder:text-white/40 focus:ring-0 focus:outline-none transition-all py-1 resize-none max-h-[120px] custom-scrollbar selection:bg-primary/30 overflow-hidden"
                                rows={1}
                                style={{ lineHeight: '24px', minHeight: '24px' }}
                            />
                            
                            {showEmojiPicker && (
                                <EmojiOnlyPicker
                                    onSelect={insertEmoji}
                                    onClose={() => {
                                        setShowEmojiPicker(false);
                                        inputRef.current?.focus();
                                    }}
                                />
                            )}
                        </div>
                        <button 
                            onClick={handleSendReply}
                            disabled={!quickReply.trim() || isSendingReply}
                            className="w-14 h-14 flex items-center justify-center bg-primary text-on-primary rounded-2xl hover:brightness-110 active:scale-95 transition-all shadow-lg shadow-primary/20 disabled:opacity-50 disabled:grayscale"
                        >
                            <Send size={20} />
                        </button>
                    </div>
                </div>
            )}
        </div>

        {/* Info Right Panel (Desktop) - Only show for current user's own stories */}
        {currentUser.user.id === user?.id && (
            <div className="hidden xl:flex flex-col w-[320px] space-y-6 self-start pt-4">
                {/* Viewers Panel */}
                <div className="p-8 rounded-[2rem] bg-surface-container-low/60 backdrop-blur-xl border border-white/5 space-y-6 shadow-2xl">
                    <div className="flex items-center justify-between">
                        <h3 className="text-[11px] font-black text-on-surface-variant uppercase tracking-[0.2em] opacity-40">
                            ПРОСМОТРЕЛИ
                        </h3>
                        <div className="px-2 py-0.5 rounded-full bg-primary/20 text-primary text-[10px] font-black">{currentStory.viewCount || 0}</div>
                    </div>

                    <div className="space-y-6">
                        {viewersLoading && <div className="text-[10px] text-zinc-500 font-bold uppercase tracking-widest animate-pulse">Загрузка...</div>}
                        <div className="space-y-4 max-h-[400px] overflow-y-auto custom-scrollbar pr-2">
                            {viewers.map((v) => (
                                <div key={v.userId} className="flex items-center gap-3 group transition-all">
                                    <Avatar 
                                        src={v.avatar ? getMediaUrl(v.avatar) : null}
                                        name={v.displayName || v.username || '?'}
                                        size="md"
                                        className="rounded-2xl border border-white/5 group-hover:scale-105 transition-transform"
                                    />
                                    <div className="flex-1 min-w-0">
                                        <p className="text-sm font-bold text-white truncate leading-tight">{v.displayName || v.username || '?'}</p>
                                        <p className="text-[10px] text-on-surface-variant font-medium tracking-wide uppercase opacity-70">@{v.username || ''}</p>
                                    </div>
                                </div>
                            ))}
                            {viewers.length === 0 && !viewersLoading && (
                                <div className="flex items-center gap-3 text-zinc-600">
                                    <UserIcon size={16} />
                                    <span className="text-[10px] font-bold uppercase tracking-widest">Просмотров нет</span>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        )}
      </div>
    </motion.div>
  );
}
