import React, { useState } from 'react';
import { Badge } from '../../ui/Badge';
import { Button } from '../../ui/Button';
import {
  ChefHat,
  Timer,
  Package,
  Flame,
  Snowflake,
  Box,
  CheckCircle,
  CircleDot,
  Eye,
  Scale,
  Thermometer,
  FlaskRound,
  CheckSquare,
  ArrowRight,
  Clock,
  AlertTriangle,
  ChevronDown,
  ChevronRight,
  Info,
  Play,
  Pause,
  MessageCircle
} from 'lucide-react';

export type ProcessStage = 'mixing' | 'proofing' | 'shaping' | 'baking' | 'cooling' | 'packaging' | 'finishing';

export interface QualityCheckRequirement {
  id: string;
  name: string;
  stage: ProcessStage;
  isRequired: boolean;
  isCritical: boolean;
  status: 'pending' | 'completed' | 'failed' | 'skipped';
  checkType: 'visual' | 'measurement' | 'temperature' | 'weight' | 'boolean';
  description?: string;
}

export interface ProcessStageInfo {
  current: ProcessStage;
  history: Array<{
    stage: ProcessStage;
    start_time: string;
    end_time?: string;
    duration?: number; // in minutes
    notes?: string;
    personnel?: string[];
  }>;
  pendingQualityChecks: QualityCheckRequirement[];
  completedQualityChecks: QualityCheckRequirement[];
  totalProgressPercentage: number;
  estimatedTimeRemaining?: number; // in minutes
  currentStageDuration?: number; // in minutes
}

export interface ProcessStageTrackerProps {
  processStage: ProcessStageInfo;
  onAdvanceStage?: (currentStage: ProcessStage) => void;
  onQualityCheck?: (checkId: string) => void;
  onAddNote?: (stage: ProcessStage, note: string) => void;
  onViewStageDetails?: (stage: ProcessStage) => void;
  onStageAction?: (stage: ProcessStage, action: 'start' | 'pause' | 'resume') => void;
  className?: string;
}

const getProcessStageIcon = (stage: ProcessStage) => {
  switch (stage) {
    case 'mixing': return ChefHat;
    case 'proofing': return Timer;
    case 'shaping': return Package;
    case 'baking': return Flame;
    case 'cooling': return Snowflake;
    case 'packaging': return Box;
    case 'finishing': return CheckCircle;
    default: return CircleDot;
  }
};

const getProcessStageColor = (stage: ProcessStage) => {
  switch (stage) {
    case 'mixing': return 'var(--color-info)';
    case 'proofing': return 'var(--color-warning)';
    case 'shaping': return 'var(--color-primary)';
    case 'baking': return 'var(--color-error)';
    case 'cooling': return 'var(--color-info)';
    case 'packaging': return 'var(--color-success)';
    case 'finishing': return 'var(--color-success)';
    default: return 'var(--color-gray)';
  }
};

const getProcessStageLabel = (stage: ProcessStage) => {
  switch (stage) {
    case 'mixing': return 'Mezclado';
    case 'proofing': return 'Fermentado';
    case 'shaping': return 'Formado';
    case 'baking': return 'Horneado';
    case 'cooling': return 'Enfriado';
    case 'packaging': return 'Empaquetado';
    case 'finishing': return 'Acabado';
    default: return 'Sin etapa';
  }
};

const getQualityCheckIcon = (checkType: string) => {
  switch (checkType) {
    case 'visual': return Eye;
    case 'measurement': return Scale;
    case 'temperature': return Thermometer;
    case 'weight': return Scale;
    case 'boolean': return CheckSquare;
    default: return FlaskRound;
  }
};

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleTimeString('es-ES', {
    hour: '2-digit',
    minute: '2-digit'
  });
};

const formatDuration = (minutes?: number) => {
  if (!minutes) return '';
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  if (hours > 0) {
    return `${hours}h ${mins}m`;
  }
  return `${mins}m`;
};

