/**
 * ConversationHistoryAdvanced Component
 * Enhanced conversation history with date filters, search, and continue functionality
 * OQI-007: LLM Strategy Agent - Conversation History UI
 */

import React, { useState, useMemo, useCallback } from 'react';
import { format, formatDistanceToNow, isWithinInterval, startOfDay, endOfDay, subDays } from 'date-fns';
import { es } from 'date-fns/locale';
import {
  ChatBubbleLeftRightIcon,
  PlusIcon,
  TrashIcon,
  MagnifyingGlassIcon,
  CalendarIcon,
  FunnelIcon,
  ArrowPathIcon,
  ChevronRightIcon,
  XMarkIcon,
  ArchiveBoxIcon,
  ClockIcon,
  SparklesIcon,
} from '@heroicons/react/24/outline';
import { SparklesIcon as SparklesSolidIcon } from '@heroicons/react/24/solid';
import type { ChatSession } from '../../../types/chat.types';

// ============================================================================
// Types
// ============================================================================

type DateFilter = 'all' | 'today' | 'week' | 'month' | 'custom';

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

// ============================================================================
// Helper Functions
// ============================================================================

const getSessionTitle = (session: ChatSession): string => {
  const firstUserMessage = session.messages.find((m) => m.role === 'user');
  if (firstUserMessage) {
    return firstUserMessage.content.slice(0, 50) + (firstUserMessage.content.length > 50 ? '...' : '');
  }
  return 'Nueva conversacion';
};

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

const getDateFilterRange = (filter: DateFilter, customRange?: { start: Date; end: Date }) => {
  const now = new Date();
  switch (filter) {
    case 'today':
      return { start: startOfDay(now), end: endOfDay(now) };
    case 'week':
      return { start: startOfDay(subDays(now, 7)), end: endOfDay(now) };
    case 'month':
      return { start: startOfDay(subDays(now, 30)), end: endOfDay(now) };
    case 'custom':
      return customRange || null;
    default:
      return null;
  }
};

// ============================================================================
// Sub-Components
// ============================================================================

interface DateFilterButtonsProps {
  selected: DateFilter;
  onSelect: (filter: DateFilter) => void;
  onCustomClick: () => void;
}

const DateFilterButtons: React.FC<DateFilterButtonsProps> = ({ selected, onSelect, onCustomClick }) => {
  const filters: { id: DateFilter; label: string }[] = [
    { id: 'all', label: 'Todo' },
    { id: 'today', label: 'Hoy' },
    { id: 'week', label: '7 dias' },
    { id: 'month', label: '30 dias' },
    { id: 'custom', label: 'Rango' },
  ];

  return (
    <div className="flex flex-wrap gap-1.5">
      {filters.map((filter) => (
        <button
          key={filter.id}
          onClick={() => filter.id === 'custom' ? onCustomClick() : onSelect(filter.id)}
          className={`px-2.5 py-1 text-xs rounded-lg transition-colors ${
            selected === filter.id
              ? 'bg-primary-500 text-white'
              : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600'
          }`}
        >
          {filter.label}
        </button>
      ))}
    </div>
  );
};

interface SessionListItemProps {
  session: ChatSession;
  isActive: boolean;
  onSelect: () => void;
  onDelete: () => void;
  onContinue?: () => void;
  onArchive?: () => void;
}

