/**
 * ConversationHistory Component
 * Displays list of chat sessions with actions to load, create, and delete
 */

import React, { useEffect, useState } from 'react';
import { format, formatDistanceToNow } from 'date-fns';
import { es } from 'date-fns/locale';
import {
  ChatBubbleLeftRightIcon,
  PlusIcon,
  TrashIcon,
  MagnifyingGlassIcon,
} from '@heroicons/react/24/outline';
import { SparklesIcon } from '@heroicons/react/24/solid';
import type { ChatSession } from '../../../types/chat.types';

interface ConversationHistoryProps {
  sessions: ChatSession[];
  currentSessionId: string | null;
  loading: boolean;
  onSelectSession: (sessionId: string) => void;
  onCreateSession: () => void;
  onDeleteSession: (sessionId: string) => void;
}

const ConversationHistory: React.FC<ConversationHistoryProps> = ({
  sessions,
  currentSessionId,
  loading,
  onSelectSession,
  onCreateSession,
  onDeleteSession,
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  // Filter sessions by search term
  const filteredSessions = sessions.filter((session) => {
    if (!searchTerm.trim()) return true;
    const lastMessage = session.messages[session.messages.length - 1];
    return (
      lastMessage?.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
      session.id.toLowerCase().includes(searchTerm.toLowerCase())
    );
  });

  // Get session title from first user message or default
  const getSessionTitle = (session: ChatSession): string => {
    const firstUserMessage = session.messages.find((m) => m.role === 'user');
    if (firstUserMessage) {
      return firstUserMessage.content.slice(0, 40) + (firstUserMessage.content.length > 40 ? '...' : '');
    }
    return 'Nueva conversacion';
  };

  // Get last message preview
  const getLastMessagePreview = (session: ChatSession): string => {
    const lastMessage = session.messages[session.messages.length - 1];
    if (lastMessage) {
      const preview = lastMessage.content.slice(0, 50);
      return preview + (lastMessage.content.length > 50 ? '...' : '');
    }
    return 'Sin mensajes';
  };

  const handleDelete = (sessionId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    if (deleteConfirm === sessionId) {
      onDeleteSession(sessionId);
      setDeleteConfirm(null);
    } else {
      setDeleteConfirm(sessionId);
      // Auto-cancel after 3 seconds
      setTimeout(() => setDeleteConfirm(null), 3000);
    }
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header with New Chat button */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={onCreateSession}
          disabled={loading}
          className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-gradient-to-r from-cyan-500 to-blue-600 hover:from-cyan-600 hover:to-blue-700 text-white rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-md hover:shadow-lg"
        >
          <PlusIcon className="w-5 h-5" />
          <span className="font-medium">Nueva Conversacion</span>
        </button>
      </div>

      {/* Search */}
      <div className="px-4 py-2">
        <div className="relative">
          <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Buscar conversaciones..."
            className="w-full pl-9 pr-4 py-2 text-sm bg-gray-100 dark:bg-gray-700 border-0 rounded-lg focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-white placeholder-gray-500"
          />
        </div>
      </div>

      {/* Session List */}
      <div className="flex-1 overflow-y-auto px-2 py-2">
        {loading && sessions.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12">
            <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin mb-3" />
            <p className="text-sm text-gray-500">Cargando conversaciones...</p>
          </div>
        ) : filteredSessions.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 px-4 text-center">
            <div className="w-16 h-16 bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-4">
              <ChatBubbleLeftRightIcon className="w-8 h-8 text-gray-400" />
            </div>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">
              {searchTerm ? 'No se encontraron resultados' : 'Sin conversaciones'}
            </p>
            <p className="text-xs text-gray-400">
              {searchTerm ? 'Intenta con otros terminos' : 'Inicia una nueva conversacion'}
            </p>
          </div>
        ) : (
          <div className="space-y-1">
            {filteredSessions.map((session) => {
              const isActive = session.id === currentSessionId;
              const isDeleting = deleteConfirm === session.id;

              return (
                <div
                  key={session.id}
                  onClick={() => onSelectSession(session.id)}
                  className={`group relative p-3 rounded-lg cursor-pointer transition-all ${
                    isActive
                      ? 'bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800'
                      : 'hover:bg-gray-100 dark:hover:bg-gray-700/50 border border-transparent'
                  }`}
                >
                  <div className="flex items-start gap-3">
                    {/* Icon */}
                    <div
                      className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center ${
                        isActive
                          ? 'bg-blue-500 text-white'
                          : 'bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400'
                      }`}
                    >
                      <SparklesIcon className="w-4 h-4" />
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <p
                        className={`font-medium text-sm truncate ${
                          isActive
                            ? 'text-blue-900 dark:text-blue-100'
                            : 'text-gray-900 dark:text-white'
                        }`}
                      >
                        {getSessionTitle(session)}
                      </p>
                      <p className="text-xs text-gray-500 truncate mt-0.5">
                        {getLastMessagePreview(session)}
                      </p>
                      <p className="text-xs text-gray-400 mt-1">
                        {formatDistanceToNow(new Date(session.updatedAt), {
                          addSuffix: true,
                          locale: es,
                        })}
                      </p>
                    </div>

                    {/* Delete Button */}
                    <button
                      onClick={(e) => handleDelete(session.id, e)}
                      className={`flex-shrink-0 p-1.5 rounded-md transition-all ${
                        isDeleting
                          ? 'bg-red-100 dark:bg-red-900/30 text-red-600'
                          : 'opacity-0 group-hover:opacity-100 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20'
                      }`}
                      title={isDeleting ? 'Click para confirmar' : 'Eliminar'}
                    >
                      <TrashIcon className="w-4 h-4" />
                    </button>
                  </div>

                  {/* Message count badge */}
                  {session.messages.length > 0 && (
                    <div className="absolute bottom-2 right-2">
                      <span className="text-xs text-gray-400">
                        {session.messages.length} msg
                      </span>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Footer stats */}
      <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">
        <div className="flex items-center justify-between text-xs text-gray-500">
          <span>{sessions.length} conversaciones</span>
          <span>
            {sessions.reduce((acc, s) => acc + s.messages.length, 0)} mensajes
          </span>
        </div>
      </div>
    </div>
  );
};

export default ConversationHistory;
