import React from 'react';
import { LucideIcon } from 'lucide-react';
import { Card } from '../Card';
import { Button } from '../Button';
import { ProgressBar } from '../ProgressBar';
import { statusColors } from '../../../styles/colors';

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;
  }>;
  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;

  // 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-4 sm: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 border-l-6 sm:border-l-8'
          : statusIndicator.isHighlight
            ? 'ring-1 ring-yellow-200 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-4 sm:space-y-5">
        {/* Header with status indicator */}
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-4 flex-1">
            <div
              className={`flex-shrink-0 p-2 sm:p-3 rounded-xl 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"
                  style={{ color: statusIndicator.color }}
                />
              )}
            </div>
            <div className="flex-1 min-w-0">
              <div className="font-semibold text-[var(--text-primary)] text-base sm:text-lg leading-tight mb-1 truncate">
                {title}
              </div>
              <div className="flex items-center gap-2 mb-1">
                <div
                  className={`inline-flex items-center px-2 sm:px-3 py-1 sm:py-1.5 rounded-full text-xs font-semibold 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'
                  }`}
                  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-2 text-sm">🚨</span>
                  )}
                  {statusIndicator.isHighlight && (
                    <span className="mr-1.5">⚠️</span>
                  )}
                  {statusIndicator.text}
                </div>
              </div>
              {subtitle && (
                <div className="text-sm text-[var(--text-secondary)] truncate">
                  {subtitle}
                </div>
              )}
            </div>
          </div>
          <div className="text-right flex-shrink-0 ml-4 min-w-0">
            <div className="text-2xl sm:text-3xl font-bold text-[var(--text-primary)] leading-none truncate">
              {primaryValue}
            </div>
            {primaryValueLabel && (
              <div className="text-xs text-[var(--text-tertiary)] uppercase tracking-wide mt-1 truncate">
                {primaryValueLabel}
              </div>
            )}
          </div>
        </div>

        {/* Secondary info - Mobile optimized */}
        {secondaryInfo && (
          <div className="flex items-center justify-between text-sm gap-2">
            <span className="text-[var(--text-secondary)] truncate flex-shrink-0">
              {secondaryInfo.label}
            </span>
            <span className="font-medium text-[var(--text-primary)] truncate text-right">
              {secondaryInfo.value}
            </span>
          </div>
        )}

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


        {/* Metadata - Improved mobile layout */}
        {metadata.length > 0 && (
          <div className="text-xs text-[var(--text-secondary)] space-y-1">
            {metadata.map((item, index) => (
              <div key={index} className="truncate" title={item}>{item}</div>
            ))}
          </div>
        )}

        {/* Simplified Action System - Mobile optimized */}
        {actions.length > 0 && (
          <div className="pt-3 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 flex-wrap">

              {/* Primary action as a subtle text button */}
              {primaryActions.length > 0 && (
                <button
                  onClick={primaryActions[0].onClick}
                  className={`
                    flex items-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 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
                    ${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)]'
                    }
                  `}
                >
                  {primaryActions[0].icon && React.createElement(primaryActions[0].icon, { className: "w-3 h-3 sm:w-4 sm:h-4" })}
                  <span className="truncate">{primaryActions[0].label}</span>
                </button>
              )}

              {/* Action icons for secondary actions */}
              <div className="flex items-center gap-1">
                {secondaryActions.map((action, index) => (
                  <button
                    key={`action-${index}`}
                    onClick={action.onClick}
                    title={action.label}
                    className={`
                      p-1.5 sm:p-2 rounded-lg transition-all duration-200 hover:scale-110 active:scale-95
                      ${action.destructive
                        ? 'text-red-500 hover:bg-red-50 hover:text-red-600'
                        : 'text-[var(--text-tertiary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-secondary)]'
                      }
                    `}
                  >
                    {action.icon && React.createElement(action.icon, { className: "w-3 h-3 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={action.onClick}
                    title={action.label}
                    className={`
                      p-1.5 sm:p-2 rounded-lg transition-all duration-200 hover:scale-110 active:scale-95
                      ${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 h-3 sm:w-4 sm:h-4" })}
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </Card>
  );
};

export default StatusCard;