import React from 'react';
import { LucideIcon } from 'lucide-react';
import { Card } from '../Card';
import { ProgressBar } from '../ProgressBar';
import { statusColors } from '../../../styles/colors';
import { TextOverflowPrevention, overflowClasses, getScreenSize, safeText } from '../../../utils/textUtils';

export interface StatusIndicatorConfig {
  color: string;
  text: string;
  icon?: LucideIcon;
  isCritical?: boolean;
  isHighlight?: boolean;
}

export interface StatusCardProps {
  id: string;
  statusIndicator: StatusIndicatorConfig;
  title: string;
  subtitle?: string;
  primaryValue: string | number;
  primaryValueLabel?: string;
  secondaryInfo?: {
    label: string;
    value: string;
  };
  progress?: {
    label: string;
    percentage: number;
    color?: string;
  };
  metadata?: string[];
  actions?: Array<{
    label: string;
    icon?: LucideIcon;
    variant?: 'primary' | 'outline';
    onClick: () => void;
    priority?: 'primary' | 'secondary' | 'tertiary';
    destructive?: boolean;
    highlighted?: boolean;
    disabled?: boolean;
  }>;
  onClick?: () => void;
  className?: string;
  compact?: boolean;
}

/**
 * Get status color configuration from the global palette
 */
export const getStatusColor = (status: string): StatusIndicatorConfig['color'] => {
  // Normalize status key (handle different formats)
  const normalizedStatus = status.toLowerCase().replace(/[_-]/g, '').replace(/\s+/g, '');
  
  // Map common status variations to our palette
  const statusMap: { [key: string]: keyof typeof statusColors } = {
    'pending': 'pending',
    'inprogress': 'inProgress',
    'completed': 'completed',
    'cancelled': 'cancelled',
    'normal': 'normal',
    'low': 'low',
    'out': 'out',
    'expired': 'expired',
    'approved': 'approved',
    'intransit': 'inTransit',
    'delivered': 'delivered',
    'bread': 'bread',
    'pastry': 'pastry',
    'cake': 'cake',
    'cookie': 'cookie',
    'other': 'other',
  };

  const mappedStatus = statusMap[normalizedStatus];
  return mappedStatus ? statusColors[mappedStatus].primary : statusColors.other.primary;
};

/**
 * StatusCard - Reusable card component with consistent status styling
 */