const ProcessStageTracker: React.FC<ProcessStageTrackerProps> = ({
  processStage,
  onAdvanceStage,
  onQualityCheck,
  onAddNote,
  onViewStageDetails,
  onStageAction,
  className = ''
}) => {
  const allStages: ProcessStage[] = ['mixing', 'proofing', 'shaping', 'baking', 'cooling', 'packaging', 'finishing'];

  const currentStageIndex = allStages.indexOf(processStage.current);
  const completedStages = processStage.history.map(h => h.stage);
  
  const criticalPendingChecks = processStage.pendingQualityChecks.filter(qc => qc.isCritical);
  const canAdvanceStage = processStage.pendingQualityChecks.length === 0 && currentStageIndex < allStages.length - 1;

  const [expandedQualityChecks, setExpandedQualityChecks] = useState(false);
  const [expandedStageHistory, setExpandedStageHistory] = useState(false);

  const currentStageHistory = processStage.history.find(h => h.stage === processStage.current);

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Progress Summary */}
      <div className="bg-[var(--bg-secondary)] rounded-xl p-4">
        <div className="flex items-center justify-between mb-2">
          <h4 className="font-semibold text-[var(--text-primary)]">Progreso General</h4>
          <span className="text-sm font-medium" style={{ color: getProcessStageColor(processStage.current) }}>
            {Math.round(processStage.totalProgressPercentage || 0)}% completado
          </span>
        </div>
        
        {/* Progress Bar */}
        <div className="w-full bg-[var(--bg-primary)] rounded-full h-2 mb-3">
          <div 
            className="h-2 rounded-full" 
            style={{ 
              width: `${processStage.totalProgressPercentage || 0}%`,
              backgroundColor: getProcessStageColor(processStage.current)
            }}
          />
        </div>
        
        {processStage.estimatedTimeRemaining && (
          <div className="text-xs text-[var(--text-secondary)] flex items-center gap-1">
            <Clock className="w-3 h-3" />
            <span>Tiempo restante estimado: {formatDuration(processStage.estimatedTimeRemaining)}</span>
          </div>
        )}
      </div>

      {/* Current Stage Card */}
      <div 
        className="bg-[var(--bg-primary)] border border-[var(--border-primary)] rounded-xl p-4 cursor-pointer transition-colors hover:bg-[var(--bg-secondary)]"
        onClick={() => onViewStageDetails?.(processStage.current)}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div
              className="p-3 rounded-lg"
              style={{
                backgroundColor: `${getProcessStageColor(processStage.current)}20`,
                color: getProcessStageColor(processStage.current)
              }}
            >
              {React.createElement(getProcessStageIcon(processStage.current), { className: 'w-5 h-5' })}
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h3 className="font-semibold text-[var(--text-primary)]">
                  {getProcessStageLabel(processStage.current)}
                </h3>
                {processStage.currentStageDuration && (
                  <Badge variant="info" size="sm">
                    {formatDuration(processStage.currentStageDuration)}
                  </Badge>
                )}
              </div>
              <p className="text-sm text-[var(--text-secondary)]">
                Etapa actual en progreso
              </p>
              {currentStageHistory?.notes && (
                <div className="flex items-center gap-1 mt-1 text-xs text-[var(--text-tertiary)]">
                  <MessageCircle className="w-3 h-3" />
                  <span>{currentStageHistory.notes}</span>
                </div>
              )}
            </div>
          </div>

          <div className="flex items-center gap-2">
            <div className="flex flex-col items-end">
              <Button
                size="sm"
                variant="primary"
                onClick={(e) => {
                  e.stopPropagation();
                  onAdvanceStage?.(processStage.current);
                }}
                className="flex items-center gap-1"
                disabled={!canAdvanceStage}
              >
                <ArrowRight className="w-4 h-4" />
                Siguiente
              </Button>
              
              {onStageAction && (
                <div className="flex gap-1 mt-2">
                  <Button 
                    size="xs" 
                    variant="outline" 
                    onClick={(e) => {
                      e.stopPropagation();
                      onStageAction(processStage.current, 'start');
                    }}
                  >
                    <Play className="w-3 h-3" />
                  </Button>
                  <Button 
                    size="xs" 
                    variant="outline" 
                    onClick={(e) => {
                      e.stopPropagation();
                      onStageAction(processStage.current, 'pause');
                    }}
                  >
                    <Pause className="w-3 h-3" />
                  </Button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Stage Timeline */}
      <div className="space-y-4">
        <h4 className="font-medium text-[var(--text-primary)] flex items-center gap-2">
          <Info className="w-4 h-4" />
          Línea de tiempo de etapas
        </h4>
        
        <div className="relative">
          {/* Timeline line */}
          <div className="absolute left-4 top-6 h-[calc(100%-48px)] w-0.5" 
               style={{ 
                 backgroundColor: 'var(--border-primary)',
                 marginLeft: '2px'
               }} />
              
          <div className="space-y-3">
            {allStages.map((stage, index) => {
              const StageIcon = getProcessStageIcon(stage);
              const isCompleted = completedStages.includes(stage);
              const isCurrent = stage === processStage.current;
              const stageHistory = processStage.history.find(h => h.stage === stage);
              
              // Get quality checks for this specific stage
              const stagePendingChecks = processStage.pendingQualityChecks.filter(check => check.stage === stage);
              const stageCompletedChecks = processStage.completedQualityChecks.filter(check => check.stage === stage);

              return (
                <div 
                  key={stage} 
                  className={`flex items-start gap-3 p-3 rounded-lg cursor-pointer transition-colors
                    ${isCurrent ? 'bg-[var(--bg-secondary)] border border-[var(--border-primary)]' : 'hover:bg-[var(--bg-tertiary)]'}`}
                  onClick={() => onViewStageDetails?.(stage)}
                >
                  <div className="relative z-10">
                    <div
                      className="w-8 h-8 rounded-full flex items-center justify-center border-2"
                      style={{
                        backgroundColor: isCompleted || isCurrent ? getProcessStageColor(stage) : 'var(--bg-primary)',
                        borderColor: isCompleted || isCurrent ? getProcessStageColor(stage) : 'var(--border-primary)',
                        color: isCompleted || isCurrent ? 'white' : 'var(--text-tertiary)'
                      }}
                    >
                      <StageIcon className="w-4 h-4" />
                    </div>
                  </div>
                  
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <div>
                        <h5 className={`font-medium ${isCurrent ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]'}`}>
                          {getProcessStageLabel(stage)}
                        </h5>
                        
                        {stageHistory && (
                          <div className="text-xs text-[var(--text-tertiary)] mt-1">
                            <div>{stageHistory.start_time ? `Inicio: ${formatTime(stageHistory.start_time)}` : ''}</div>
                            {stageHistory.end_time && (
                              <div>Fin: {formatTime(stageHistory.end_time)}</div>
                            )}
                            {stageHistory.duration && (
                              <div>Duración: {formatDuration(stageHistory.duration)}</div>
                            )}
                            {stageHistory.notes && (
                              <div className="mt-1 flex items-center gap-1">
                                <MessageCircle className="w-3 h-3" />
                                <span>{stageHistory.notes}</span>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                      
                      <div className="flex items-center gap-2">
                        {stagePendingChecks.length > 0 && (
                          <Badge variant="warning" size="sm">
                            {stagePendingChecks.length} pendientes
                          </Badge>
                        )}
                        {stageCompletedChecks.length > 0 && (
                          <Badge variant="success" size="sm">
                            {stageCompletedChecks.length} completados
                          </Badge>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Quality Checks Section */}
      {processStage.pendingQualityChecks.length > 0 && (
        <div className="border border-[var(--border-primary)] rounded-xl overflow-hidden">
          <div 
            className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] cursor-pointer"
            onClick={() => setExpandedQualityChecks(!expandedQualityChecks)}
          >
            <div className="flex items-center gap-2">
              <FlaskRound className="w-4 h-4 text-[var(--text-secondary)]" />
              <h5 className="font-medium text-[var(--text-primary)]">
                Controles de Calidad Pendientes
              </h5>
              {criticalPendingChecks.length > 0 && (
                <Badge variant="error" size="xs">
                  {criticalPendingChecks.length} críticos
                </Badge>
              )}
            </div>
            
            {expandedQualityChecks ? 
              <ChevronDown className="w-4 h-4 text-[var(--text-secondary)]" /> : 
              <ChevronRight className="w-4 h-4 text-[var(--text-secondary)]" />
            }
          </div>
          
          {expandedQualityChecks && (
            <div className="p-3 space-y-3">
              {processStage.pendingQualityChecks.map((check) => {
                const CheckIcon = getQualityCheckIcon(check.checkType);
                return (
                  <div
                    key={check.id}
                    className="flex items-start gap-3 p-3 bg-[var(--bg-primary)] rounded-lg"
                  >
                    <div
                      className="p-2 rounded-lg mt-0.5"
                      style={{
                        backgroundColor: check.isCritical ? 'var(--color-error)20' : 'var(--color-warning)20',
                        color: check.isCritical ? 'var(--color-error)' : 'var(--color-warning)'
                      }}
                    >
                      <CheckIcon className="w-4 h-4" />
                    </div>
                    
                    <div className="flex-1">
                      <div className="flex items-start justify-between">
                        <div>
                          <div className="font-medium text-[var(--text-primary)] flex items-center gap-2">
                            {check.name}
                            {check.isCritical && (
                              <AlertTriangle className="w-4 h-4 text-[var(--color-error)]" />
                            )}
                          </div>
                          {check.description && (
                            <div className="text-sm text-[var(--text-secondary)] mt-1">
                              {check.description}
                            </div>
                          )}
                        </div>
                        
                        <Button
                          size="sm"
                          variant={check.isCritical ? 'primary' : 'outline'}
                          onClick={() => onQualityCheck?.(check.id)}
                        >
                          {check.isCritical ? 'Realizar' : 'Verificar'}
                        </Button>
                      </div>
                      
                      <div className="text-xs text-[var(--text-tertiary)] mt-2">
                        Etapa: {getProcessStageLabel(check.stage)} • {check.isRequired ? 'Obligatorio' : 'Opcional'}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* Completed Quality Checks Summary */}
      {processStage.completedQualityChecks.length > 0 && (
        <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)] p-3 bg-[var(--bg-secondary)] rounded-lg">
          <CheckCircle className="w-4 h-4 text-[var(--color-success)]" />
          <span>{processStage.completedQualityChecks.length} controles de calidad completados</span>
        </div>
      )}

      {/* Stage History Summary - Collapsible */}
      {processStage.history.length > 0 && (
        <div className="border border-[var(--border-primary)] rounded-xl overflow-hidden">
          <div 
            className="flex items-center justify-between p-3 bg-[var(--bg-secondary)] cursor-pointer"
            onClick={() => setExpandedStageHistory(!expandedStageHistory)}
          >
            <h5 className="font-medium text-[var(--text-primary)]">
              Historial de Etapas
            </h5>
            
            {expandedStageHistory ? 
              <ChevronDown className="w-4 h-4 text-[var(--text-secondary)]" /> : 
              <ChevronRight className="w-4 h-4 text-[var(--text-secondary)]" />
            }
          </div>
          
          {expandedStageHistory && (
            <div className="p-3">
              <div className="space-y-2">
                {processStage.history.map((historyItem, index) => (
                  <div key={index} className="flex justify-between items-start p-2 bg-[var(--bg-primary)] rounded-md">
                    <div>
                      <div className="font-medium">{getProcessStageLabel(historyItem.stage)}</div>
                      <div className="text-xs text-[var(--text-tertiary)] mt-1">
                        {historyItem.start_time && `Inicio: ${formatTime(historyItem.start_time)}`}
                        {historyItem.end_time && ` • Fin: ${formatTime(historyItem.end_time)}`}
                        {historyItem.duration && ` • Duración: ${formatDuration(historyItem.duration)}`}
                      </div>
                      {historyItem.notes && (
                        <div className="text-xs text-[var(--text-tertiary)] mt-1 flex items-center gap-1">
                          <MessageCircle className="w-3 h-3" />
                          <span>{historyItem.notes}</span>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default ProcessStageTracker;