import { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import Picker from '@emoji-mart/react';
import data from '@emoji-mart/data';
import { Search, TrendingUp, Loader2, Clock, Grid } from 'lucide-react';
import { useLang } from '../../../../core/infrastructure/i18n';
import { useAuthStore } from '../../../auth/application/authStore';
import { AppApi } from '../../../../core/infrastructure/appApi';

interface KlipyGif {
  id: string;
  files?: any;
  file?: any;
  media_formats?: any;
  media?: any;
  images?: any;
  title?: string;
}

interface GifCategory {
  category: string;
  query: string;
  preview_url: string;
}

interface EmojiPickerProps {
  onSelect: (emoji: string) => void;
  onSelectGif?: (url: string, preview: string) => void;
  onClose: () => void;
}

type GifMode = 'recent' | 'trending' | 'categories' | 'search';

const CATEGORY_TRANSLATIONS: Record<string, string> = {
  'hello': 'Привет',
  'lol': 'Лол',
  'love': 'Любовь',
  'happy birthday': 'С днем рождения',
  'thank you': 'Спасибо',
  'excited': 'Восторг',
  'smile': 'Улыбка',
  'aww': 'Мило',
  'high five': 'Дай пять',
  'good morning': 'Доброе утро',
  'good night': 'Спокойной ночи',
  'yes': 'Да',
  'no': 'Нет',
  'ok': 'Ок',
  'sorry': 'Прости',
  'please': 'Пожалуйста',
  'wow': 'Вау',
  'dance': 'Танцы',
  'hungry': 'Голоден',
  'scared': 'Страшно',
  'tired': 'Устал',
  'sad': 'Грустно',
  'party': 'Вечеринка',
  'cry': 'Плачу',
  'cool': 'Круто'
};

export default function EmojiPicker({ onSelect, onSelectGif, onClose }: EmojiPickerProps) {
  const { lang, t } = useLang();
  const { config } = useAuthStore();
  
  // Persist only the main tab type, but reset GIF sub-mode to 'recent' on entry
  const [tab, setTab] = useState<'emoji' | 'gif'>(() => {
    return (localStorage.getItem('emojiPicker_tab') as any) || 'emoji';
  });
  const [gifMode, setGifMode] = useState<GifMode>('recent');
  
  useEffect(() => {
    localStorage.setItem('emojiPicker_tab', tab);
  }, [tab]);

  const [gifQuery, setGifQuery] = useState('');
  const [gifs, setGifs] = useState<KlipyGif[]>([]);
  const [gifLoading, setGifLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  
  const [trendingGifs, setTrendingGifs] = useState<KlipyGif[]>([]);
  const [trendingPage, setTrendingPage] = useState(1);
  const [trendingHasMore, setTrendingHasMore] = useState(true);

  const [recentGifs, setRecentGifs] = useState<KlipyGif[]>([]);
  const [recentPage, setRecentPage] = useState(1);
  const [recentHasMore, setRecentHasMore] = useState(true);

  const [categories, setCategories] = useState<GifCategory[]>([]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);

  const gifSearchRef = useRef<HTMLInputElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  const initialFetchDone = useRef({ trending: false, categories: false, recent: false });

  const extractGifs = (d: any): KlipyGif[] => {
    if (!d) return [];
    let list: any[] = [];
    if (d.data && Array.isArray(d.data.data)) list = d.data.data;
    else if (Array.isArray(d.data)) list = d.data;
    else if (Array.isArray(d.result)) list = d.result;
    else if (d.result && Array.isArray(d.result.data)) list = d.result.data;
    else if (Array.isArray(d)) list = d;
    else if (Array.isArray(d.gifs)) list = d.gifs;
    
    return list.filter(g => g && typeof g === 'object' && (g.id || g.media || g.files || g.file));
  };

  const checkHasMore = (d: any): boolean => {
    if (!d) return false;
    if (d.data && typeof d.data.has_next === 'boolean') return d.data.has_next;
    const meta = d.data?.meta || d.meta || d.result?.meta;
    if (meta) {
      if (typeof meta.has_more === 'boolean') return meta.has_more;
      if (typeof meta.has_next === 'boolean') return meta.has_next;
      if (typeof meta.last_page === 'number' && typeof meta.current_page === 'number') {
         return meta.current_page < meta.last_page;
      }
    }
    const count = extractGifs(d).length;
    return count >= 20; 
  };

  const fetchTrending = useCallback((p: number) => {
    if (!config?.klipy?.enabled) return;
    setGifLoading(true);
    AppApi.getTrendingGifs(p)
      .then(d => { 
        const newGifs = extractGifs(d);
        setTrendingGifs(prev => p === 1 ? newGifs : [...prev, ...newGifs]); 
        setTrendingHasMore(checkHasMore(d));
      })
      .catch(console.error)
      .finally(() => setGifLoading(false));
  }, [config?.klipy?.enabled]);

  const fetchRecent = useCallback((p: number) => {
    if (!config?.klipy?.enabled) return;
    setGifLoading(true);
    AppApi.getRecentGifs(p)
      .then(d => {
        const newGifs = extractGifs(d);
        setRecentGifs(prev => p === 1 ? newGifs : [...prev, ...newGifs]);
        setRecentHasMore(checkHasMore(d));
        
        // Auto-switch to trending if history is empty on first load
        if (p === 1 && newGifs.length === 0 && gifMode === 'recent') {
          setGifMode('trending');
        }
      })
      .catch(console.error)
      .finally(() => setGifLoading(false));
  }, [config?.klipy?.enabled, gifMode]);

  const fetchCategories = useCallback(() => {
    if (!config?.klipy?.enabled) return;
    setCategoriesLoading(true);
    AppApi.getGifCategories('RU')
      .then(d => {
        if (d.data && Array.isArray(d.data.categories)) {
          setCategories(d.data.categories);
        }
      })
      .catch(console.error)
      .finally(() => setCategoriesLoading(false));
  }, [config?.klipy?.enabled]);

  const searchGifs = useCallback((q: string, p: number) => {
    if (!config?.klipy?.enabled || !q.trim()) { 
      setGifs([]); 
      return; 
    }
    setGifLoading(true);
    AppApi.searchKlipyGifs(q, p)
      .then(d => { 
        const newGifs = extractGifs(d);
        setGifs(prev => p === 1 ? newGifs : [...prev, ...newGifs]);
        setHasMore(checkHasMore(d));
      })
      .catch(console.error)
      .finally(() => setGifLoading(false));
  }, [config?.klipy?.enabled]);

  useEffect(() => {
    if (tab === 'gif' && config?.klipy?.enabled) {
      if (!initialFetchDone.current.trending) {
        initialFetchDone.current.trending = true;
        fetchTrending(1);
      }
      if (!initialFetchDone.current.categories) {
        initialFetchDone.current.categories = true;
        fetchCategories();
      }
      if (!initialFetchDone.current.recent) {
        initialFetchDone.current.recent = true;
        fetchRecent(1);
      }
    }
  }, [tab, config?.klipy?.enabled, fetchTrending, fetchCategories, fetchRecent]);

  // Handle switching to recent tab to refresh it
  useEffect(() => {
    if (tab === 'gif' && gifMode === 'recent') {
      fetchRecent(1);
    }
  }, [gifMode, tab, fetchRecent]);

  const handleGifSearch = (q: string) => {
    setGifQuery(q);
    setPage(1);
    setHasMore(true);
    if (!q.trim()) {
        setGifMode('trending');
        return;
    }
    setGifMode('search');
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => searchGifs(q, 1), 400);
  };

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    if (gifLoading) return;
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
    if (scrollTop + clientHeight >= scrollHeight - 400) {
      if (gifMode === 'search' && hasMore) {
        const nextPage = page + 1;
        setPage(nextPage);
        searchGifs(gifQuery, nextPage);
      } else if (gifMode === 'trending' && trendingHasMore) {
        const n = trendingPage + 1;
        setTrendingPage(n);
        fetchTrending(n);
      } else if (gifMode === 'recent' && recentHasMore) {
        const n = recentPage + 1;
        setRecentPage(n);
        fetchRecent(n);
      }
    }
  };

  const getGifUrl = (gif: any): string => {
    return gif.files?.hd?.gif?.url || gif.files?.sd?.gif?.url 
        || gif.file?.hd?.gif?.url || gif.file?.sd?.gif?.url 
        || gif.media_formats?.gif?.url || gif.media?.[0]?.gif?.url 
        || gif.images?.original?.url || '';
  };

  const getGifPreview = (gif: any, fullUrl: string): string => {
    return gif.files?.sd?.webp?.url || gif.files?.sd?.gif?.url 
        || gif.file?.sd?.webp?.url || gif.file?.sd?.gif?.url 
        || gif.media_formats?.tinygif?.url || gif.media?.[0]?.tinygif?.url 
        || gif.images?.fixed_height_small?.url || fullUrl;
  };

  const pickGif = (gif: KlipyGif) => {
    const url = getGifUrl(gif);
    const preview = getGifPreview(gif, url);
    if (onSelectGif && url) {
      onSelectGif(url, preview);
      // Mark as shared with Klipy trigger API
      AppApi.markGifShared(gif.id, gifMode === 'search' ? gifQuery : '')
        .then(() => fetchRecent(1)) // Refresh history immediately after sharing
        .catch(console.error);
    }
  };

  const anchorRef = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState<{ top: number; left: number } | null>(null);

  useEffect(() => {
    const update = () => {
      const el = anchorRef.current?.parentElement;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const w = 400;
      let left = rect.right - w;
      if (left < 8) left = 8;
      setPos({ top: rect.top - 8, left });
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, [tab]);

  const displayGifs = gifMode === 'search' ? gifs : gifMode === 'recent' ? recentGifs : trendingGifs;
  const currentHasMore = gifMode === 'search' ? hasMore : gifMode === 'recent' ? recentHasMore : trendingHasMore;

  const translateCategory = (cat: string) => {
    if (lang !== 'ru') return cat;
    return CATEGORY_TRANSLATIONS[cat.toLowerCase()] || cat;
  };

  return (
    <>
      <div ref={anchorRef} className="hidden" />
      {createPortal(
        <>
          <div className="fixed inset-0 z-[9990]" onClick={onClose} />
          <div
            className="fixed z-[9991] rounded-[2rem] shadow-[0_32px_64px_-16px_rgba(0,0,0,0.6)] border border-white/10 overflow-hidden flex flex-col backdrop-blur-3xl"
            onClick={(e) => e.stopPropagation()}
            style={{
              width: 400,
              height: 520,
              bottom: pos ? `${window.innerHeight - pos.top}px` : undefined,
              left: pos ? pos.left : undefined,
              background: 'rgba(19, 19, 19, 0.85)',
              visibility: pos ? 'visible' : 'hidden',
            }}
          >
            {/* Main Tabs */}
            <div className="flex p-2 gap-1 bg-black/20 backdrop-blur-md flex-shrink-0">
              <button
                onClick={() => setTab('emoji')}
                className={`flex-1 py-3 text-[12px] font-black uppercase tracking-widest rounded-xl transition-all duration-300 ${tab === 'emoji' ? 'bg-primary/20 text-primary shadow-[0_0_20px_rgba(154,203,255,0.15)]' : 'text-zinc-500 hover:text-white hover:bg-white/5'}`}
              >
                {lang === 'ru' ? 'Эмодзи' : 'Emojis'}
              </button>
              {config?.klipy?.enabled && (
                <button
                  onClick={() => { setTab('gif'); setTimeout(() => gifSearchRef.current?.focus(), 100); }}
                  className={`flex-1 py-3 text-[12px] font-black uppercase tracking-widest rounded-xl transition-all duration-300 ${tab === 'gif' ? 'bg-primary/20 text-primary shadow-[0_0_20px_rgba(154,203,255,0.15)]' : 'text-zinc-500 hover:text-white hover:bg-white/5'}`}
                >
                  GIF
                </button>
              )}
            </div>

            {tab === 'emoji' && (
                <div className="flex-1 overflow-hidden">
                  <Picker
                    data={data}
                    onEmojiSelect={(e: { native: string }) => onSelect(e.native)}
                    theme="dark"
                    locale={lang === 'ru' ? 'ru' : 'en'}
                    set="native"
                    previewPosition="none"
                    skinTonePosition="search"
                    perLine={10}
                    emojiSize={26}
                    emojiButtonSize={34}
                    maxFrequentRows={2}
                    navPosition="top"
                    dynamicWidth={false}
                    background="transparent"
                  />
                </div>
            )}

            {config?.klipy?.enabled && tab === 'gif' && (
              <div className="flex flex-col flex-1 min-h-0">
                {/* Search Bar */}
                <div className="px-3 pt-2 pb-1 flex-shrink-0">
                  <div className="relative">
                    <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-500" />
                    <input
                      ref={gifSearchRef}
                      value={gifQuery}
                      onChange={(e) => handleGifSearch(e.target.value)}
                      placeholder={lang === 'ru' ? 'Поиск GIF...' : 'Search GIFs...'}
                      className="w-full pl-9 pr-3 py-2.5 rounded-xl bg-white/5 text-xs text-white placeholder-zinc-500 border border-white/5 focus:border-primary/50 outline-none transition-all shadow-inner"
                    />
                  </div>
                </div>

                {/* Sub-Tabs */}
                <div className="flex items-center gap-1 px-3 py-1 bg-black/10 flex-shrink-0">
                   <button 
                     onClick={() => { setGifMode('recent'); setGifQuery(''); }}
                     className={`p-2 rounded-lg transition-all ${gifMode === 'recent' ? 'text-primary bg-primary/20 shadow-lg' : 'text-zinc-500 hover:text-zinc-300 hover:bg-white/5'}`}
                     title={lang === 'ru' ? 'История' : 'History'}
                   >
                     <Clock size={16} />
                   </button>
                   <button 
                     onClick={() => { setGifMode('trending'); setGifQuery(''); }}
                     className={`p-2 rounded-lg transition-all ${gifMode === 'trending' ? 'text-primary bg-primary/20 shadow-lg' : 'text-zinc-500 hover:text-zinc-300 hover:bg-white/5'}`}
                     title={lang === 'ru' ? 'Тренды' : 'Trending'}
                   >
                     <TrendingUp size={16} />
                   </button>
                   <button 
                     onClick={() => { setGifMode('categories'); setGifQuery(''); }}
                     className={`p-2 rounded-lg transition-all ${gifMode === 'categories' ? 'text-primary bg-primary/20 shadow-lg' : 'text-zinc-500 hover:text-zinc-300 hover:bg-white/5'}`}
                     title={lang === 'ru' ? 'Категории' : 'Categories'}
                   >
                     <Grid size={16} />
                   </button>
                   {gifMode === 'search' && (
                      <div className="flex items-center gap-2 px-3 py-1 ml-auto rounded-full bg-primary/10 border border-primary/20 animate-in fade-in slide-in-from-right-2">
                          <Search size={10} className="text-primary" />
                          <span className="text-[10px] text-primary font-black uppercase truncate max-w-[100px] tracking-widest">{gifQuery}</span>
                      </div>
                   )}
                </div>

                {/* Content Area */}
                <div 
                  ref={scrollContainerRef}
                  onScroll={handleScroll}
                  className="flex-1 overflow-y-auto px-2 pt-1 pb-2 scroll-smooth custom-scrollbar"
                >
                  {gifMode === 'categories' ? (
                     categoriesLoading ? (
                        <div className="flex items-center justify-center py-20"><Loader2 size={32} className="text-primary animate-spin opacity-50" /></div>
                     ) : (
                        <div className="grid grid-cols-2 gap-2 p-1">
                           {categories.map((cat, i) => (
                              <button
                                key={i}
                                onClick={() => { setGifQuery(cat.query); handleGifSearch(cat.query); }}
                                className="relative aspect-[16/9] rounded-xl overflow-hidden group hover:ring-2 ring-primary/50 transition-all border border-white/5 bg-zinc-900 shadow-lg"
                              >
                                 <img src={cat.preview_url} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700 opacity-60" />
                                 <div className="absolute inset-0 flex items-center justify-center bg-black/20 group-hover:bg-black/80 transition-all duration-300">
                                    <span className="text-[10px] font-black uppercase tracking-[0.2em] text-white drop-shadow-[0_2px_4px_rgba(0,0,0,0.8)]">{translateCategory(cat.category)}</span>
                                 </div>
                                 <div className="absolute inset-0 bg-primary/10 opacity-0 group-hover:opacity-100 transition-opacity" />
                              </button>
                           ))}
                        </div>
                     )
                  ) : displayGifs.length === 0 && gifLoading ? (
                    <div className="flex items-center justify-center py-10"><Loader2 size={32} className="text-primary animate-spin opacity-50" /></div>
                  ) : (
                    <>
                      <div className="grid grid-cols-3 gap-1">
                        {displayGifs.map((gif, idx) => (
                          <button
                            key={`${gif.id}-${idx}-${gifMode}`}
                            onClick={() => { pickGif(gif); onClose(); }}
                            className="aspect-square w-full rounded-xl overflow-hidden hover:brightness-110 active:scale-95 transition-all bg-white/5 shadow-md border border-white/5 relative group"
                          >
                            <img
                              src={getGifPreview(gif, getGifUrl(gif))}
                              alt={gif.title || 'GIF'}
                              className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                              loading="lazy"
                            />
                            <div className="absolute inset-0 bg-primary/20 opacity-0 group-hover:opacity-100 transition-opacity" />
                          </button>
                        ))}
                      </div>
                      {gifLoading && (
                        <div className="flex items-center justify-center py-6"><Loader2 size={24} className="text-primary animate-spin" /></div>
                      )}
                      {!currentHasMore && !gifLoading && displayGifs.length > 0 && (
                          <p className="text-center text-[10px] text-zinc-600 py-4 uppercase tracking-widest font-black leading-none opacity-50">{lang === 'ru' ? 'Больше нет результатов' : 'No more results'}</p>
                      )}
                      {!gifLoading && displayGifs.length === 0 && (
                         <div className="flex flex-col items-center justify-center py-16 text-zinc-600 animate-in fade-in zoom-in-95 duration-500">
                            <Clock size={32} className="opacity-20 mb-3" />
                            <p className="text-xs font-bold uppercase tracking-widest opacity-40">{gifMode === 'recent' ? (lang === 'ru' ? 'Пусто в истории' : 'Empty history') : (lang === 'ru' ? 'Ничего не найдено' : 'Nothing found')}</p>
                         </div>
                      )}
                    </>
                  )}
                </div>
              </div>
            )}
          </div>
        </>,
        document.body
      )}
    </>
  );
}
