import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  AlertTriangle,
  AlertCircle,
  Info,
  CheckCircle,
  Check,
  Trash2,
  Clock,
  MoreVertical,
  ChevronDown,
  ChevronUp,
} from 'lucide-react';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import type { NotificationData } from '../../../hooks/useNotifications';
import { getSnoozedTimeRemaining, categorizeAlert } from '../../../utils/alertHelpers';
import AlertContextActions from './AlertContextActions';
import AlertSnoozeMenu from './AlertSnoozeMenu';

export interface AlertCardProps {
  alert: NotificationData;
  isExpanded: boolean;
  isSelected: boolean;
  isSnoozed: boolean;
  snoozedUntil?: number;
  onToggleExpand: () => void;
  onToggleSelect: () => void;
  onMarkAsRead: () => void;
  onRemove: () => void;
  onSnooze: (duration: '15min' | '1hr' | '4hr' | 'tomorrow' | number) => void;
  onUnsnooze: () => void;
  showCheckbox?: boolean;
}

const getSeverityIcon = (severity: string) => {
  switch (severity) {
    case 'urgent':
      return AlertTriangle;
    case 'high':
      return AlertCircle;
    case 'medium':
      return Info;
    case 'low':
      return CheckCircle;
    default:
      return Info;
  }
};

const getSeverityColor = (severity: string) => {
  switch (severity) {
    case 'urgent':
      return 'var(--color-error)';
    case 'high':
      return 'var(--color-warning)';
    case 'medium':
      return 'var(--color-info)';
    case 'low':
      return 'var(--color-success)';
    default:
      return 'var(--color-info)';
  }
};

const getSeverityBadge = (severity: string): 'error' | 'warning' | 'info' | 'success' => {
  switch (severity) {
    case 'urgent':
      return 'error';
    case 'high':
      return 'warning';
    case 'medium':
      return 'info';
    case 'low':
      return 'success';
    default:
      return 'info';
  }
};

const formatTimestamp = (timestamp: string, t: any) => {
  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 t('dashboard:alerts.time.now', 'Ahora');
  if (diffMins < 60) return t('dashboard:alerts.time.minutes_ago', 'hace {{count}} min', { count: diffMins });
  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return t('dashboard:alerts.time.hours_ago', 'hace {{count}} h', { count: diffHours });
  return date.toLocaleDateString() === new Date(now.getTime() - 24 * 60 * 60 * 1000).toLocaleDateString()
    ? t('dashboard:alerts.time.yesterday', 'Ayer')
    : date.toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' });
};