const SessionListItem: React.FC<SessionListItemProps> = ({
  session,
  isActive,
  onSelect,
  onDelete,
  onContinue,
  onArchive,
}) => {
  const [showActions, setShowActions] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (confirmDelete) {
      onDelete();
      setConfirmDelete(false);
    } else {
      setConfirmDelete(true);
      setTimeout(() => setConfirmDelete(false), 3000);
    }
  };

  return (
    <div
      onClick={onSelect}
      onMouseEnter={() => setShowActions(true)}
      onMouseLeave={() => { setShowActions(false); setConfirmDelete(false); }}
      className={`group relative p-3 rounded-lg cursor-pointer transition-all ${
        isActive
          ? 'bg-primary-50 dark:bg-primary-900/30 border border-primary-200 dark:border-primary-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-9 h-9 rounded-full flex items-center justify-center ${
          isActive
            ? 'bg-primary-500 text-white'
            : 'bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400'
        }`}>
          {isActive ? <SparklesSolidIcon className="w-4 h-4" /> : <SparklesIcon className="w-4 h-4" />}
        </div>

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

        {/* Actions */}
        <div className={`flex items-center gap-1 transition-opacity ${showActions ? 'opacity-100' : 'opacity-0'}`}>
          {!confirmDelete ? (
            <>
              {onContinue && (
                <button
                  onClick={(e) => { e.stopPropagation(); onContinue(); }}
                  className="p-1.5 text-gray-400 hover:text-primary-500 hover:bg-primary-50 dark:hover:bg-primary-900/20 rounded-lg"
                  title="Continuar conversacion"
                >
                  <ChevronRightIcon className="w-4 h-4" />
                </button>
              )}
              {onArchive && (
                <button
                  onClick={(e) => { e.stopPropagation(); onArchive(); }}
                  className="p-1.5 text-gray-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg"
                  title="Archivar"
                >
                  <ArchiveBoxIcon className="w-4 h-4" />
                </button>
              )}
              <button
                onClick={handleDelete}
                className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg"
                title="Eliminar"
              >
                <TrashIcon className="w-4 h-4" />
              </button>
            </>
          ) : (
            <>
              <button
                onClick={handleDelete}
                className="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
              >
                Confirmar
              </button>
              <button
                onClick={(e) => { e.stopPropagation(); setConfirmDelete(false); }}
                className="p-1 text-gray-400 hover:text-gray-600"
              >
                <XMarkIcon className="w-4 h-4" />
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// ============================================================================
// Main Component
// ============================================================================

export const ConversationHistoryAdvanced: React.FC<ConversationHistoryAdvancedProps> = ({
  sessions,
  currentSessionId,
  loading,
  onSelectSession,
  onCreateSession,
  onDeleteSession,
  onContinueSession,
  onArchiveSession,
  onExportSession,
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [dateFilter, setDateFilter] = useState<DateFilter>('all');
  const [showFilters, setShowFilters] = useState(false);
  const [customRange, setCustomRange] = useState<{ start: Date; end: Date } | null>(null);
  const [showCustomDatePicker, setShowCustomDatePicker] = useState(false);

  const filteredSessions = useMemo(() => {
    let filtered = sessions;

    // Search filter
    if (searchTerm.trim()) {
      const query = searchTerm.toLowerCase();
      filtered = filtered.filter((session) => {
        const title = getSessionTitle(session).toLowerCase();
        const hasMatchInMessages = session.messages.some((m) =>
          m.content.toLowerCase().includes(query)
        );
        return title.includes(query) || hasMatchInMessages;
      });
    }

    // Date filter
    const range = getDateFilterRange(dateFilter, customRange || undefined);
    if (range) {
      filtered = filtered.filter((session) => {
        const date = new Date(session.updatedAt);
        return isWithinInterval(date, { start: range.start, end: range.end });
      });
    }

    // Sort by most recent
    return filtered.sort((a, b) =>
      new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    );
  }, [sessions, searchTerm, dateFilter, customRange]);

  const handleContinue = useCallback((sessionId: string) => {
    onSelectSession(sessionId);
    onContinueSession?.(sessionId);
  }, [onSelectSession, onContinueSession]);

  const totalMessages = sessions.reduce((acc, s) => acc + s.messages.length, 0);

  return (
    <div className="flex flex-col h-full bg-white dark:bg-gray-800">
      {/* Header with New Chat */}
      <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 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-3 space-y-3">
        <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 en conversaciones..."
            className="w-full pl-9 pr-10 py-2 text-sm bg-gray-100 dark:bg-gray-700 border-0 rounded-lg focus:ring-2 focus:ring-primary-500 text-gray-900 dark:text-white placeholder-gray-500"
          />
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-lg transition-colors ${
              showFilters || dateFilter !== 'all'
                ? 'text-primary-500 bg-primary-50 dark:bg-primary-900/20'
                : 'text-gray-400 hover:text-gray-600 dark:hover:text-gray-300'
            }`}
          >
            <FunnelIcon className="w-4 h-4" />
          </button>
        </div>

        {/* Filters */}
        {showFilters && (
          <div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg space-y-3">
            <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
              <CalendarIcon className="w-4 h-4" />
              <span>Filtrar por fecha</span>
            </div>
            <DateFilterButtons
              selected={dateFilter}
              onSelect={setDateFilter}
              onCustomClick={() => setShowCustomDatePicker(true)}
            />
            {dateFilter === 'custom' && customRange && (
              <div className="flex items-center gap-2 text-xs text-gray-500">
                <span>{format(customRange.start, 'dd/MM/yyyy', { locale: es })}</span>
                <span>-</span>
                <span>{format(customRange.end, 'dd/MM/yyyy', { locale: es })}</span>
                <button
                  onClick={() => { setCustomRange(null); setDateFilter('all'); }}
                  className="ml-auto text-gray-400 hover:text-red-500"
                >
                  <XMarkIcon className="w-4 h-4" />
                </button>
              </div>
            )}
            {showCustomDatePicker && (
              <div className="grid grid-cols-2 gap-2">
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Desde</label>
                  <input
                    type="date"
                    onChange={(e) => {
                      const start = new Date(e.target.value);
                      setCustomRange((prev) => ({ start, end: prev?.end || new Date() }));
                      setDateFilter('custom');
                    }}
                    className="w-full px-2 py-1.5 text-sm bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded"
                  />
                </div>
                <div>
                  <label className="block text-xs text-gray-500 mb-1">Hasta</label>
                  <input
                    type="date"
                    onChange={(e) => {
                      const end = new Date(e.target.value);
                      setCustomRange((prev) => ({ start: prev?.start || subDays(new Date(), 30), end }));
                      setDateFilter('custom');
                    }}
                    className="w-full px-2 py-1.5 text-sm bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded"
                  />
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Results Summary */}
      {(searchTerm || dateFilter !== 'all') && (
        <div className="px-4 pb-2">
          <p className="text-xs text-gray-500">
            {filteredSessions.length} de {sessions.length} conversaciones
          </p>
        </div>
      )}

      {/* Session List */}
      <div className="flex-1 overflow-y-auto px-3 py-2">
        {loading && sessions.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12">
            <ArrowPathIcon className="w-8 h-8 text-primary-500 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 || dateFilter !== 'all' ? 'No se encontraron resultados' : 'Sin conversaciones'}
            </p>
            <p className="text-xs text-gray-400">
              {searchTerm || dateFilter !== 'all' ? 'Intenta con otros terminos o filtros' : 'Inicia una nueva conversacion'}
            </p>
          </div>
        ) : (
          <div className="space-y-1">
            {filteredSessions.map((session) => (
              <SessionListItem
                key={session.id}
                session={session}
                isActive={session.id === currentSessionId}
                onSelect={() => onSelectSession(session.id)}
                onDelete={() => onDeleteSession(session.id)}
                onContinue={onContinueSession ? () => handleContinue(session.id) : undefined}
                onArchive={onArchiveSession ? () => onArchiveSession(session.id) : undefined}
              />
            ))}
          </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>{totalMessages.toLocaleString()} mensajes totales</span>
        </div>
      </div>
    </div>
  );
};

export default ConversationHistoryAdvanced;
