import React, { useState, useEffect } from 'react';
import { Plus, Trash2, CheckCircle, Clock, AlertTriangle, Settings } from 'lucide-react';

interface QualityControlEditorProps {
  value: any; // The quality control configuration
  onChange: (value: any) => void;
  allTemplates: Array<{ id: string; name: string; category: string }>; // Available templates
}

export interface RecipeQualityConfiguration {
  stages: {
    [key: string]: {
      template_ids: string[];
      is_required?: boolean;
      blocking?: boolean;
      min_checks_passed?: number;
    };
  };
  overall_quality_threshold?: number;
  auto_create_quality_checks?: boolean;
  quality_manager_approval_required?: boolean;
  critical_stage_blocking?: boolean;
}

export const RecipeQualityControlEditor: React.FC<QualityControlEditorProps> = ({ 
  value, 
  onChange, 
  allTemplates 
}) => {
  // Initialize with default structure if no value
  const initialConfig: RecipeQualityConfiguration = value || {
    stages: {
      MIXING: { template_ids: [], is_required: false, blocking: false },
      PROOFING: { template_ids: [], is_required: false, blocking: false },
      SHAPING: { template_ids: [], is_required: false, blocking: false },
      BAKING: { template_ids: [], is_required: false, blocking: false },
      COOLING: { template_ids: [], is_required: false, blocking: false },
      PACKAGING: { template_ids: [], is_required: false, blocking: false },
      FINISHING: { template_ids: [], is_required: false, blocking: false },
    },
    overall_quality_threshold: 70,
    auto_create_quality_checks: false,
    quality_manager_approval_required: false,
    critical_stage_blocking: false
  };

  const [config, setConfig] = useState<RecipeQualityConfiguration>(initialConfig);

  // Update parent when config changes
  useEffect(() => {
    onChange(config);
  }, [config, onChange]);

  const stageOptions = [
    { value: 'MIXING', label: 'Mezclado', icon: Settings },
    { value: 'PROOFING', label: 'Fermentación', icon: Clock },
    { value: 'SHAPING', label: 'Formado', icon: Settings },
    { value: 'BAKING', label: 'Horneado', icon: AlertTriangle },
    { value: 'COOLING', label: 'Enfriado', icon: Clock },
    { value: 'PACKAGING', label: 'Empaquetado', icon: CheckCircle },
    { value: 'FINISHING', label: 'Acabado', icon: CheckCircle },
  ];

  const addTemplateToStage = (stage: string, templateId: string) => {
    setConfig(prev => {
      const newConfig = { ...prev };
      const stageConfig = newConfig.stages[stage] || { template_ids: [], is_required: false, blocking: false };
      
      if (!stageConfig.template_ids.includes(templateId)) {
        stageConfig.template_ids = [...stageConfig.template_ids, templateId];
        newConfig.stages = { ...newConfig.stages, [stage]: stageConfig };
      }
      
      return newConfig;
    });
  };

  const removeTemplateFromStage = (stage: string, templateId: string) => {
    setConfig(prev => {
      const newConfig = { ...prev };
      const stageConfig = newConfig.stages[stage] || { template_ids: [], is_required: false, blocking: false };
      
      stageConfig.template_ids = stageConfig.template_ids.filter(id => id !== templateId);
      newConfig.stages = { ...newConfig.stages, [stage]: stageConfig };
      
      return newConfig;
    });
  };

  const toggleStageSetting = (stage: string, setting: 'is_required' | 'blocking', value: boolean) => {
    setConfig(prev => {
      const newConfig = { ...prev };
      const existingStage = newConfig.stages[stage] || { template_ids: [], is_required: false, blocking: false };
      
      newConfig.stages[stage] = {
        ...existingStage,
        [setting]: value
      };
      
      return newConfig;
    });
  };

  const updateGlobalSetting = (setting: keyof RecipeQualityConfiguration, value: any) => {
    setConfig(prev => ({
      ...prev,
      [setting]: value
    }));
  };

  return (
    <div className="space-y-6">
      {/* Global Settings */}
      <div className="p-4 rounded-lg border border-[var(--border-secondary)] bg-[var(--bg-secondary)]/30">
        <h4 className="font-medium text-[var(--text-primary)] mb-3 flex items-center gap-2">
          <Settings className="w-4 h-4" />
          Configuración General
        </h4>
        
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <div>
              <label className="text-sm font-medium text-[var(--text-primary)]">Umbral de calidad general</label>
              <p className="text-xs text-[var(--text-tertiary)]">Porcentaje mínimo para calidad aprobada</p>
            </div>
            <div className="flex items-center gap-2">
              <input
                type="number"
                min="0"
                max="100"
                value={config.overall_quality_threshold || 70}
                onChange={(e) => updateGlobalSetting('overall_quality_threshold', parseInt(e.target.value) || 0)}
                className="w-20 px-2 py-1 border border-[var(--border-secondary)] rounded text-sm bg-[var(--bg-primary)] text-[var(--text-primary)]"
              />
              <span className="text-sm">%</span>
            </div>
          </div>
          
          <div className="flex items-center justify-between pt-2 border-t border-[var(--border-secondary)]">
            <div>
              <label className="text-sm font-medium text-[var(--text-primary)]">Auto-crear controles</label>
              <p className="text-xs text-[var(--text-tertiary)]">Crear controles automáticamente</p>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={config.auto_create_quality_checks || false}
                onChange={(e) => updateGlobalSetting('auto_create_quality_checks', e.target.checked)}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-[var(--border-secondary)] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--color-primary)]"></div>
            </label>
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="text-sm font-medium text-[var(--text-primary)]">Aprobación requerida</label>
              <p className="text-xs text-[var(--text-tertiary)]">Requiere aprobación de responsable</p>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={config.quality_manager_approval_required || false}
                onChange={(e) => updateGlobalSetting('quality_manager_approval_required', e.target.checked)}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-[var(--border-secondary)] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--color-primary)]"></div>
            </label>
          </div>
          
          <div className="flex items-center justify-between">
            <div>
              <label className="text-sm font-medium text-[var(--text-primary)]">Etapas críticas bloqueantes</label>
              <p className="text-xs text-[var(--text-tertiary)]">Bloquear producción en fallo crítico</p>
            </div>
            <label className="relative inline-flex items-center cursor-pointer">
              <input
                type="checkbox"
                checked={config.critical_stage_blocking || false}
                onChange={(e) => updateGlobalSetting('critical_stage_blocking', e.target.checked)}
                className="sr-only peer"
              />
              <div className="w-11 h-6 bg-[var(--border-secondary)] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[var(--color-primary)]"></div>
            </label>
          </div>
        </div>
      </div>

      {/* Stage Configuration */}
      <div className="space-y-4">
        <h4 className="font-medium text-[var(--text-primary)] mb-2">Configuración por Etapas</h4>
        
        {stageOptions.map(({ value: stageValue, label, icon: Icon }) => {
          const stageConfig = config.stages[stageValue] || { template_ids: [], is_required: false, blocking: false };
          const availableTemplates = allTemplates.filter(template => 
            !stageConfig.template_ids.includes(template.id)
          );

          return (
            <div 
              key={stageValue} 
              className="p-4 rounded-lg border border-[var(--border-secondary)] bg-[var(--bg-secondary)]/30"
            >
              <div className="flex items-center gap-2 mb-3">
                <Icon className="w-4 h-4 text-[var(--color-primary)]" />
                <h5 className="font-medium text-[var(--text-primary)]">{label}</h5>
              </div>
              
              {/* Add Template Dropdown */}
              <div className="mb-3">
                <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                  Añadir Plantilla de Control
                </label>
                <div className="flex gap-2">
                  <select
                    className="flex-1 px-3 py-2 border border-[var(--border-secondary)] rounded-md bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                    onChange={(e) => {
                      if (e.target.value) {
                        addTemplateToStage(stageValue, e.target.value);
                        e.target.value = ''; // Reset selection
                      }
                    }}
                  >
                    <option value="">Seleccionar plantilla...</option>
                    {availableTemplates.map(template => (
                      <option key={template.id} value={template.id}>
                        {template.name} ({template.category})
                      </option>
                    ))}
                  </select>
                </div>
              </div>
              
              {/* Assigned Templates */}
              <div className="mb-3">
                <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                  Plantillas Asignadas
                </label>
                {stageConfig.template_ids.length === 0 ? (
                  <div className="text-sm text-[var(--text-tertiary)] italic py-2">
                    No hay plantillas asignadas a esta etapa
                  </div>
                ) : (
                  <div className="space-y-2">
                    {stageConfig.template_ids.map(templateId => {
                      const template = allTemplates.find(t => t.id === templateId);
                      return template ? (
                        <div 
                          key={templateId} 
                          className="flex items-center justify-between p-2 bg-[var(--bg-primary)]/70 border border-[var(--border-secondary)] rounded-md"
                        >
                          <span className="text-sm">{template.name}</span>
                          <button
                            type="button"
                            onClick={() => removeTemplateFromStage(stageValue, templateId)}
                            className="p-1 text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950 rounded transition-colors"
                          >
                            <Trash2 className="w-3 h-3" />
                          </button>
                        </div>
                      ) : null;
                    })}
                  </div>
                )}
              </div>
              
              {/* Stage Settings */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2 border-t border-[var(--border-secondary)]">
                <div className="flex items-center justify-between">
                  <div>
                    <label className="text-xs font-medium text-[var(--text-primary)]">Requerido</label>
                    <p className="text-xs text-[var(--text-tertiary)]">Obligatorio para esta etapa</p>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={stageConfig.is_required || false}
                      onChange={(e) => toggleStageSetting(stageValue, 'is_required', e.target.checked)}
                      className="sr-only peer"
                    />
                    <div className="w-9 h-5 bg-[var(--border-secondary)] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[var(--color-primary)]"></div>
                  </label>
                </div>
                
                <div className="flex items-center justify-between">
                  <div>
                    <label className="text-xs font-medium text-[var(--text-primary)]">Bloqueante</label>
                    <p className="text-xs text-[var(--text-tertiary)]">Bloquea la producción si falla</p>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={stageConfig.blocking || false}
                      onChange={(e) => toggleStageSetting(stageValue, 'blocking', e.target.checked)}
                      className="sr-only peer"
                    />
                    <div className="w-9 h-5 bg-[var(--border-secondary)] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[var(--color-primary)]"></div>
                  </label>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default RecipeQualityControlEditor;