const AlertCard: React.FC<AlertCardProps> = ({
  alert,
  isExpanded,
  isSelected,
  isSnoozed,
  snoozedUntil,
  onToggleExpand,
  onToggleSelect,
  onMarkAsRead,
  onRemove,
  onSnooze,
  onUnsnooze,
  showCheckbox = false,
}) => {
  const { t } = useTranslation(['dashboard']);
  const [showSnoozeMenu, setShowSnoozeMenu] = useState(false);
  const [showActions, setShowActions] = useState(false);
  const [isHovered, setIsHovered] = useState(false);

  const SeverityIcon = getSeverityIcon(alert.severity);
  const severityColor = getSeverityColor(alert.severity);

  const handleSnooze = (duration: '15min' | '1hr' | '4hr' | 'tomorrow' | number) => {
    onSnooze(duration);
    setShowSnoozeMenu(false);
  };

  const category = categorizeAlert(alert);

  return (
    <div
      className={`
        rounded-lg transition-all duration-200 relative overflow-hidden
        ${isExpanded ? 'shadow-md' : 'hover:shadow-md'}
        ${isSelected ? 'ring-2 ring-[var(--color-primary)] ring-offset-2' : ''}
        ${isSnoozed ? 'opacity-75' : ''}
      `}
      style={{
        backgroundColor: 'var(--bg-primary)',
        border: '1px solid var(--border-primary)',
        ...(isExpanded && {
          backgroundColor: 'var(--bg-secondary)',
        }),
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* Left severity accent border */}
      <div
        className="absolute left-0 top-0 bottom-0 w-1"
        style={{ backgroundColor: severityColor }}
      />

      {/* Compact Card Header */}
      <div className="flex items-start gap-3 p-4 pl-5">
        {/* Checkbox for selection */}
        {showCheckbox && (
          <div className="flex-shrink-0 pt-0.5">
            <input
              type="checkbox"
              checked={isSelected}
              onChange={(e) => {
                e.stopPropagation();
                onToggleSelect();
              }}
              className="w-4 h-4 rounded border-[var(--border-primary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)] focus:ring-offset-0 cursor-pointer"
              aria-label={`Select alert: ${alert.title}`}
            />
          </div>
        )}

        {/* Severity Icon */}
        <div
          className="flex-shrink-0 p-2 rounded-lg cursor-pointer hover:scale-105 transition-transform"
          style={{ backgroundColor: severityColor + '15' }}
          onClick={onToggleExpand}
          aria-label="Toggle alert details"
        >
          <SeverityIcon
            className="w-5 h-5"
            style={{ color: severityColor }}
          />
        </div>

        {/* Alert Content */}
        <div className="flex-1 min-w-0 cursor-pointer" onClick={onToggleExpand}>
          {/* Title and Status */}
          <div className="flex items-start justify-between gap-3 mb-1.5">
            <div className="flex-1 min-w-0">
              <h4 className="text-base font-semibold leading-snug mb-1" style={{ color: 'var(--text-primary)' }}>
                {alert.title}
              </h4>
              <div className="flex items-center gap-2 flex-wrap">
                {/* Single primary severity badge */}
                <Badge variant={getSeverityBadge(alert.severity)} size="sm" className="font-semibold px-2.5 py-1 min-h-[1.375rem]">
                  {t(`dashboard:alerts.severity.${alert.severity}`, alert.severity.toUpperCase())}
                </Badge>

                {/* Unread indicator */}
                {!alert.read && (
                  <span className="inline-flex items-center gap-1.5 text-xs font-medium px-2 py-1 rounded-md bg-blue-50 dark:bg-blue-900/20 min-h-[1.375rem]" style={{ color: 'var(--color-info)' }}>
                    <span className="w-2 h-2 rounded-full bg-[var(--color-info)] animate-pulse flex-shrink-0" />
                    {t('dashboard:alerts.status.new', 'Nuevo')}
                  </span>
                )}

                {/* Snoozed indicator */}
                {isSnoozed && snoozedUntil && (
                  <span className="inline-flex items-center gap-1.5 text-xs font-medium px-2 py-1 rounded-md bg-gray-50 dark:bg-gray-800 min-h-[1.375rem]" style={{ color: 'var(--text-secondary)' }}>
                    <Clock className="w-3 h-3 flex-shrink-0" />
                    <span className="whitespace-nowrap">{getSnoozedTimeRemaining(alert.id, new Map([[alert.id, { alertId: alert.id, until: snoozedUntil }]]))}</span>
                  </span>
                )}
              </div>
            </div>

            {/* Timestamp */}
            <span className="text-xs font-medium flex-shrink-0 pt-0.5" style={{ color: 'var(--text-secondary)' }}>
              {formatTimestamp(alert.timestamp, t)}
            </span>
          </div>

          {/* Preview message when collapsed */}
          {!isExpanded && alert.message && (
            <p
              className="text-sm leading-relaxed mt-2 overflow-hidden"
              style={{
                color: 'var(--text-secondary)',
                display: '-webkit-box',
                WebkitLineClamp: 2,
                WebkitBoxOrient: 'vertical',
              }}
            >
              {alert.message}
            </p>
          )}
        </div>

        {/* Actions - shown on hover or when expanded */}
        <div className={`flex-shrink-0 flex items-center gap-1 transition-opacity ${isHovered || isExpanded || showActions ? 'opacity-100' : 'opacity-0'}`}>
          {/* Quick action buttons */}
          {!alert.read && !isExpanded && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                onMarkAsRead();
              }}
              className="p-1.5 rounded-md hover:bg-[var(--bg-tertiary)] transition-colors"
              title={t('dashboard:alerts.mark_as_read', 'Marcar como leído')}
              aria-label="Mark as read"
            >
              <Check className="w-4 h-4" style={{ color: 'var(--color-success)' }} />
            </button>
          )}

          <button
            onClick={(e) => {
              e.stopPropagation();
              setShowActions(!showActions);
            }}
            className="p-1.5 rounded-md hover:bg-[var(--bg-tertiary)] transition-colors"
            aria-label="More actions"
            title="More actions"
          >
            <MoreVertical className="w-4 h-4" style={{ color: 'var(--text-secondary)' }} />
          </button>

          <button
            onClick={(e) => {
              e.stopPropagation();
              onToggleExpand();
            }}
            className="p-1.5 rounded-md hover:bg-[var(--bg-tertiary)] transition-colors"
            aria-label={isExpanded ? "Collapse" : "Expand"}
            title={isExpanded ? "Collapse" : "Expand"}
          >
            {isExpanded ? (
              <ChevronUp className="w-4 h-4" style={{ color: 'var(--text-secondary)' }} />
            ) : (
              <ChevronDown className="w-4 h-4" style={{ color: 'var(--text-secondary)' }} />
            )}
          </button>
        </div>
      </div>

      {/* Quick Actions Menu - Better positioning */}
      {showActions && (
        <>
          <div
            className="fixed inset-0 z-20"
            onClick={() => setShowActions(false)}
            aria-hidden="true"
          />
          <div className="absolute right-3 top-16 z-30 bg-[var(--bg-primary)] border border-[var(--border-primary)] rounded-lg shadow-xl py-1 min-w-[180px]">
            {!alert.read && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onMarkAsRead();
                  setShowActions(false);
                }}
                className="w-full px-4 py-2 text-left text-sm hover:bg-[var(--bg-secondary)] transition-colors flex items-center gap-2"
                style={{ color: 'var(--text-primary)' }}
              >
                <Check className="w-4 h-4" style={{ color: 'var(--color-success)' }} />
                Marcar como leído
              </button>
            )}
            <button
              onClick={(e) => {
                e.stopPropagation();
                setShowSnoozeMenu(true);
                setShowActions(false);
              }}
              className="w-full px-4 py-2 text-left text-sm hover:bg-[var(--bg-secondary)] transition-colors flex items-center gap-2"
              style={{ color: 'var(--text-primary)' }}
            >
              <Clock className="w-4 h-4" />
              {isSnoozed ? 'Cambiar tiempo' : 'Posponer'}
            </button>
            {isSnoozed && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onUnsnooze();
                  setShowActions(false);
                }}
                className="w-full px-4 py-2 text-left text-sm hover:bg-[var(--bg-secondary)] transition-colors flex items-center gap-2"
                style={{ color: 'var(--text-primary)' }}
              >
                <Clock className="w-4 h-4" />
                Reactivar ahora
              </button>
            )}
            <div className="my-1 border-t border-[var(--border-primary)]" />
            <button
              onClick={(e) => {
                e.stopPropagation();
                onRemove();
                setShowActions(false);
              }}
              className="w-full px-4 py-2 text-left text-sm hover:bg-red-50 dark:hover:bg-red-900/20 text-red-600 transition-colors flex items-center gap-2"
            >
              <Trash2 className="w-4 h-4" />
              Eliminar
            </button>
          </div>
        </>
      )}

      {/* Snooze Menu - Better positioning */}
      {showSnoozeMenu && (
        <>
          <div
            className="fixed inset-0 z-20"
            onClick={() => setShowSnoozeMenu(false)}
            aria-hidden="true"
          />
          <div className="absolute right-3 top-16 z-30">
            <AlertSnoozeMenu
              onSnooze={handleSnooze}
              onCancel={() => setShowSnoozeMenu(false)}
            />
          </div>
        </>
      )}

      {/* Expanded Details */}
      {isExpanded && (
        <div className="px-5 pb-4 border-t pt-4" style={{ borderColor: 'var(--border-primary)' }}>
          {/* Full Message */}
          <div className="mb-4">
            <p className="text-sm leading-relaxed" style={{ color: 'var(--text-primary)' }}>
              {alert.message}
            </p>
          </div>

          {/* Metadata */}
          {alert.metadata && Object.keys(alert.metadata).length > 0 && (
            <div className="mb-4 p-3 rounded-lg border" style={{
              backgroundColor: 'var(--bg-tertiary)',
              borderColor: 'var(--border-primary)'
            }}>
              <p className="text-xs font-semibold mb-2 uppercase tracking-wide" style={{ color: 'var(--text-primary)' }}>
                {t('dashboard:alerts.additional_details', 'Detalles Adicionales')}
              </p>
              <div className="text-sm space-y-2" style={{ color: 'var(--text-secondary)' }}>
                {Object.entries(alert.metadata).map(([key, value]) => (
                  <div key={key} className="flex justify-between gap-4">
                    <span className="font-medium capitalize text-[var(--text-primary)]">{key.replace(/_/g, ' ')}:</span>
                    <span className="text-right">{String(value)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Contextual Actions */}
          <div className="mb-4">
            <AlertContextActions alert={alert} />
          </div>

          {/* Action Buttons */}
          <div className="flex items-center gap-2 flex-wrap">
            {!alert.read && (
              <Button
                variant="primary"
                size="sm"
                onClick={(e) => {
                  e.stopPropagation();
                  onMarkAsRead();
                }}
                className="h-9 px-4 text-sm font-medium"
              >
                <Check className="w-4 h-4 mr-2" />
                {t('dashboard:alerts.mark_as_read', 'Marcar como leído')}
              </Button>
            )}
            <Button
              variant="outline"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                setShowSnoozeMenu(true);
              }}
              className="h-9 px-4 text-sm font-medium"
            >
              <Clock className="w-4 h-4 mr-2" />
              {isSnoozed ? 'Cambiar' : 'Posponer'}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                onRemove();
              }}
              className="h-9 px-4 text-sm font-medium text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              {t('dashboard:alerts.remove', 'Eliminar')}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

export default AlertCard;
