import React 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
} 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';
}

export interface ProcessStageInfo {
  current: ProcessStage;
  history: Array<{
    stage: ProcessStage;
    timestamp: string;
    duration?: number;
  }>;
  pendingQualityChecks: QualityCheckRequirement[];
  completedQualityChecks: QualityCheckRequirement[];
}

export interface CompactProcessStageTrackerProps {
  processStage: ProcessStageInfo;
  onAdvanceStage?: (currentStage: ProcessStage) => void;
  onQualityCheck?: (checkId: string) => 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 CompactProcessStageTracker: React.FC<CompactProcessStageTrackerProps> = ({
  processStage,
  onAdvanceStage,
  onQualityCheck,
  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;

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Current Stage Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div
            className="p-2 rounded-lg"
            style={{
              backgroundColor: `${getProcessStageColor(processStage.current)}20`,
              color: getProcessStageColor(processStage.current)
            }}
          >
            {React.createElement(getProcessStageIcon(processStage.current), { className: 'w-4 h-4' })}
          </div>
          <div>
            <h4 className="font-medium text-[var(--text-primary)]">
              {getProcessStageLabel(processStage.current)}
            </h4>
            <p className="text-sm text-[var(--text-secondary)]">
              Etapa actual
            </p>
          </div>
        </div>

        {canAdvanceStage && (
          <Button
            size="sm"
            variant="primary"
            onClick={() => onAdvanceStage?.(processStage.current)}
            className="flex items-center gap-1"
          >
            <ArrowRight className="w-4 h-4" />
            Siguiente
          </Button>
        )}
      </div>

      {/* Process Timeline */}
      <div className="relative">
        <div className="flex items-center justify-between">
          {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);

            return (
              <div key={stage} className="flex flex-col items-center relative">
                {/* Connection Line */}
                {index < allStages.length - 1 && (
                  <div
                    className="absolute left-full top-4 w-full h-0.5 -translate-y-1/2 z-0"
                    style={{
                      backgroundColor: isCompleted || isCurrent ? getProcessStageColor(stage) : 'var(--border-primary)',
                      opacity: isCompleted || isCurrent ? 1 : 0.3
                    }}
                  />
                )}

                {/* Stage Icon */}
                <div
                  className="w-8 h-8 rounded-full flex items-center justify-center relative z-10 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>

                {/* Stage Label */}
                <div className="text-xs mt-1 text-center max-w-12">
                  <div className={`font-medium ${isCurrent ? 'text-[var(--text-primary)]' : 'text-[var(--text-secondary)]'}`}>
                    {getProcessStageLabel(stage).split(' ')[0]}
                  </div>
                  {stageHistory && (
                    <div className="text-[var(--text-tertiary)]">
                      {formatTime(stageHistory.timestamp)}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Quality Checks Section */}
      {processStage.pendingQualityChecks.length > 0 && (
        <div className="bg-[var(--bg-secondary)] rounded-lg p-3">
          <div className="flex items-center gap-2 mb-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>

          <div className="space-y-2">
            {processStage.pendingQualityChecks.map((check) => {
              const CheckIcon = getQualityCheckIcon(check.checkType);
              return (
                <div
                  key={check.id}
                  className="flex items-center justify-between bg-[var(--bg-primary)] rounded-md p-2"
                >
                  <div className="flex items-center gap-2">
                    <CheckIcon className="w-4 h-4 text-[var(--text-secondary)]" />
                    <div>
                      <div className="text-sm font-medium text-[var(--text-primary)]">
                        {check.name}
                      </div>
                      <div className="text-xs text-[var(--text-secondary)] flex items-center gap-2">
                        {check.isCritical && <AlertTriangle className="w-3 h-3 text-[var(--color-error)]" />}
                        {check.isRequired ? 'Obligatorio' : 'Opcional'}
                      </div>
                    </div>
                  </div>

                  <Button
                    size="xs"
                    variant={check.isCritical ? 'primary' : 'outline'}
                    onClick={() => onQualityCheck?.(check.id)}
                  >
                    {check.isCritical ? 'Realizar' : 'Verificar'}
                  </Button>
                </div>
              );
            })}
          </div>
        </div>
      )}

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

      {/* Stage History Summary */}
      {processStage.history.length > 0 && (
        <div className="text-xs text-[var(--text-tertiary)] bg-[var(--bg-secondary)] rounded-md p-2">
          <div className="font-medium mb-1">Historial de etapas:</div>
          <div className="space-y-1">
            {processStage.history.map((historyItem, index) => (
              <div key={index} className="flex justify-between">
                <span>{getProcessStageLabel(historyItem.stage)}</span>
                <span>
                  {formatTime(historyItem.timestamp)}
                  {historyItem.duration && ` (${formatDuration(historyItem.duration)})`}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default CompactProcessStageTracker;