/**
 * NotificationsPage
 * Full page view for all notifications with filters and preferences
 */

import { useState, useEffect } from 'react';
import {
  Bell,
  CheckCheck,
  Filter,
  Settings,
  Trash2,
  RefreshCw,
} from 'lucide-react';
import clsx from 'clsx';
import { useNotificationStore } from '../../../stores/notificationStore';
import NotificationItem from '../components/NotificationItem';
import type { NotificationType } from '../../../services/notification.service';

// Filter options
const typeFilters: { value: NotificationType | 'all'; label: string }[] = [
  { value: 'all', label: 'Todas' },
  { value: 'alert_triggered', label: 'Alertas' },
  { value: 'trade_executed', label: 'Trades' },
  { value: 'deposit_confirmed', label: 'Depósitos' },
  { value: 'withdrawal_completed', label: 'Retiros' },
  { value: 'distribution_received', label: 'Distribuciones' },
  { value: 'system_announcement', label: 'Sistema' },
  { value: 'security_alert', label: 'Seguridad' },
  { value: 'account_update', label: 'Cuenta' },
];

const statusFilters = [
  { value: 'all', label: 'Todas' },
  { value: 'unread', label: 'Sin leer' },
  { value: 'read', label: 'Leídas' },
];

export default function NotificationsPage() {
  const [typeFilter, setTypeFilter] = useState<NotificationType | 'all'>('all');
  const [statusFilter, setStatusFilter] = useState<'all' | 'unread' | 'read'>('all');
  const [showPreferences, setShowPreferences] = useState(false);

  const {
    notifications,
    unreadCount,
    preferences,
    loading,
    fetchNotifications,
    fetchPreferences,
    markAsRead,
    markAllAsRead,
    deleteNotification,
    updatePreferences,
  } = useNotificationStore();

  // Fetch data on mount
  useEffect(() => {
    fetchNotifications();
    fetchPreferences();
  }, [fetchNotifications, fetchPreferences]);

  // Filter notifications
  const filteredNotifications = notifications.filter((n) => {
    if (typeFilter !== 'all' && n.type !== typeFilter) return false;
    if (statusFilter === 'unread' && n.isRead) return false;
    if (statusFilter === 'read' && !n.isRead) return false;
    return true;
  });

  const handleRefresh = () => {
    fetchNotifications();
  };

  const handleTogglePreference = async (key: 'emailEnabled' | 'pushEnabled' | 'inAppEnabled' | 'smsEnabled') => {
    if (!preferences) return;
    const currentValue = preferences[key];
    if (typeof currentValue === 'boolean') {
      await updatePreferences({ [key]: !currentValue });
    }
  };

  return (
    <div className="max-w-4xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Bell className="w-8 h-8 text-primary-500" />
          <div>
            <h1 className="text-2xl font-bold text-white">Notificaciones</h1>
            <p className="text-sm text-gray-400">
              {unreadCount > 0
                ? `${unreadCount} sin leer`
                : 'Todas las notificaciones leídas'}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={handleRefresh}
            className="p-2 rounded-lg hover:bg-gray-700 text-gray-400 hover:text-white transition-colors"
            title="Actualizar"
          >
            <RefreshCw className={clsx('w-5 h-5', loading && 'animate-spin')} />
          </button>
          {unreadCount > 0 && (
            <button
              onClick={() => markAllAsRead()}
              className="flex items-center gap-2 px-3 py-2 rounded-lg bg-gray-700 hover:bg-gray-600 text-white transition-colors"
            >
              <CheckCheck className="w-4 h-4" />
              <span className="text-sm">Marcar todas como leídas</span>
            </button>
          )}
          <button
            onClick={() => setShowPreferences(!showPreferences)}
            className={clsx(
              'p-2 rounded-lg transition-colors',
              showPreferences
                ? 'bg-primary-600 text-white'
                : 'hover:bg-gray-700 text-gray-400 hover:text-white'
            )}
            title="Preferencias"
          >
            <Settings className="w-5 h-5" />
          </button>
        </div>
      </div>

      {/* Preferences Panel */}
      {showPreferences && preferences && (
        <div className="mb-6 p-4 bg-gray-800 border border-gray-700 rounded-xl">
          <h3 className="font-semibold text-white mb-4">Preferencias de Notificaciones</h3>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={preferences.emailEnabled}
                onChange={() => handleTogglePreference('emailEnabled')}
                className="w-4 h-4 rounded border-gray-600 bg-gray-700 text-primary-500 focus:ring-primary-500"
              />
              <span className="text-sm text-gray-300">Email</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={preferences.pushEnabled}
                onChange={() => handleTogglePreference('pushEnabled')}
                className="w-4 h-4 rounded border-gray-600 bg-gray-700 text-primary-500 focus:ring-primary-500"
              />
              <span className="text-sm text-gray-300">Push</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={preferences.inAppEnabled}
                onChange={() => handleTogglePreference('inAppEnabled')}
                className="w-4 h-4 rounded border-gray-600 bg-gray-700 text-primary-500 focus:ring-primary-500"
              />
              <span className="text-sm text-gray-300">In-App</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={preferences.smsEnabled}
                onChange={() => handleTogglePreference('smsEnabled')}
                className="w-4 h-4 rounded border-gray-600 bg-gray-700 text-primary-500 focus:ring-primary-500"
              />
              <span className="text-sm text-gray-300">SMS</span>
            </label>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-4 mb-6">
        <div className="flex items-center gap-2">
          <Filter className="w-4 h-4 text-gray-400" />
          <span className="text-sm text-gray-400">Filtrar:</span>
        </div>

        {/* Type filter */}
        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value as NotificationType | 'all')}
          className="px-3 py-1.5 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
        >
          {typeFilters.map((filter) => (
            <option key={filter.value} value={filter.value}>
              {filter.label}
            </option>
          ))}
        </select>

        {/* Status filter */}
        <div className="flex rounded-lg overflow-hidden border border-gray-700">
          {statusFilters.map((filter) => (
            <button
              key={filter.value}
              onClick={() => setStatusFilter(filter.value as 'all' | 'unread' | 'read')}
              className={clsx(
                'px-3 py-1.5 text-sm transition-colors',
                statusFilter === filter.value
                  ? 'bg-primary-600 text-white'
                  : 'bg-gray-800 text-gray-400 hover:text-white'
              )}
            >
              {filter.label}
            </button>
          ))}
        </div>

        {/* Results count */}
        <span className="text-sm text-gray-500 ml-auto">
          {filteredNotifications.length} notificaciones
        </span>
      </div>

      {/* Notifications List */}
      <div className="space-y-2">
        {loading ? (
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500" />
          </div>
        ) : filteredNotifications.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-gray-400">
            <Bell className="w-16 h-16 mb-4 opacity-30" />
            <p className="text-lg font-medium">No hay notificaciones</p>
            <p className="text-sm">
              {typeFilter !== 'all' || statusFilter !== 'all'
                ? 'Intenta cambiar los filtros'
                : 'Las notificaciones aparecerán aquí'}
            </p>
          </div>
        ) : (
          filteredNotifications.map((notification) => (
            <NotificationItem
              key={notification.id}
              notification={notification}
              onMarkAsRead={markAsRead}
              onDelete={deleteNotification}
            />
          ))
        )}
      </div>

      {/* Load more button (if needed) */}
      {filteredNotifications.length >= 50 && (
        <div className="mt-6 text-center">
          <button
            onClick={() => fetchNotifications()}
            className="px-4 py-2 text-sm text-primary-400 hover:text-primary-300 transition-colors"
          >
            Cargar más notificaciones
          </button>
        </div>
      )}
    </div>
  );
}