export const StatusCard: React.FC<StatusCardProps> = ({
  id: _id,
  statusIndicator,
  title,
  subtitle,
  primaryValue,
  primaryValueLabel,
  secondaryInfo,
  progress,
  metadata = [],
  actions = [],
  onClick,
  className = '',
  compact: _compact = false,
}) => {
  const StatusIcon = statusIndicator.icon;
  const hasInteraction = onClick || actions.length > 0;

  // Detect screen size for responsive truncation
  const screenSize = React.useMemo(() => getScreenSize(), []);
  const isMobile = screenSize === 'mobile';

  // Apply truncation based on screen size
  const truncationEngine = isMobile ? TextOverflowPrevention.mobile : TextOverflowPrevention.statusCard;

  // Sort actions by priority
  const sortedActions = [...actions].sort((a, b) => {
    const priorityOrder = { primary: 0, secondary: 1, tertiary: 2 };
    const aPriority = priorityOrder[a.priority || 'secondary'];
    const bPriority = priorityOrder[b.priority || 'secondary'];
    return aPriority - bPriority;
  });

  // Split actions into primary and secondary groups
  const primaryActions = sortedActions.filter(action => action.priority === 'primary');
  const secondaryActions = sortedActions.filter(action => action.priority !== 'primary');


  return (
    <Card
      className={`
        p-3 sm:p-5 lg:p-6 transition-all duration-200 border-l-4 hover:shadow-lg
        ${hasInteraction ? 'hover:shadow-xl cursor-pointer hover:scale-[1.01]' : ''}
        ${statusIndicator.isCritical
          ? 'ring-2 ring-red-200 shadow-md sm:border-l-6 lg:border-l-8'
          : statusIndicator.isHighlight
            ? 'ring-1 ring-yellow-200 sm:border-l-6'
            : ''
        }
        ${className}
      `}
      style={{
        borderLeftColor: statusIndicator.color,
        backgroundColor: statusIndicator.isCritical
          ? `${statusIndicator.color}08`
          : statusIndicator.isHighlight
            ? `${statusIndicator.color}05`
            : undefined
      }}
      onClick={onClick}
    >
      <div className="space-y-3 sm:space-y-4">
        {/* Header with status indicator */}
        <div className="flex items-start justify-between gap-2 sm:gap-4">
          <div className="flex items-start gap-2 sm:gap-3 flex-1 min-w-0">
            <div
              className={`flex-shrink-0 p-1.5 sm:p-2.5 lg:p-3 rounded-lg shadow-sm ${
                statusIndicator.isCritical ? 'ring-2 ring-white' : ''
              }`}
              style={{ backgroundColor: `${statusIndicator.color}20` }}
            >
              {StatusIcon && (
                <StatusIcon
                  className="w-4 h-4 sm:w-5 sm:h-5 lg:w-6 lg:h-6"
                  style={{ color: statusIndicator.color }}
                />
              )}
            </div>
            <div className="flex-1 min-w-0">
              <div
                className={`font-semibold text-[var(--text-primary)] text-sm sm:text-base lg:text-lg leading-tight mb-1 sm:mb-2 ${overflowClasses.truncate}`}
                title={title}
              >
                {truncationEngine.title(title)}
              </div>
              {subtitle && (
                <div
                  className={`text-xs sm:text-sm text-[var(--text-secondary)] mb-1 sm:mb-2 ${overflowClasses.truncate}`}
                  title={subtitle}
                >
                  {truncationEngine.subtitle(subtitle)}
                </div>
              )}
              <div className="flex items-center gap-2">
                <div
                  className={`inline-flex items-center px-2 py-1 sm:px-3 sm:py-1.5 rounded-full text-xs font-medium transition-all ${
                    statusIndicator.isCritical
                      ? 'bg-red-100 text-red-800 ring-2 ring-red-300 shadow-sm animate-pulse'
                      : statusIndicator.isHighlight
                      ? 'bg-yellow-100 text-yellow-800 ring-1 ring-yellow-300 shadow-sm'
                      : 'ring-1 shadow-sm'
                  } max-w-full sm:max-w-[220px]`}
                  style={{
                    backgroundColor: statusIndicator.isCritical || statusIndicator.isHighlight
                      ? undefined
                      : `${statusIndicator.color}20`,
                    color: statusIndicator.isCritical || statusIndicator.isHighlight
                      ? undefined
                      : statusIndicator.color,
                    borderColor: `${statusIndicator.color}40`
                  }}
                >
                  {statusIndicator.isCritical && (
                    <span className="mr-1.5 text-sm flex-shrink-0">🚨</span>
                  )}
                  {statusIndicator.isHighlight && (
                    <span className="mr-1.5 flex-shrink-0">⚠️</span>
                  )}
                  <span
                    className={`${overflowClasses.truncate} flex-1`}
                    title={statusIndicator.text}
                  >
                    {safeText(statusIndicator.text, statusIndicator.text, isMobile ? 20 : 28)}
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div className="text-right flex-shrink-0 min-w-[60px] sm:min-w-[80px] max-w-[100px] sm:max-w-[140px] lg:max-w-[160px]">
            <div
              className={`text-xl sm:text-2xl lg:text-3xl font-bold text-[var(--text-primary)] leading-none mb-0.5 sm:mb-1 ${overflowClasses.truncate}`}
              title={primaryValue?.toString()}
            >
              {safeText(primaryValue?.toString(), '0', isMobile ? 10 : 18)}
            </div>
            {primaryValueLabel && (
              <div
                className={`text-[10px] sm:text-xs text-[var(--text-tertiary)] uppercase tracking-wide ${overflowClasses.truncate}`}
                title={primaryValueLabel}
              >
                {truncationEngine.primaryValueLabel(primaryValueLabel)}
              </div>
            )}
          </div>
        </div>

        {/* Secondary info - Mobile optimized */}
        {secondaryInfo && (
          <div className="flex items-center justify-between text-xs sm:text-sm gap-2 min-w-0">
            <span
              className={`text-[var(--text-secondary)] flex-shrink-0 ${overflowClasses.truncate} max-w-[80px] sm:max-w-[120px]`}
              title={secondaryInfo.label}
            >
              {truncationEngine.secondaryLabel(secondaryInfo.label)}
            </span>
            <span
              className={`font-medium text-[var(--text-primary)] text-right flex-1 ${overflowClasses.truncate}`}
              title={secondaryInfo.value}
            >
              {truncationEngine.secondaryValue(secondaryInfo.value)}
            </span>
          </div>
        )}

        {/* Progress indicator */}
        {progress && (
          <div className="space-y-2 sm:space-y-3">
            <ProgressBar
              value={progress.percentage}
              max={100}
              size="md"
              variant="default"
              showLabel={true}
              label={truncationEngine.progressLabel(progress.label)}
              animated={progress.percentage < 100}
              customColor={progress.color || statusIndicator.color}
              className="w-full"
              glow={progress.percentage > 10 && progress.percentage < 90}
            />
          </div>
        )}


        {/* Metadata - Improved mobile layout with overflow prevention */}
        {metadata.length > 0 && (
          <div className="text-[10px] sm:text-xs text-[var(--text-secondary)] space-y-0.5 sm:space-y-1">
            {metadata.slice(0, isMobile ? 2 : 4).map((item, index) => (
              <div
                key={index}
                className={`${overflowClasses.truncate} ${overflowClasses.breakWords} leading-tight`}
                title={item}
              >
                {truncationEngine.metadataItem(item)}
              </div>
            ))}
            {metadata.length > (isMobile ? 2 : 4) && (
              <div className="text-[var(--text-tertiary)] italic text-[10px]">
                +{metadata.length - (isMobile ? 2 : 4)} más...
              </div>
            )}
          </div>
        )}

        {/* Simplified Action System - Mobile optimized */}
        {actions.length > 0 && (
          <div className="pt-2 sm:pt-4 border-t border-[var(--border-primary)]">
            {/* All actions in a clean horizontal layout */}
            <div className="flex items-center justify-between gap-2 sm:gap-3 flex-wrap">

              {/* Primary action as a subtle text button */}
              {primaryActions.length > 0 && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    if (!primaryActions[0].disabled) {
                      primaryActions[0].onClick();
                    }
                  }}
                  disabled={primaryActions[0].disabled}
                  className={`
                    flex items-center gap-1.5 sm:gap-2 px-2 py-1.5 sm:px-3 sm:py-2 text-xs sm:text-sm font-medium rounded-lg
                    transition-all duration-200 hover:scale-105 active:scale-95 flex-shrink-0 max-w-[120px] sm:max-w-[160px]
                    ${primaryActions[0].disabled
                      ? 'opacity-50 cursor-not-allowed'
                      : primaryActions[0].destructive
                        ? 'text-red-600 hover:bg-red-50 hover:text-red-700'
                        : 'text-[var(--color-primary-600)] hover:bg-[var(--color-primary-50)] hover:text-[var(--color-primary-700)]'
                    }
                  `}
                  title={primaryActions[0].label}
                >
                  {primaryActions[0].icon && React.createElement(primaryActions[0].icon, { className: "w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" })}
                  <span className={`${overflowClasses.truncate} flex-1`}>
                    {truncationEngine.actionLabel(primaryActions[0].label)}
                  </span>
                </button>
              )}

              {/* Action icons for secondary actions */}
              <div className="flex items-center gap-1.5 sm:gap-2">
                {secondaryActions.map((action, index) => (
                  <button
                    key={`action-${index}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      if (!action.disabled) {
                        action.onClick();
                      }
                    }}
                    disabled={action.disabled}
                    title={action.label}
                    className={`
                      p-1.5 sm:p-2 rounded-lg transition-all duration-200 hover:scale-110 active:scale-95 hover:shadow-sm
                      ${action.disabled
                        ? 'opacity-50 cursor-not-allowed'
                        : action.destructive
                          ? 'text-red-500 hover:bg-red-50 hover:text-red-600'
                          : action.highlighted
                            ? 'text-[var(--color-primary-500)] hover:text-[var(--color-primary-600)] hover:bg-[var(--color-primary-50)]'
                            : 'text-[var(--text-tertiary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]'
                      }
                    `}
                  >
                    {action.icon && React.createElement(action.icon, { className: "w-3.5 h-3.5 sm:w-4 sm:h-4" })}
                  </button>
                ))}

                {/* Include additional primary actions as icons */}
                {primaryActions.slice(1).map((action, index) => (
                  <button
                    key={`primary-icon-${index}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      if (!action.disabled) {
                        action.onClick();
                      }
                    }}
                    disabled={action.disabled}
                    title={action.label}
                    className={`
                      p-1.5 sm:p-2 rounded-lg transition-all duration-200 hover:scale-110 active:scale-95 hover:shadow-sm
                      ${action.disabled
                        ? 'opacity-50 cursor-not-allowed'
                        : action.destructive
                          ? 'text-red-500 hover:bg-red-50 hover:text-red-600'
                          : 'text-[var(--color-primary-500)] hover:text-[var(--color-primary-600)] hover:bg-[var(--color-primary-50)]'
                      }
                    `}
                  >
                    {action.icon && React.createElement(action.icon, { className: "w-3.5 h-3.5 sm:w-4 sm:h-4" })}
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </Card>
  );
};

export default StatusCard;