import React from 'react';
import { Eye, ClipboardCheck, Target, Settings, Cog, CheckCircle, AlertTriangle } from 'lucide-react';
import { EditViewModal, EditViewModalSection } from '../../ui/EditViewModal/EditViewModal';
import {
  QualityCheckType,
  ProcessStage,
  type QualityCheckTemplate
} from '../../../api/types/qualityTemplates';
import { useTranslation } from 'react-i18next';

interface ViewQualityTemplateModalProps {
  isOpen: boolean;
  onClose: () => void;
  template: QualityCheckTemplate;
  onEdit?: () => void;
}

const QUALITY_CHECK_TYPE_LABELS: Record<QualityCheckType, string> = {
  [QualityCheckType.VISUAL]: 'Visual - Inspección visual',
  [QualityCheckType.MEASUREMENT]: 'Medición - Medidas precisas',
  [QualityCheckType.TEMPERATURE]: 'Temperatura - Control térmico',
  [QualityCheckType.WEIGHT]: 'Peso - Control de peso',
  [QualityCheckType.BOOLEAN]: 'Sí/No - Verificación binaria',
  [QualityCheckType.TIMING]: 'Tiempo - Control temporal',
  [QualityCheckType.CHECKLIST]: 'Lista de verificación - Checklist'
};

const PROCESS_STAGE_LABELS: Record<ProcessStage, string> = {
  [ProcessStage.MIXING]: 'Mezclado',
  [ProcessStage.PROOFING]: 'Fermentación',
  [ProcessStage.SHAPING]: 'Formado',
  [ProcessStage.BAKING]: 'Horneado',
  [ProcessStage.COOLING]: 'Enfriado',
  [ProcessStage.PACKAGING]: 'Empaquetado',
  [ProcessStage.FINISHING]: 'Acabado'
};

const CATEGORY_LABELS: Record<string, string> = {
  'appearance': 'Apariencia',
  'structure': 'Estructura',
  'texture': 'Textura',
  'flavor': 'Sabor',
  'safety': 'Seguridad',
  'packaging': 'Empaque',
  'temperature': 'Temperatura',
  'weight': 'Peso',
  'dimensions': 'Dimensiones'
};

