import { useState, useEffect, useRef, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { conversations, characters } from '../../api/client';
import { formatDateTR, sortMessagesByDate } from '../../types/telegram';
import { motion } from 'framer-motion';
import { ArrowLeft, User, MessageSquare } from 'lucide-react';
import ImageLightbox from '../../components/ImageLightbox';

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: string;
  messageType?: 'text' | 'photo' | 'text_photo';
  imagePath?: string;
  imageUrl?: string;
}

const POLL_INTERVAL = 10_000;
const PAGE_LIMIT = 50;

export default function ConversationDetail() {
  const { characterId, userId } = useParams<{ characterId: string; userId: string }>();
  const navigate = useNavigate();
  const bottomRef = useRef<HTMLDivElement>(null);

  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [characterName, setCharacterName] = useState<string>('');
  const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
  const [avatarError, setAvatarError] = useState(false);
  const [avatarLoaded, setAvatarLoaded] = useState(false);

  const scrollToBottom = useCallback(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, []);

  const fetchMessages = useCallback(async (showLoader = false) => {
    if (!characterId || !userId) return;
    if (showLoader) setLoading(true);
    try {
      const res = await conversations.getMessages(characterId, userId, { page: 1, limit: PAGE_LIMIT });
      const data = res.data?.data?.messages ?? res.data?.data ?? res.data?.messages ?? [];
      const msgArray = Array.isArray(data) ? data : [];
      // Sort messages chronologically (oldest first) — Requirement 3.1
      const sorted = sortMessagesByDate(msgArray);
      setMessages(sorted);
      setError(null);
    } catch {
      if (showLoader) setError('Mesajlar yüklenirken bir hata oluştu. Lütfen bağlantınızı kontrol edip tekrar deneyin.');
    } finally {
      if (showLoader) setLoading(false);
    }
  }, [characterId, userId]);

  // Fetch character name
  useEffect(() => {
    if (!characterId) return;
    characters.get(characterId).then((res) => {
      const name = res.data?.data?.identity?.name ?? res.data?.identity?.name ?? '';
      setCharacterName(name);
    }).catch(() => {});
  }, [characterId]);

  // Initial fetch
  useEffect(() => {
    fetchMessages(true);
  }, [fetchMessages]);

  // Polling every 10 seconds
  useEffect(() => {
    const interval = setInterval(() => fetchMessages(false), POLL_INTERVAL);
    return () => clearInterval(interval);
  }, [fetchMessages]);

  // Auto scroll to bottom on messages change
  useEffect(() => {
    scrollToBottom();
  }, [messages, scrollToBottom]);

  const handleBack = () => {
    navigate(-1);
  };

  const hasImage = (msg: Message) =>
    (msg.messageType === 'photo' || msg.messageType === 'text_photo') && (msg.imageUrl || msg.imagePath);

  const getImageSrc = (msg: Message) => {
    if (msg.imageUrl) return msg.imageUrl;
    // imagePath is already a valid URL path (e.g. /static/characters/.../photo.jpg)
    if (msg.imagePath) return msg.imagePath;
    return '';
  };

  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-[900px] mx-auto">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={handleBack}
          className="flex items-center gap-2 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" />
          Geri
        </button>
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-gradient-to-br from-violet-500/20 to-pink-500/20 border border-violet-500/20 flex items-center justify-center">
            <User className="w-5 h-5 text-violet-400" />
          </div>
          <div>
            <div className="text-[15px] font-semibold text-white">
              Kullanıcı #{userId}
            </div>
            <div className="text-[11px] text-slate-500 flex items-center gap-1.5">
              {/* Character avatar */}
              {characterId && (
                avatarError ? (
                  <span className="inline-flex items-center justify-center w-[18px] h-[18px] rounded-full bg-gradient-to-br from-indigo-500/20 to-violet-500/20 border border-indigo-500/20 text-[9px] font-bold text-indigo-300 shrink-0">
                    {(characterName || '?')[0].toUpperCase()}
                  </span>
                ) : (
                  <span className="relative inline-flex w-[18px] h-[18px] shrink-0">
                    {!avatarLoaded && (
                      <span className="absolute inset-0 rounded-full bg-white/[0.06] animate-pulse" />
                    )}
                    <img
                      src={`/static/characters/${characterId}/reference-images/master.jpg`}
                      alt={characterName || ''}
                      className={`w-[18px] h-[18px] rounded-full object-cover border border-white/[0.06] ${!avatarLoaded ? 'opacity-0' : 'opacity-100'} transition-opacity duration-200`}
                      onLoad={() => setAvatarLoaded(true)}
                      onError={() => setAvatarError(true)}
                    />
                  </span>
                )
              )}
              {characterName ? `${characterName} ile konuşma` : 'Konuşma detayı'}
              {' · '}{messages.length} mesaj
            </div>
          </div>
        </div>

        {/* Character avatar — header right */}
        {characterId && (
          <div className="ml-auto">
            {avatarError ? (
              <div className="w-[44px] h-[44px] rounded-full bg-gradient-to-br from-indigo-500/20 to-violet-500/20 border border-indigo-500/20 flex items-center justify-center">
                <span className="text-[15px] font-bold text-indigo-300">{(characterName || '?')[0].toUpperCase()}</span>
              </div>
            ) : (
              <div className="relative w-[44px] h-[44px]">
                {!avatarLoaded && (
                  <div className="absolute inset-0 rounded-full bg-white/[0.06] animate-pulse" />
                )}
                <img
                  src={`/static/characters/${characterId}/reference-images/master.jpg`}
                  alt={characterName || ''}
                  className={`w-[44px] h-[44px] rounded-full object-cover border border-white/[0.06] ${!avatarLoaded ? 'opacity-0' : 'opacity-100'} transition-opacity duration-200`}
                  onLoad={() => setAvatarLoaded(true)}
                  onError={() => setAvatarError(true)}
                />
              </div>
            )}
          </div>
        )}
      </div>

      {/* Error */}
      {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>
          <div className="flex items-center gap-2">
            <button
              onClick={() => fetchMessages(true)}
              className="text-[12px] text-red-400 hover:text-red-300 cursor-pointer underline"
            >
              Tekrar Dene
            </button>
            <button
              onClick={() => setError(null)}
              className="text-[12px] text-red-400 hover:text-red-300 cursor-pointer"
            >
              Kapat
            </button>
          </div>
        </motion.div>
      )}

      {/* Chat area */}
      <div className="rounded-2xl border border-white/[0.06] bg-white/[0.03] backdrop-blur-xl overflow-hidden">
        {messages.length === 0 ? (
          <div className="py-20 text-center">
            <MessageSquare className="w-8 h-8 text-slate-700 mx-auto mb-3" />
            <p className="text-[13px] text-slate-500">Henüz mesaj bulunmuyor.</p>
          </div>
        ) : (
          <div className="max-h-[600px] overflow-y-auto p-5 space-y-3">
            {messages.map((msg) => (
              <div
                key={msg.id}
                data-role={msg.role}
                className={`flex ${msg.role === 'user' ? 'justify-start' : 'justify-end'}`}
              >
                <motion.div
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  className={`max-w-[70%] rounded-2xl px-4 py-3 ${
                    msg.role === 'user'
                      ? 'bg-slate-700/50 text-slate-200'
                      : 'bg-indigo-600/30 text-slate-100'
                  }`}
                >
                  {/* Image */}
                  {hasImage(msg) && (
                    <div className="mb-2">
                      <img
                        src={getImageSrc(msg)}
                        alt="Mesaj görseli"
                        className="max-w-[200px] rounded-lg cursor-pointer hover:opacity-80 transition-opacity"
                        loading="lazy"
                        onClick={() => {
                          setLightboxSrc(getImageSrc(msg));
                        }}
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = 'none';
                        }}
                      />
                    </div>
                  )}

                  {/* Text content */}
                  {msg.content && (
                    <p className="text-[13px] leading-relaxed m-0 whitespace-pre-wrap">{msg.content}</p>
                  )}

                  {/* Timestamp */}
                  <div
                    data-testid="message-timestamp"
                    className={`mt-1.5 text-[10px] text-slate-500 flex items-center gap-1.5 ${
                      msg.role === 'user' ? 'justify-start' : 'justify-end'
                    }`}
                  >
                    {msg.role === 'user' ? (
                      <User className="w-2.5 h-2.5" />
                    ) : (
                      <MessageSquare className="w-2.5 h-2.5" />
                    )}
                    {formatDateTR(msg.timestamp)}
                  </div>
                </motion.div>
              </div>
            ))}
            <div ref={bottomRef} />
          </div>
        )}
      </div>

      <ImageLightbox
        isOpen={!!lightboxSrc}
        src={lightboxSrc || ''}
        onClose={() => setLightboxSrc(null)}
      />
    </div>
  );
}

