import React from 'react';
import { clsx } from 'clsx';
import { Button } from '../Button';
import { Badge } from '../Badge';
import { NotificationData } from '../../../hooks/useNotifications';
import {
  Check,
  Trash2,
  AlertTriangle,
  CheckCircle,
  X,
  Bot,
  TrendingUp,
  Clock,
  DollarSign,
  Phone,
  ExternalLink
} from 'lucide-react';
import { Alert, AlertTypeClass, getPriorityColor, getTypeClassBadgeVariant, formatTimeUntilConsequence } from '../../../api/types/events';
import { renderEventTitle, renderEventMessage, renderActionLabel, renderAIReasoning } from '../../../utils/i18n/alertRendering';
import { useSmartActionHandler } from '../../../utils/smartActionHandlers';
import { useAuthUser } from '../../../stores/auth.store';
import { useTranslation } from 'react-i18next';
import { useTenantCurrency } from '../../../hooks/useTenantCurrency';

export interface NotificationPanelProps {
  notifications: NotificationData[];
  enrichedAlerts?: Alert[];
  isOpen: boolean;
  onClose: () => void;
  onMarkAsRead: (id: string) => void;
  onMarkAllAsRead: () => void;
  onRemoveNotification: (id: string) => void;
  onClearAll: () => void;
  className?: string;
}

// Legacy severity functions removed - now using enriched priority_level and type_class

const formatTimestamp = (timestamp: string) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / (1000 * 60));

  if (diffMins < 1) return 'Ahora';
  if (diffMins < 60) return `${diffMins}m`;
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return `${diffHours}h`;
  return date.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' });
};