export const ViewQualityTemplateModal: React.FC<ViewQualityTemplateModalProps> = ({
  isOpen,
  onClose,
  template,
  onEdit
}) => {
  const { t } = useTranslation();

  // Helper function to get translated category label
  const getCategoryLabel = (category: string | null | undefined): string => {
    if (!category) return 'Sin categoría';
    const translationKey = `production.quality.categories.${category}`;
    const translated = t(translationKey);
    // If translation is same as key, it means no translation exists, fallback to hardcoded labels
    return translated === translationKey ? (CATEGORY_LABELS[category] || category) : translated;
  };

  const showMeasurementFields = [
    QualityCheckType.MEASUREMENT,
    QualityCheckType.TEMPERATURE,
    QualityCheckType.WEIGHT
  ].includes(template.check_type);

  const getSections = (): EditViewModalSection[] => {
    const sections: EditViewModalSection[] = [
      {
        title: 'Información Básica',
        icon: ClipboardCheck,
        fields: [
          {
            label: 'Nombre',
            value: template.name,
            type: 'text',
            highlight: true,
            editable: false
          },
          {
            label: 'Código de Plantilla',
            value: template.template_code || 'No especificado',
            type: 'text',
            editable: false
          },
          {
            label: 'Tipo de Control',
            value: QUALITY_CHECK_TYPE_LABELS[template.check_type],
            type: 'text',
            editable: false
          },
          {
            label: 'Categoría',
            value: getCategoryLabel(template.category),
            type: 'text',
            editable: false
          },
          {
            label: 'Descripción',
            value: template.description || 'Sin descripción',
            type: 'text',
            editable: false,
            span: 2 as 1 | 2 | 3
          },
          {
            label: 'Instrucciones para el Personal',
            value: template.instructions || 'No especificadas',
            type: 'text',
            editable: false,
            span: 2 as 1 | 2 | 3
          }
        ]
      }
    ];

    // Add measurement configuration section if applicable
    if (showMeasurementFields) {
      const measurementFields = [];

      if (template.min_value !== null && template.min_value !== undefined) {
        measurementFields.push({
          label: 'Valor Mínimo',
          value: `${template.min_value} ${template.unit || ''}`,
          type: 'text' as const,
          editable: false
        });
      }

      if (template.max_value !== null && template.max_value !== undefined) {
        measurementFields.push({
          label: 'Valor Máximo',
          value: `${template.max_value} ${template.unit || ''}`,
          type: 'text' as const,
          editable: false
        });
      }

      if (template.target_value !== null && template.target_value !== undefined) {
        measurementFields.push({
          label: 'Valor Objetivo',
          value: `${template.target_value} ${template.unit || ''}`,
          type: 'text' as const,
          editable: false,
          highlight: true
        });
      }

      if (template.tolerance_percentage !== null && template.tolerance_percentage !== undefined) {
        measurementFields.push({
          label: 'Tolerancia',
          value: `±${template.tolerance_percentage}%`,
          type: 'text' as const,
          editable: false
        });
      }

      if (template.unit) {
        measurementFields.push({
          label: 'Unidad de Medida',
          value: template.unit,
          type: 'text' as const,
          editable: false
        });
      }

      // Add summary field if we have min, max, and target
      if (template.min_value !== null && template.max_value !== null && template.target_value !== null) {
        measurementFields.push({
          label: 'Rango Aceptable',
          value: `${template.min_value} - ${template.max_value} ${template.unit || ''} (objetivo: ${template.target_value} ${template.unit || ''})`,
          type: 'text' as const,
          editable: false,
          span: 2 as 1 | 2 | 3
        });
      }

      if (measurementFields.length > 0) {
        sections.push({
          title: 'Configuración de Medición',
          icon: Target,
          fields: measurementFields
        });
      }
    }

    // Process stages section
    sections.push({
      title: 'Etapas del Proceso Aplicables',
      icon: Settings,
      description: template.applicable_stages && template.applicable_stages.length > 0
        ? 'Este control se aplica a las siguientes etapas del proceso:'
        : 'Este control se aplica a todas las etapas del proceso',
      fields: [
        {
          label: 'Etapas',
          value: template.applicable_stages && template.applicable_stages.length > 0
            ? template.applicable_stages.map(stage => PROCESS_STAGE_LABELS[stage]).join(', ')
            : 'Todas las etapas',
          type: 'text',
          editable: false,
          span: 2 as 1 | 2 | 3
        }
      ]
    });

    // Configuration section
    sections.push({
      title: 'Configuración',
      icon: Cog,
      fields: [
        {
          label: 'Peso en Puntuación General',
          value: template.weight.toString(),
          type: 'text',
          editable: false,
          helpText: 'Mayor peso = mayor importancia en la puntuación final'
        },
        {
          label: 'Estado de la Plantilla',
          value: template.is_active ? '✓ Activa' : '✗ Inactiva',
          type: 'status',
          editable: false
        },
        {
          label: 'Tipo de Control',
          value: template.is_required ? '✓ Requerido' : 'Opcional',
          type: 'status',
          editable: false,
          helpText: template.is_required ? 'Debe completarse obligatoriamente' : undefined
        },
        {
          label: 'Nivel de Criticidad',
          value: template.is_critical ? '⚠️ Crítico - Bloquea producción si falla' : 'Normal',
          type: 'status',
          editable: false,
          highlight: template.is_critical
        }
      ]
    });

    // Template metadata section
    sections.push({
      title: 'Información de la Plantilla',
      icon: ClipboardCheck,
      collapsible: true,
      collapsed: true,
      fields: [
        {
          label: 'ID',
          value: template.id,
          type: 'text',
          editable: false
        },
        {
          label: 'Fecha de Creación',
          value: template.created_at,
          type: 'datetime',
          editable: false
        },
        {
          label: 'Última Actualización',
          value: template.updated_at,
          type: 'datetime',
          editable: false
        }
      ]
    });

    return sections;
  };

  const getStatusIndicator = () => {
    const typeColors: Record<QualityCheckType, string> = {
      [QualityCheckType.VISUAL]: '#3B82F6',
      [QualityCheckType.MEASUREMENT]: '#10B981',
      [QualityCheckType.TEMPERATURE]: '#EF4444',
      [QualityCheckType.WEIGHT]: '#A855F7',
      [QualityCheckType.BOOLEAN]: '#6B7280',
      [QualityCheckType.TIMING]: '#F59E0B',
      [QualityCheckType.CHECKLIST]: '#6366F1'
    };

    const getIcon = () => {
      if (template.is_critical) return AlertTriangle;
      if (template.is_active) return CheckCircle;
      return Eye;
    };

    return {
      color: template.is_active ? typeColors[template.check_type] : '#6B7280',
      text: template.is_active ? 'Activa' : 'Inactiva',
      icon: getIcon(),
      isCritical: template.is_critical,
      isHighlight: template.is_required
    };
  };

  // Custom actions for view mode
  const customActions = onEdit ? [
    {
      label: 'Editar Plantilla',
      icon: Cog,
      variant: 'primary' as const,
      onClick: onEdit
    }
  ] : [];

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={onClose}
      mode="view"
      title={template.name}
      subtitle={`${getCategoryLabel(template.category)} • ${template.template_code || 'Sin código'}`}
      statusIndicator={getStatusIndicator()}
      sections={getSections()}
      size="xl"
      showDefaultActions={false}
      actions={customActions}
      mobileOptimized={true}
    />
  );
};

export default ViewQualityTemplateModal;
