import { useState, useEffect, useCallback } from 'react';
import type { FC } from 'react';
import { characters, conversations } from '../../api/client';
import { sortConversationsByDate, sortMessagesByDate, formatDateTR } from '../../types/telegram';
import type { CharacterSummary, Conversation, Message } from '../../types/telegram';
import { motion, AnimatePresence } from 'framer-motion';
import {
  ArrowLeft, Trash2, MessageSquare, Star, Users, Search,
  ChevronDown, Send, User,
} from 'lucide-react';

const Messages: FC = () => {
  const [charList, setCharList] = useState<CharacterSummary[]>([]);
  const [selectedCharId, setSelectedCharId] = useState<string | null>(null);
  const [convos, setConvos] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(true);
  const [convosLoading, setConvosLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [msgsLoading, setMsgsLoading] = useState(false);
  const [search, setSearch] = useState('');
  const [charDropdownOpen, setCharDropdownOpen] = useState(false);
  const [imgErrors, setImgErrors] = useState<Set<string>>(new Set());

  const getCharImgSrc = (charId: string) =>
    `/static/characters/${charId}/reference-images/master.jpg`;

  const handleImgError = (charId: string) => {
    setImgErrors(prev => new Set(prev).add(charId));
  };

  const renderCharAvatar = (char: CharacterSummary, size: 'sm' | 'md' = 'sm') => {
    const px = size === 'md' ? 'w-8 h-8' : 'w-7 h-7';
    const initial = (char.identity?.name ?? '?')[0].toUpperCase();

    if (imgErrors.has(char.id)) {
      return (
        <div className={`${px} rounded-full bg-gradient-to-br from-indigo-500/20 to-violet-500/20 border border-indigo-500/20 flex items-center justify-center shrink-0`}>
          <span className="text-[11px] font-semibold text-indigo-300">{initial}</span>
        </div>
      );
    }

    return (
      <div className={`${px} rounded-full shrink-0 relative overflow-hidden`}>
        <img
          src={getCharImgSrc(char.id)}
          alt={char.identity?.name ?? ''}
          className={`${px} rounded-full object-cover border border-white/[0.06]`}
          onError={() => handleImgError(char.id)}
        />
      </div>
    );
  };

  const fetchChars = useCallback(async () => {
    try {
      setLoading(true);
      const res = await characters.list();
      const data = res.data?.data ?? res.data ?? [];
      const list = Array.isArray(data) ? data : [];
      setCharList(list);
      if (list.length > 0 && !selectedCharId) setSelectedCharId(list[0].id);
    } catch {
      setError('Karakter listesi yüklenemedi.');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchChars(); }, [fetchChars]);

  const fetchConvos = useCallback(async (charId: string) => {
    setConvosLoading(true);
    setConvos([]);
    setSelectedUserId(null);
    try {
      const res = await conversations.list(charId);
      const data = res.data?.data ?? res.data?.conversations ?? res.data ?? [];
      setConvos(sortConversationsByDate(Array.isArray(data) ? data : []));
    } catch {
      setConvos([]);
    }
    setConvosLoading(false);
  }, []);

  useEffect(() => {
    if (selectedCharId) fetchConvos(selectedCharId);
  }, [selectedCharId, fetchConvos]);

  const fetchMessages = async (userId: string) => {
    if (!selectedCharId) return;
    setMsgsLoading(true);
    setSelectedUserId(userId);
    try {
      const res = await conversations.getHistory(selectedCharId, userId);
      const raw = res.data?.data;
      const data = Array.isArray(raw) ? raw : (raw?.messages ?? res.data?.messages ?? []);
      setMessages(sortMessagesByDate(Array.isArray(data) ? data : []));
    } catch {
      setMessages([]);
    }
    setMsgsLoading(false);
  };

  const handleDelete = async (userId: string) => {
    if (!selectedCharId || !window.confirm('Bu konuşmayı silmek istediğinize emin misiniz?')) return;
    try {
      await conversations.deleteHistory(selectedCharId, userId);
      if (selectedUserId === userId) setSelectedUserId(null);
      await fetchConvos(selectedCharId);
    } catch {
      setError('Konuşma silinemedi.');
    }
  };

  const selectedCharName = charList.find(c => c.id === selectedCharId)?.identity?.name ?? 'Seçiniz';

  const filteredConvos = convos.filter(c => {
    if (!search) return true;
    const name = c.userName ?? `#${c.telegramUserId}`;
    return name.toLowerCase().includes(search.toLowerCase());
  });

  if (loading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="max-w-[1200px] mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white tracking-tight">Konuşmalar</h1>
          <p className="text-sm text-slate-500 mt-1">Karakter bazlı sohbet geçmişi ve yönetimi</p>
        </div>
        <div className="flex items-center gap-3">
          <span className="text-[12px] text-slate-500">{convos.length} konuşma</span>
        </div>
      </div>

      {error && (
        <motion.div initial={{ opacity: 0, y: -10 }} animate={{ opacity: 1, y: 0 }}
          className="mb-6 p-4 rounded-xl border border-red-500/20 bg-red-500/[0.05] flex items-center justify-between">
          <span className="text-[13px] text-red-400">{error}</span>
          <button onClick={() => setError(null)} className="text-[12px] text-red-400 hover:text-red-300 cursor-pointer">Kapat</button>
        </motion.div>
      )}

      {/* Character selector + Search */}
      <div className="flex items-center gap-3 mb-6">
        {/* Custom dropdown */}
        <div className="relative">
          <button
            onClick={() => setCharDropdownOpen(!charDropdownOpen)}
            className="flex items-center gap-3 px-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] hover:border-white/[0.12] transition-all cursor-pointer min-w-[220px]"
          >
            <div className="w-8 h-8 rounded-lg shrink-0">
              {selectedCharId && charList.find(c => c.id === selectedCharId)
                ? renderCharAvatar(charList.find(c => c.id === selectedCharId)!, 'md')
                : <div className="w-8 h-8 rounded-lg bg-indigo-500/20 flex items-center justify-center"><Users className="w-4 h-4 text-indigo-400" /></div>
              }
            </div>
            <div className="flex-1 text-left">
              <div className="text-[11px] text-slate-500 leading-none">Karakter</div>
              <div className="text-[13px] font-medium text-slate-200 mt-0.5">{selectedCharName}</div>
            </div>
            <ChevronDown className={`w-4 h-4 text-slate-500 transition-transform ${charDropdownOpen ? 'rotate-180' : ''}`} />
          </button>
          <AnimatePresence>
            {charDropdownOpen && (
              <motion.div
                initial={{ opacity: 0, y: -4 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -4 }}
                className="absolute top-full left-0 mt-2 w-full rounded-xl bg-[#16162a] border border-white/[0.08] shadow-2xl shadow-black/40 z-50 overflow-hidden"
              >
                {charList.map(c => (
                  <button
                    key={c.id}
                    onClick={() => { setSelectedCharId(c.id); setCharDropdownOpen(false); }}
                    className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors cursor-pointer ${
                      selectedCharId === c.id ? 'bg-indigo-500/[0.1] text-white' : 'text-slate-400 hover:bg-white/[0.04] hover:text-slate-200'
                    }`}
                  >
                    {renderCharAvatar(c)}
                    <span className="text-[13px] font-medium">{c.identity?.name ?? c.id.slice(0, 8)}</span>
                  </button>
                ))}
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* Search */}
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Kullanıcı ara..."
            className="w-full pl-10 pr-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] text-sm text-slate-300 placeholder-slate-600 focus:outline-none focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/10 transition-all"
          />
        </div>
      </div>

      {/* Content */}
      <AnimatePresence mode="wait">
        {selectedUserId ? (
          /* Message view */
          <motion.div key="messages" initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }}>
            <button
              onClick={() => setSelectedUserId(null)}
              className="flex items-center gap-2 mb-5 px-4 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.06] text-[13px] font-medium text-slate-400 hover:text-white hover:bg-white/[0.06] transition-all cursor-pointer"
            >
              <ArrowLeft className="w-4 h-4" /> Konuşmalara Dön
            </button>

            <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] overflow-hidden">
              <div className="px-6 py-4 border-b border-white/[0.06] flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 rounded-full bg-gradient-to-br from-violet-500/20 to-pink-500/20 flex items-center justify-center">
                    <User className="w-4 h-4 text-violet-400" />
                  </div>
                  <div>
                    <div className="text-[14px] font-semibold text-white">Kullanıcı #{selectedUserId}</div>
                    <div className="text-[11px] text-slate-500">{messages.length} mesaj</div>
                  </div>
                </div>
                <button
                  onClick={() => handleDelete(selectedUserId)}
                  className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-[12px] text-red-400 hover:bg-red-500/10 transition-colors cursor-pointer"
                >
                  <Trash2 className="w-3.5 h-3.5" /> Sil
                </button>
              </div>

              {msgsLoading ? (
                <div className="flex min-h-[300px] items-center justify-center">
                  <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
                </div>
              ) : messages.length === 0 ? (
                <div className="py-16 text-center text-[13px] text-slate-500">Mesaj bulunamadı.</div>
              ) : (
                <div className="max-h-[500px] overflow-y-auto p-5 space-y-3">
                  {messages.map((m) => (
                    <div key={m.id} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                      <div className={`max-w-[70%] rounded-2xl px-4 py-3 ${
                        m.role === 'user'
                          ? 'bg-indigo-500/[0.12] text-indigo-100 ring-1 ring-indigo-500/20'
                          : 'bg-white/[0.04] text-slate-200 ring-1 ring-white/[0.06]'
                      }`}>
                        {(m.messageType === 'photo' || m.messageType === 'text_photo' || m.imagePath || m.imageUrl) && (m.imagePath || m.imageUrl) && (
                          <img
                            src={m.imageUrl || m.imagePath}
                            alt="Gönderilen fotoğraf"
                            className="max-w-[200px] rounded-lg mb-2 cursor-pointer hover:opacity-80 transition-opacity"
                            loading="lazy"
                            onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
                          />
                        )}
                        {m.content && m.content !== '[Fotoğraf gönderildi]' && (
                          <p className="text-[13px] leading-relaxed m-0">{m.content}</p>
                        )}
                        {m.content === '[Fotoğraf gönderildi]' && !m.imagePath && !m.imageUrl && (
                          <p className="text-[13px] leading-relaxed m-0 italic text-slate-500"> Fotoğraf gönderildi</p>
                        )}
                        <div className="mt-1.5 text-[10px] text-slate-500 flex items-center gap-1.5">
                          {m.role === 'user' ? <Send className="w-2.5 h-2.5" /> : <MessageSquare className="w-2.5 h-2.5" />}
                          {formatDateTR(m.timestamp)}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </motion.div>
        ) : (
          /* Conversation list */
          <motion.div key="convos" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
            {convosLoading ? (
              <div className="flex min-h-[300px] items-center justify-center">
                <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
              </div>
            ) : filteredConvos.length === 0 ? (
              <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] py-16 text-center">
                <MessageSquare className="w-8 h-8 text-slate-700 mx-auto mb-3" />
                <p className="text-[13px] text-slate-500">
                  {convos.length === 0 ? 'Bu karakter için henüz konuşma bulunmuyor.' : 'Aramanızla eşleşen konuşma yok.'}
                </p>
              </div>
            ) : (
              <div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] overflow-hidden">
                <div className="grid grid-cols-[1fr_90px_80px_140px_60px] gap-4 px-6 py-3 text-[11px] font-semibold text-slate-500 uppercase tracking-wider border-b border-white/[0.04]">
                  <span>Kullanıcı</span><span className="text-center">Mesaj</span><span className="text-center">Stars</span><span>Son Aktivite</span><span />
                </div>
                {filteredConvos.map((c, i) => (
                  <motion.button
                    key={c.telegramUserId}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: i * 0.03 }}
                    onClick={() => fetchMessages(String(c.telegramUserId))}
                    className="grid grid-cols-[1fr_90px_80px_140px_60px] gap-4 items-center w-full px-6 py-3.5 hover:bg-white/[0.02] transition-colors cursor-pointer text-left border-b border-white/[0.03] last:border-b-0"
                  >
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="w-9 h-9 rounded-full bg-gradient-to-br from-violet-500/20 to-pink-500/20 border border-violet-500/20 flex items-center justify-center shrink-0">
                        <User className="w-4 h-4 text-violet-300" />
                      </div>
                      <div className="min-w-0">
                        <div className="text-[13px] font-medium text-slate-200 truncate">{c.userName ?? `Kullanıcı #${c.telegramUserId}`}</div>
                        <div className="text-[11px] text-slate-600">ID: {c.telegramUserId}</div>
                        {c.lastMessagePreview && (
                          <div className="text-[11px] text-slate-500 truncate mt-0.5">{c.lastMessagePreview}</div>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center justify-center gap-1.5">
                      <MessageSquare className="w-3.5 h-3.5 text-slate-500" />
                      <span className="text-[13px] text-slate-400 tabular-nums">{c.totalMessages}</span>
                    </div>
                    <div className="flex items-center justify-center gap-1.5">
                      <Star className="w-3.5 h-3.5 text-amber-400" />
                      <span className="text-[13px] text-slate-400 tabular-nums">{c.starsSpent ?? 0}</span>
                    </div>
                    <div className="text-[12px] text-slate-500">{formatDateTR(c.lastActivity)}</div>
                    <div className="flex justify-end">
                      <button
                        onClick={(e) => { e.stopPropagation(); handleDelete(String(c.telegramUserId)); }}
                        className="p-2 rounded-lg text-slate-600 hover:text-red-400 hover:bg-red-500/10 transition-all cursor-pointer"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  </motion.button>
                ))}
              </div>
            )}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default Messages;