import React from 'react';
import { Clock, Timer, CheckCircle, AlertCircle, Package, Play, Pause, X, Eye, Info } from 'lucide-react';
import { StatusCard, StatusIndicatorConfig } from '../../ui/StatusCard/StatusCard';
import { statusColors } from '../../../styles/colors';
import { ProductionBatchResponse, ProductionStatus, ProductionPriority } from '../../../api/types/production';
import { useTranslation } from 'react-i18next';
import { TextOverflowPrevention, safeText } from '../../../utils/textUtils';

export interface ProductionStatusCardProps {
  batch: ProductionBatchResponse;
  onView?: (batch: ProductionBatchResponse) => void;
  onEdit?: (batch: ProductionBatchResponse) => void;
  onStart?: (batch: ProductionBatchResponse) => void;
  onPause?: (batch: ProductionBatchResponse) => void;
  onComplete?: (batch: ProductionBatchResponse) => void;
  onCancel?: (batch: ProductionBatchResponse) => void;
  onQualityCheck?: (batch: ProductionBatchResponse) => void;
  onViewHistory?: (batch: ProductionBatchResponse) => void;
  showDetailedProgress?: boolean;
  compact?: boolean;
}

export const ProductionStatusCard: React.FC<ProductionStatusCardProps> = ({
  batch,
  onView,
  onEdit,
  onStart,
  onPause,
  onComplete,
  onCancel,
  onQualityCheck,
  onViewHistory,
  showDetailedProgress = true,
  compact = false
}) => {
  const { t } = useTranslation(['production', 'common']);

  const getProductionStatusConfig = (status: ProductionStatus, priority: ProductionPriority): StatusIndicatorConfig => {
    const statusConfig = {
      [ProductionStatus.PENDING]: { icon: Clock },
      [ProductionStatus.IN_PROGRESS]: { icon: Timer },
      [ProductionStatus.COMPLETED]: { icon: CheckCircle },
      [ProductionStatus.CANCELLED]: { icon: X },
      [ProductionStatus.ON_HOLD]: { icon: Pause },
      [ProductionStatus.QUALITY_CHECK]: { icon: Package },
      [ProductionStatus.FAILED]: { icon: AlertCircle },
    };

    const config = statusConfig[status] || { icon: AlertCircle };
    const Icon = config.icon;
    const isUrgent = priority === ProductionPriority.URGENT;
    const isCritical = status === ProductionStatus.FAILED ||
                      status === ProductionStatus.CANCELLED ||
                      (status === ProductionStatus.PENDING && isUrgent);
    const isHighlight = isUrgent && status !== ProductionStatus.FAILED && status !== ProductionStatus.CANCELLED;

    const getStatusColorForProduction = (status: ProductionStatus) => {
      const normalizedStatus = status.toLowerCase();
      switch (normalizedStatus) {
        case 'pending':
          return statusColors.pending.primary;
        case 'in_progress':
          return statusColors.inProgress.primary;
        case 'completed':
          return statusColors.completed.primary;
        case 'cancelled':
        case 'failed':
          return statusColors.cancelled.primary;
        case 'on_hold':
          return statusColors.pending.primary;
        case 'quality_check':
          return statusColors.inProgress.primary;
        default:
          return statusColors.other.primary;
      }
    };

    return {
      color: getStatusColorForProduction(status),
      text: t(`production:status.${status.toLowerCase()}`),
      icon: Icon,
      isCritical,
      isHighlight
    };
  };

  const calculateDetailedProgress = (batch: ProductionBatchResponse): number => {
    if (batch.status === ProductionStatus.COMPLETED) return 100;
    if (batch.status === ProductionStatus.PENDING) return 0;
    if (batch.status === ProductionStatus.CANCELLED || batch.status === ProductionStatus.FAILED) return 0;

    if (batch.actual_start_time && batch.planned_end_time) {
      const now = new Date();
      const startTime = new Date(batch.actual_start_time);
      const endTime = new Date(batch.planned_end_time);
      const totalDuration = endTime.getTime() - startTime.getTime();
      const elapsed = now.getTime() - startTime.getTime();

      if (totalDuration > 0) {
        return Math.min(90, Math.max(10, Math.round((elapsed / totalDuration) * 100)));
      }
    }

    if (batch.status === ProductionStatus.QUALITY_CHECK) return 85;
    if (batch.status === ProductionStatus.ON_HOLD) return 50;

    return 50;
  };

  const getProgressLabel = (batch: ProductionBatchResponse): string => {
    switch (batch.status) {
      case ProductionStatus.PENDING:
        return 'Programado';
      case ProductionStatus.IN_PROGRESS:
        return 'En producción';
      case ProductionStatus.QUALITY_CHECK:
        return 'Control de calidad';
      case ProductionStatus.ON_HOLD:
        return 'En pausa';
      case ProductionStatus.COMPLETED:
        return 'Completado';
      case ProductionStatus.CANCELLED:
        return 'Cancelado';
      case ProductionStatus.FAILED:
        return 'Fallido';
      default:
        return 'Estado desconocido';
    }
  };

  const getQualityStatusInfo = (batch: ProductionBatchResponse): string | undefined => {
    if (batch.status === ProductionStatus.QUALITY_CHECK) {
      return 'Control de calidad pendiente';
    }

    if (batch.quality_score !== undefined && batch.quality_score !== null) {
      if (batch.quality_score >= 8) {
        return `Calidad excelente (${batch.quality_score}/10)`;
      } else if (batch.quality_score >= 6) {
        return `Calidad aceptable (${batch.quality_score}/10)`;
      } else {
        return `Calidad baja (${batch.quality_score}/10)`;
      }
    }

    if (batch.status === ProductionStatus.COMPLETED) {
      return 'Control de calidad final pendiente';
    }

    return undefined;
  };

  const getProductionActions = () => {
    const actions = [];

    // Primary action - View batch details (matches inventory "Ver Detalles")
    if (onView) {
      actions.push({
        label: 'Ver Detalles',
        icon: Eye,
        variant: 'primary' as const,
        priority: 'primary' as const,
        onClick: () => onView(batch)
      });
    }

    // Status-specific primary actions
    if (batch.status === ProductionStatus.PENDING && onStart) {
      actions.push({
        label: 'Iniciar Producción',
        icon: Play,
        priority: 'secondary' as const,
        highlighted: true,
        onClick: () => onStart(batch)
      });
    }

    if (batch.status === ProductionStatus.IN_PROGRESS) {
      if (onComplete) {
        actions.push({
          label: 'Completar',
          icon: CheckCircle,
          priority: 'secondary' as const,
          highlighted: true,
          onClick: () => onComplete(batch)
        });
      }

      if (onPause) {
        actions.push({
          label: 'Pausar',
          icon: Pause,
          priority: 'secondary' as const,
          onClick: () => onPause(batch)
        });
      }
    }

    if (batch.status === ProductionStatus.ON_HOLD && onStart) {
      actions.push({
        label: 'Reanudar',
        icon: Play,
        priority: 'secondary' as const,
        highlighted: true,
        onClick: () => onStart(batch)
      });
    }

    if (batch.status === ProductionStatus.QUALITY_CHECK && onQualityCheck) {
      actions.push({
        label: 'Control de Calidad',
        icon: Package,
        priority: 'secondary' as const,
        highlighted: true,
        onClick: () => onQualityCheck(batch)
      });
    }

    // Cancel action for non-completed batches
    if (onCancel && batch.status !== ProductionStatus.COMPLETED && batch.status !== ProductionStatus.CANCELLED) {
      actions.push({
        label: 'Cancelar',
        icon: X,
        priority: 'secondary' as const,
        destructive: true,
        onClick: () => onCancel(batch)
      });
    }

    return actions;
  };

  const getMetadata = (): string[] => {
    const metadata = [];

    if (batch.planned_start_time) {
      const startTime = new Date(batch.planned_start_time);
      metadata.push(`Inicio: ${startTime.toLocaleDateString()} ${startTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`);
    }

    if (batch.planned_end_time) {
      const endTime = new Date(batch.planned_end_time);
      metadata.push(`Fin: ${endTime.toLocaleDateString()} ${endTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`);
    }

    if (batch.staff_assigned && batch.staff_assigned.length > 0) {
      const staff = TextOverflowPrevention.production.staffList(batch.staff_assigned);
      metadata.push(`Personal: ${staff}`);
    }

    if (batch.equipment_used && batch.equipment_used.length > 0) {
      const equipment = TextOverflowPrevention.production.equipmentList(batch.equipment_used);
      metadata.push(`Equipos: ${equipment}`);
    }

    const qualityInfo = getQualityStatusInfo(batch);
    if (qualityInfo) {
      metadata.push(safeText(qualityInfo, qualityInfo, 50));
    }

    // Add reasoning information if available
    if (batch.reasoning_data) {
      const { trigger_type, trigger_description, factors, consequence, confidence_score, variance, prediction_details } = batch.reasoning_data;

      // Add trigger information
      if (trigger_type) {
        let triggerLabel = t(`reasoning:triggers.${trigger_type.toLowerCase()}`);
        if (triggerLabel === `reasoning:triggers.${trigger_type.toLowerCase()}`) {
          triggerLabel = trigger_type;
        }
        metadata.push(`Causa: ${triggerLabel}`);
      }

      // Add factors
      if (factors && Array.isArray(factors) && factors.length > 0) {
        const factorLabels = factors.map(factor => {
          const factorLabel = t(`reasoning:factors.${factor.toLowerCase()}`);
          return factorLabel === `reasoning:factors.${factor.toLowerCase()}` ? factor : factorLabel;
        }).join(', ');
        metadata.push(`Factores: ${factorLabels}`);
      }

      // Add confidence score
      if (confidence_score) {
        metadata.push(`Confianza: ${confidence_score}%`);
      }

      // Add variance information
      if (variance) {
        metadata.push(`Varianza: ${variance}%`);
      }
    }

    if (batch.priority === ProductionPriority.URGENT) {
      metadata.push('⚡ Orden urgente');
    }

    if (batch.is_rush_order) {
      metadata.push('🏃 Orden express');
    }

    if (batch.is_special_recipe) {
      metadata.push('🌟 Receta especial');
    }

    return metadata;
  };

  const getSecondaryInfo = () => {
    if (batch.actual_quantity && batch.planned_quantity) {
      const completionPercent = Math.round((batch.actual_quantity / batch.planned_quantity) * 100);
      return {
        label: 'Progreso',
        value: `${batch.actual_quantity}/${batch.planned_quantity} (${completionPercent}%)`
      };
    }

    if (batch.staff_assigned && batch.staff_assigned.length > 0) {
      const staff = TextOverflowPrevention.mobile.staff(batch.staff_assigned);
      return {
        label: 'Personal',
        value: staff
      };
    }

    return {
      label: 'Prioridad',
      value: t(`production:priority.${batch.priority.toLowerCase()}`)
    };
  };

  const statusConfig = getProductionStatusConfig(batch.status, batch.priority);
  const progress = showDetailedProgress ? calculateDetailedProgress(batch) : undefined;

  return (
    <StatusCard
      id={batch.id}
      statusIndicator={statusConfig}
      title={TextOverflowPrevention.production.productName(batch.product_name)}
      subtitle={`Lote: ${TextOverflowPrevention.production.batchNumber(batch.batch_number)}`}
      primaryValue={batch.planned_quantity}
      primaryValueLabel="uds"
      secondaryInfo={getSecondaryInfo()}
      progress={progress !== undefined ? {
        label: getProgressLabel(batch),
        percentage: progress,
        color: statusConfig.color
      } : undefined}
      metadata={getMetadata()}
      actions={getProductionActions()}
      onClick={onView ? () => onView(batch) : undefined}
      compact={compact}
    />
  );
};

export default ProductionStatusCard;