import React, { useState, useEffect, useMemo } from 'react';
import { Package, Clock, Users, AlertCircle, Plus, ClipboardCheck } from 'lucide-react';
import { AddModal } from '../../ui/AddModal/AddModal';
import {
  ProductionBatchCreate,
  ProductionPriorityEnum
} from '../../../api/types/production';
import { Card } from '../../ui';
import { Badge } from '../../ui';
import { ProcessStage } from '../../../api/types/qualityTemplates';
import type { RecipeResponse } from '../../../api/types/recipes';
import { useTranslation } from 'react-i18next';
import { useRecipes } from '../../../api/hooks/recipes';
import { useIngredients } from '../../../api/hooks/inventory';
import { useEquipment } from '../../../api/hooks/equipment';
import { recipesService } from '../../../api/services/recipes';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { statusColors } from '../../../styles/colors';

interface CreateProductionBatchModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreateBatch?: (batchData: ProductionBatchCreate) => Promise<void>;
}

/**
 * CreateProductionBatchModal - Modal for creating a new production batch
 * Comprehensive form for adding new production batches
 */
export const CreateProductionBatchModal: React.FC<CreateProductionBatchModalProps> = ({
  isOpen,
  onClose,
  onCreateBatch
}) => {
  const { t } = useTranslation(['production', 'common']);
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';
  const [loading, setLoading] = useState(false);
  const [selectedRecipe, setSelectedRecipe] = useState<RecipeResponse | null>(null);
  const [loadingRecipe, setLoadingRecipe] = useState(false);

  // API Data
  const { data: recipes = [], isLoading: recipesLoading } = useRecipes(tenantId);
  const { data: ingredients = [], isLoading: ingredientsLoading } = useIngredients(tenantId);
  const { data: equipmentData, isLoading: equipmentLoading } = useEquipment(tenantId, { is_active: true });

  // Stage labels for display
  const 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'
  };

  // Load recipe details when recipe is selected
  const handleRecipeChange = async (recipeId: string) => {
    if (!recipeId) {
      setSelectedRecipe(null);
      return;
    }

    setLoadingRecipe(true);
    try {
      const recipe = await recipesService.getRecipe(tenantId, recipeId);
      setSelectedRecipe(recipe);
    } catch (error) {
      console.error('Error loading recipe:', error);
      setSelectedRecipe(null);
    } finally {
      setLoadingRecipe(false);
    }
  };

  // Filter finished products (ingredients that are finished products)
  const finishedProducts = useMemo(() => ingredients.filter(ing =>
    ing.type === 'finished_product' ||
    ing.category === 'finished_products' ||
    ing.name.toLowerCase().includes('pan') ||
    ing.name.toLowerCase().includes('pastel') ||
    ing.name.toLowerCase().includes('torta')
  ), [ingredients]);

  const productOptions = useMemo(() => finishedProducts.map(product => ({
    value: product.id,
    label: product.name
  })), [finishedProducts]);

  const recipeOptions = useMemo(() => recipes.map(recipe => ({
    value: recipe.id,
    label: recipe.name
  })), [recipes]);

  const equipmentOptions = useMemo(() => {
    if (!equipmentData?.equipment) return [];
    return equipmentData.equipment.map(equip => ({
      value: equip.id,
      label: `${equip.name} (${equip.equipment_code || equip.id.substring(0, 8)})`
    }));
  }, [equipmentData]);

  const handleSave = async (formData: Record<string, any>) => {
    // Validate that end time is after start time
    const startTime = new Date(formData.planned_start_time);
    const endTime = new Date(formData.planned_end_time);

    if (endTime <= startTime) {
      throw new Error('La fecha de fin debe ser posterior a la fecha de inicio');
    }

    setLoading(true);

    try {
      // Find the selected product to get the name
      const selectedProduct = finishedProducts.find(p => p.id === formData.product_id);

      // Convert staff_assigned from string to array
      const staffArray = formData.staff_assigned
        ? formData.staff_assigned.split(',').map((s: string) => s.trim()).filter((s: string) => s.length > 0)
        : [];

      // Convert equipment_used from comma-separated string to array
      const equipmentArray = formData.equipment_used
        ? formData.equipment_used.split(',').map((e: string) => e.trim()).filter((e: string) => e.length > 0)
        : [];

      const batchData: ProductionBatchCreate = {
        product_id: formData.product_id,
        product_name: selectedProduct?.name || '',
        recipe_id: formData.recipe_id || '',
        planned_start_time: formData.planned_start_time,
        planned_end_time: formData.planned_end_time,
        planned_quantity: Number(formData.planned_quantity),
        planned_duration_minutes: Number(formData.planned_duration_minutes),
        priority: formData.priority as ProductionPriorityEnum,
        is_rush_order: formData.is_rush_order || false,
        is_special_recipe: formData.is_special_recipe || false,
        production_notes: formData.production_notes || '',
        batch_number: formData.batch_number || '',
        order_id: formData.order_id || '',
        forecast_id: formData.forecast_id || '',
        equipment_used: equipmentArray,
        staff_assigned: staffArray,
        station_id: formData.station_id || ''
      };

      if (onCreateBatch) {
        await onCreateBatch(batchData);
      }
    } catch (error) {
      console.error('Error creating production batch:', error);
      throw error; // Let AddModal handle error display
    } finally {
      setLoading(false);
    }
  };

  const statusConfig = useMemo(() => ({
    color: statusColors.inProgress.primary,
    text: 'Nueva Orden',
    icon: Plus,
    isCritical: false,
    isHighlight: true
  }), []);

  // Auto-calculate end time based on start time and duration
  const calculateEndTime = (startTime: string, durationMinutes: number): string => {
    if (!startTime || !durationMinutes) return '';
    const start = new Date(startTime);
    const end = new Date(start.getTime() + durationMinutes * 60000);
    return end.toISOString().slice(0, 16);
  };

  const sections = useMemo(() => [
    {
      title: 'Información del Producto',
      icon: Package,
      fields: [
        {
          label: 'Producto a Producir',
          name: 'product_id',
          type: 'select' as const,
          required: true,
          options: productOptions,
          placeholder: 'Seleccionar producto...',
          span: 2
        },
        {
          label: 'Receta a Utilizar',
          name: 'recipe_id',
          type: 'select' as const,
          options: recipeOptions,
          placeholder: 'Seleccionar receta...',
          span: 2,
          onChange: (value: string) => handleRecipeChange(value)
        },
        {
          label: 'Número de Lote',
          name: 'batch_number',
          type: 'text' as const,
          placeholder: 'Se generará automáticamente si se deja vacío'
        }
      ]
    },
    {
      title: 'Planificación de Producción',
      icon: Clock,
      fields: [
        {
          label: 'Inicio Planificado',
          name: 'planned_start_time',
          type: 'date' as const,
          required: true
        },
        {
          label: 'Fin Planificado',
          name: 'planned_end_time',
          type: 'date' as const,
          required: true,
          helpText: 'Se calcula automáticamente basado en inicio y duración'
        },
        {
          label: 'Cantidad Planificada',
          name: 'planned_quantity',
          type: 'number' as const,
          required: true,
          defaultValue: 1,
          validation: (value: string | number) => {
            const num = Number(value);
            return num <= 0 ? 'La cantidad debe ser mayor a 0' : null;
          }
        },
        {
          label: 'Duración (minutos)',
          name: 'planned_duration_minutes',
          type: 'number' as const,
          required: true,
          defaultValue: 60,
          validation: (value: string | number) => {
            const num = Number(value);
            return num <= 0 ? 'La duración debe ser mayor a 0' : null;
          }
        }
      ]
    },
    {
      title: 'Configuración y Prioridad',
      icon: AlertCircle,
      fields: [
        {
          label: 'Prioridad',
          name: 'priority',
          type: 'select' as const,
          required: true,
          defaultValue: ProductionPriorityEnum.MEDIUM,
          options: Object.values(ProductionPriorityEnum).map(value => ({
            value,
            label: t(`production:priority.${value.toLowerCase()}`)
          }))
        },
        {
          label: 'Orden Urgente',
          name: 'is_rush_order',
          type: 'select' as const,
          options: [
            { label: 'No', value: false },
            { label: 'Sí', value: true }
          ],
          defaultValue: false
        },
        {
          label: 'Receta Especial',
          name: 'is_special_recipe',
          type: 'select' as const,
          options: [
            { label: 'No', value: false },
            { label: 'Sí', value: true }
          ],
          defaultValue: false
        }
      ]
    },
    {
      title: 'Recursos y Notas',
      icon: Users,
      fields: [
        {
          label: 'Equipos a Utilizar',
          name: 'equipment_used',
          type: 'text' as const,
          placeholder: 'Separar IDs de equipos con comas (opcional)',
          span: 2,
          helpText: equipmentOptions.length > 0
            ? `Equipos disponibles: ${equipmentOptions.map(e => e.label).join(', ')}`
            : 'No hay equipos activos disponibles'
        },
        {
          label: 'Personal Asignado',
          name: 'staff_assigned',
          type: 'text' as const,
          placeholder: 'Separar nombres con comas (opcional)',
          span: 2,
          helpText: 'Ej: Juan Pérez, María García'
        },
        {
          label: 'Notas de Producción',
          name: 'production_notes',
          type: 'textarea' as const,
          placeholder: 'Instrucciones especiales, observaciones, etc.',
          span: 2
        }
      ]
    }
  ], [productOptions, recipeOptions, equipmentOptions, t]);

  // Quality Requirements Preview Component
  const qualityRequirementsPreview = selectedRecipe && (
    <Card className="mt-4 p-4 bg-blue-50 border-blue-200">
      <h4 className="font-medium text-[var(--text-primary)] mb-3 flex items-center gap-2">
        <ClipboardCheck className="w-5 h-5 text-blue-600" />
        Controles de Calidad Requeridos
      </h4>
      {selectedRecipe.quality_check_configuration && selectedRecipe.quality_check_configuration.stages ? (
        <div className="space-y-3">
          {Object.entries(selectedRecipe.quality_check_configuration.stages).map(([stage, config]: [string, any]) => {
            if (!config.template_ids || config.template_ids.length === 0) return null;

            return (
              <div key={stage} className="flex items-center gap-2 text-sm">
                <Badge variant="info">{STAGE_LABELS[stage as ProcessStage]}</Badge>
                <span className="text-[var(--text-secondary)]">
                  {config.template_ids.length} control{config.template_ids.length > 1 ? 'es' : ''}
                </span>
                {config.blocking && (
                  <Badge variant="warning" size="sm">Bloqueante</Badge>
                )}
                {config.is_required && (
                  <Badge variant="error" size="sm">Requerido</Badge>
                )}
              </div>
            );
          })}
          <div className="mt-3 pt-3 border-t border-blue-200">
            <p className="text-sm text-[var(--text-secondary)]">
              <span className="font-medium">Umbral de calidad mínimo:</span>{' '}
              {selectedRecipe.quality_check_configuration.overall_quality_threshold || 7.0}/10
            </p>
            {selectedRecipe.quality_check_configuration.critical_stage_blocking && (
              <p className="text-sm text-[var(--text-secondary)] mt-1">
                <span className="font-medium text-orange-600">⚠️ Bloqueo crítico activado:</span>{' '}
                El lote no puede avanzar si fallan checks críticos
              </p>
            )}
          </div>
        </div>
      ) : (
        <div className="text-sm text-[var(--text-secondary)]">
          <p className="mb-2">Esta receta no tiene controles de calidad configurados.</p>
          <a
            href={`/app/database/recipes`}
            target="_blank"
            rel="noopener noreferrer"
            className="text-blue-600 hover:underline"
          >
            Configurar controles de calidad →
          </a>
        </div>
      )}
    </Card>
  );

  return (
    <AddModal
      isOpen={isOpen}
      onClose={onClose}
      title="Nueva Orden de Producción"
      subtitle="Crear un nuevo lote de producción"
      statusIndicator={statusConfig}
      sections={sections}
      size="xl"
      loading={loading}
      onSave={handleSave}
      additionalContent={qualityRequirementsPreview}
    />
  );
};

export default CreateProductionBatchModal;