// Enriched Alert Item Component
const EnrichedAlertItem: React.FC<{
  alert: Alert;
  isMobile: boolean;
  onMarkAsRead: (id: string) => void;
  onRemove: (id: string) => void;
  actionHandler: any;
}> = ({ alert, isMobile, onMarkAsRead, onRemove, actionHandler }) => {
  const { t } = useTranslation();
  const { currencySymbol } = useTenantCurrency();
  const isUnread = alert.status === 'active';
  const priorityColor = getPriorityColor(alert.priority_level);

  return (
    <div
      className={clsx(
        "transition-colors hover:bg-[var(--bg-secondary)] active:bg-[var(--bg-tertiary)]",
        isMobile ? 'px-4 py-4 mx-2 my-1 rounded-lg' : 'p-3',
        isUnread && "bg-[var(--color-info)]/5 border-l-4"
      )}
      style={isUnread ? { borderLeftColor: priorityColor } : {}}
    >
      <div className={`flex gap-${isMobile ? '4' : '3'}`}>
        {/* Priority Icon */}
        <div
          className={`flex-shrink-0 rounded-full mt-0.5 ${isMobile ? 'p-2' : 'p-1'}`}
          style={{ backgroundColor: priorityColor + '15' }}
        >
          {alert.type_class === AlertTypeClass.PREVENTED_ISSUE ? (
            <CheckCircle className={`${isMobile ? 'w-5 h-5' : 'w-3 h-3'}`} style={{ color: 'var(--color-success)' }} />
          ) : alert.type_class === AlertTypeClass.ESCALATION ? (
            <Clock className={`${isMobile ? 'w-5 h-5' : 'w-3 h-3'}`} style={{ color: priorityColor }} />
          ) : (
            <AlertTriangle className={`${isMobile ? 'w-5 h-5' : 'w-3 h-3'}`} style={{ color: priorityColor }} />
          )}
        </div>

        {/* Content */}
        <div className="flex-1 min-w-0">
          {/* Header */}
          <div className={`flex items-start justify-between gap-2 ${isMobile ? 'mb-2' : 'mb-1'}`}>
            <div className={`flex items-center gap-2 ${isMobile ? 'flex-wrap' : ''}`}>
              <Badge variant={getTypeClassBadgeVariant(alert.type_class)} size={isMobile ? "md" : "sm"}>
                {alert.priority_level.toUpperCase()}
              </Badge>
              <Badge variant="secondary" size={isMobile ? "md" : "sm"}>
                {alert.priority_score}
              </Badge>
              {alert.is_group_summary && (
                <Badge variant="info" size={isMobile ? "md" : "sm"}>
                  {alert.grouped_alert_count} agrupadas
                </Badge>
              )}
            </div>
            <span className={`font-medium text-[var(--text-secondary)] ${isMobile ? 'text-sm' : 'text-xs'}`}>
              {formatTimestamp(alert.created_at)}
            </span>
          </div>

          {/* Title */}
          <p className={`font-medium leading-tight text-[var(--text-primary)] ${
            isMobile ? 'text-base mb-2' : 'text-sm mb-1'
          }`}>
            {renderEventTitle(alert, t)}
          </p>

          {/* Message */}
          <p className={`leading-relaxed text-[var(--text-secondary)] ${
            isMobile ? 'text-sm mb-3' : 'text-xs mb-2'
          }`}>
            {renderEventMessage(alert, t)}
          </p>

          {/* Context Badges */}
          <div className="flex flex-wrap gap-2 mb-3">
            {alert.orchestrator_context?.already_addressed && (
              <div className="flex items-center gap-1 px-2 py-1 rounded-md bg-success/10 text-success text-xs">
                <Bot className="w-3 h-3" />
                <span>AI ya gestionó esto</span>
              </div>
            )}
            {alert.business_impact?.financial_impact_eur && (
              <div className="flex items-center gap-1 px-2 py-1 rounded-md bg-warning/10 text-warning text-xs">
                <DollarSign className="w-3 h-3" />
                <span>{currencySymbol}{alert.business_impact.financial_impact_eur.toFixed(0)} en riesgo</span>
              </div>
            )}
            {alert.urgency?.hours_until_consequence && (
              <div className="flex items-center gap-1 px-2 py-1 rounded-md bg-error/10 text-error text-xs">
                <Clock className="w-3 h-3" />
                <span>{formatTimeUntilConsequence(alert.urgency.hours_until_consequence)}</span>
              </div>
            )}
            {alert.trend_context && (
              <div className="flex items-center gap-1 px-2 py-1 rounded-md bg-info/10 text-info text-xs">
                <TrendingUp className="w-3 h-3" />
                <span>{alert.trend_context.change_percentage > 0 ? '+' : ''}{alert.trend_context.change_percentage.toFixed(1)}%</span>
              </div>
            )}
          </div>

          {/* AI Reasoning Summary */}
          {renderAIReasoning(alert, t) && (
            <div className="mb-3 p-2 rounded-md bg-primary/5 border border-primary/20">
              <div className="flex items-start gap-2">
                <Bot className="w-4 h-4 text-primary mt-0.5 flex-shrink-0" />
                <p className="text-xs text-[var(--text-secondary)] italic">
                  {renderAIReasoning(alert, t)}
                </p>
              </div>
            </div>
          )}

          {/* Smart Actions */}
          {alert.smart_actions && alert.smart_actions.length > 0 && (
            <div className={`flex flex-wrap gap-2 ${isMobile ? 'mb-3' : 'mb-2'}`}>
              {alert.smart_actions.slice(0, 3).map((action, idx) => (
                <Button
                  key={idx}
                  size={isMobile ? "sm" : "xs"}
                  variant={action.variant === 'primary' ? 'default' : 'ghost'}
                  onClick={() => actionHandler.handleAction(action)}
                  disabled={action.disabled}
                  className={`${isMobile ? 'text-xs' : 'text-[10px]'} ${
                    action.variant === 'danger' ? 'text-error hover:text-error-dark' : ''
                  }`}
                >
                  {action.action_type === 'call_supplier' && <Phone className="w-3 h-3 mr-1" />}
                  {action.action_type === 'navigate' && <ExternalLink className="w-3 h-3 mr-1" />}
                  {renderActionLabel(action, t)}
                  {action.estimated_time_minutes && (
                    <span className="ml-1 opacity-60">({action.estimated_time_minutes}m)</span>
                  )}
                </Button>
              ))}
            </div>
          )}

          {/* Standard Actions */}
          <div className={`flex items-center gap-2 ${isMobile ? 'flex-col sm:flex-row' : ''}`}>
            {isUnread && (
              <Button
                variant="ghost"
                size={isMobile ? "md" : "sm"}
                onClick={() => onMarkAsRead(alert.id)}
                className={`${isMobile ? 'w-full sm:w-auto px-4 py-2 text-sm' : 'h-6 px-2 text-xs'}`}
              >
                <Check className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
                Marcar como leído
              </Button>
            )}
            <Button
              variant="ghost"
              size={isMobile ? "md" : "sm"}
              onClick={() => onRemove(alert.id)}
              className={`text-[var(--color-error)] hover:text-[var(--color-error-dark)] ${
                isMobile ? 'w-full sm:w-auto px-4 py-2 text-sm' : 'h-6 px-2 text-xs'
              }`}
            >
              <Trash2 className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
              Eliminar
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

export const NotificationPanel: React.FC<NotificationPanelProps> = ({
  notifications,
  enrichedAlerts = [],
  isOpen,
  onClose,
  onMarkAsRead,
  onMarkAllAsRead,
  onRemoveNotification,
  onClearAll,
  className
}) => {
  if (!isOpen) return null;

  const actionHandler = useSmartActionHandler();
  const user = useAuthUser();

  // Memoize unread notifications to prevent recalculation on every render
  const unreadNotifications = React.useMemo(() =>
    notifications.filter(n => !n.read),
    [notifications]
  );

  const isMobile = window.innerWidth < 768;

  // Use enriched alerts if available, otherwise fallback to legacy notifications
  const useEnrichedAlerts = enrichedAlerts.length > 0;

  return (
    <>
      {/* Backdrop - Only on mobile */}
      {isMobile && (
        <div
          className="fixed inset-0 z-[9998] bg-black/50 backdrop-blur-sm transition-all duration-300"
          onClick={onClose}
          aria-hidden="true"
        />
      )}

      {/* Panel */}
      <div
        className={clsx(
          "fixed z-[9999] bg-[var(--bg-primary)] border border-[var(--border-primary)] shadow-2xl flex flex-col transition-all duration-300 ease-out",
          isMobile
            ? "inset-x-0 bottom-0 rounded-t-2xl max-h-[85vh]"
            : "right-0 top-full mt-2 w-96 max-w-sm rounded-xl shadow-xl max-h-96",
          className
        )}
      >
        {/* Mobile Handle */}
        {isMobile && (
          <div className="flex justify-center py-3">
            <div className="w-10 h-1 bg-[var(--border-secondary)] rounded-full" />
          </div>
        )}

        {/* Header */}
        <div className={`flex items-center justify-between border-b border-[var(--border-primary)] ${
          isMobile ? 'px-6 py-4' : 'px-4 py-3'
        }`}>
          <div className="flex items-center gap-2">
            <h3 className={`font-semibold text-[var(--text-primary)] ${
              isMobile ? 'text-lg' : 'text-sm'
            }`}>
              Notificaciones
            </h3>
            {unreadNotifications.length > 0 && (
              <Badge variant="info" size={isMobile ? "md" : "sm"}>
                {unreadNotifications.length} nuevas
              </Badge>
            )}
          </div>

          <div className="flex items-center gap-2">
            {unreadNotifications.length > 0 && (
              <Button
                variant="ghost"
                size={isMobile ? "md" : "sm"}
                onClick={onMarkAllAsRead}
                className={`${isMobile ? 'px-3 py-2 text-sm' : 'h-6 px-2 text-xs'}`}
              >
                <Check className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
                Marcar todas
              </Button>
            )}
            <Button
              variant="ghost"
              size={isMobile ? "md" : "sm"}
              onClick={onClose}
              className={`${isMobile ? 'p-2' : 'h-6 w-6 p-0'} hover:bg-[var(--bg-secondary)] rounded-full`}
            >
              <X className={`${isMobile ? 'w-5 h-5' : 'w-3 h-3'}`} />
            </Button>
          </div>
        </div>

        {/* Notifications List */}
        <div className={`flex-1 overflow-y-auto ${isMobile ? 'px-2 py-2' : ''}`}>
          {(useEnrichedAlerts ? enrichedAlerts.length === 0 : notifications.length === 0) ? (
            <div className={`text-center ${isMobile ? 'py-12 px-6' : 'p-8'}`}>
              <CheckCircle className={`mx-auto mb-3 ${isMobile ? 'w-12 h-12' : 'w-8 h-8'}`} style={{ color: 'var(--color-success)' }} />
              <p className={`text-[var(--text-secondary)] ${isMobile ? 'text-base' : 'text-sm'}`}>
                No hay notificaciones
              </p>
            </div>
          ) : (
            <div className="divide-y divide-[var(--border-primary)]">
              {useEnrichedAlerts ? (
                // Render enriched alerts
                enrichedAlerts
                  .sort((a, b) => b.priority_score - a.priority_score)
                  .map((alert) => (
                    <EnrichedAlertItem
                      key={alert.id}
                      alert={alert}
                      isMobile={isMobile}
                      onMarkAsRead={onMarkAsRead}
                      onRemove={onRemoveNotification}
                      actionHandler={actionHandler}
                    />
                  ))
              ) : (
                // Render notifications as enriched alerts (NotificationData now has enriched fields)
                notifications
                  .sort((a, b) => b.priority_score - a.priority_score)
                  .map((notification) => (
                    <EnrichedAlertItem
                      key={notification.id}
                      alert={{
                        ...notification,
                        event_class: 'alert',
                        tenant_id: user?.tenant_id || '',
                        status: notification.read ? 'acknowledged' : 'active',
                        created_at: notification.timestamp,
                        event_metadata: notification.metadata || {},
                        service: 'notification-service',
                        event_type: notification.item_type,
                        event_domain: 'notification',
                        smart_actions: notification.actions || [],
                        entity_links: {},
                        i18n: {
                          title_key: notification.title || '',
                          message_key: notification.message || '',
                          title_params: {},
                          message_params: {}
                        }
                      } as Alert}
                      isMobile={isMobile}
                      onMarkAsRead={onMarkAsRead}
                      onRemove={onRemoveNotification}
                      actionHandler={actionHandler}
                    />
                  ))
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        {notifications.length > 0 && (
          <div className={`border-t border-[var(--border-primary)] bg-[var(--bg-secondary)] ${
            isMobile ? 'px-6 py-4' : 'p-3'
          }`}>
            <Button
              variant="ghost"
              size={isMobile ? "md" : "sm"}
              onClick={onClearAll}
              className={`w-full text-[var(--color-error)] hover:text-[var(--color-error-dark)] ${
                isMobile ? 'px-4 py-3 text-sm' : 'text-xs'
              }`}
            >
              <Trash2 className={`${isMobile ? 'w-4 h-4 mr-2' : 'w-3 h-3 mr-1'}`} />
              Limpiar todas las notificaciones
            </Button>
          </div>
        )}
      </div>
    </>
  );
};