import React, { useState, useMemo } from 'react';
import { Plus, Clock, AlertCircle, CheckCircle, Timer, ChefHat, Eye, Edit, Package, Zap, User, PlusCircle } from 'lucide-react';
import { Button, Input, Card, StatsGrid, StatusModal, Toggle } from '../../../../components/ui';
import { statusColors } from '../../../../styles/colors';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { LoadingSpinner } from '../../../../components/shared';
import { PageHeader } from '../../../../components/layout';
import { ProductionSchedule, CreateProductionBatchModal, ProductionStatusCard, QualityCheckModal, CompactProcessStageTracker } from '../../../../components/domain/production';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import {
  useProductionDashboard,
  useActiveBatches,
  useCreateProductionBatch,
  useUpdateBatchStatus,
  productionService
} from '../../../../api';
import type {
  ProductionBatchResponse,
  ProductionBatchCreate,
  ProductionBatchStatusUpdate
} from '../../../../api';
import {
  ProductionStatusEnum,
  ProductionPriorityEnum
} from '../../../../api';
import { useProductionEnums } from '../../../../utils/enumHelpers';
import { ProcessStage } from '../../../../api/types/qualityTemplates';

const ProductionPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('schedule');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedBatch, setSelectedBatch] = useState<ProductionBatchResponse | null>(null);
  const [showBatchModal, setShowBatchModal] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showQualityModal, setShowQualityModal] = useState(false);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
  const [isAIMode, setIsAIMode] = useState(true);

  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';
  const productionEnums = useProductionEnums();

  // API Data
  const {
    data: dashboardData,
    isLoading: dashboardLoading,
    error: dashboardError
  } = useProductionDashboard(tenantId);

  const {
    data: activeBatchesData,
    isLoading: batchesLoading,
    error: batchesError
  } = useActiveBatches(tenantId);

  // Mutations
  const createBatchMutation = useCreateProductionBatch();
  const updateBatchStatusMutation = useUpdateBatchStatus();

  // Handlers
  const handleCreateBatch = async (batchData: ProductionBatchCreate) => {
    try {
      await createBatchMutation.mutateAsync({
        tenantId,
        batchData
      });
    } catch (error) {
      console.error('Error creating production batch:', error);
      throw error;
    }
  };

  // Stage management handlers
  const handleStageAdvance = async (batchId: string, currentStage: ProcessStage) => {
    const stages = Object.values(ProcessStage);
    const currentIndex = stages.indexOf(currentStage);
    const nextStage = stages[currentIndex + 1];

    if (nextStage) {
      try {
        await updateBatchStatusMutation.mutateAsync({
          batchId,
          updates: {
            current_process_stage: nextStage,
            process_stage_history: {
              [currentStage]: { end_time: new Date().toISOString() },
              [nextStage]: { start_time: new Date().toISOString() }
            }
          }
        });
      } catch (error) {
        console.error('Error advancing stage:', error);
      }
    } else {
      // Final stage - mark as completed
      await updateBatchStatusMutation.mutateAsync({
        batchId,
        updates: { status: ProductionStatusEnum.COMPLETED }
      });
    }
  };

  const handleStageStart = async (batchId: string, stage: ProcessStage) => {
    try {
      await updateBatchStatusMutation.mutateAsync({
        batchId,
        updates: {
          status: ProductionStatusEnum.IN_PROGRESS,
          current_process_stage: stage,
          process_stage_history: {
            [stage]: { start_time: new Date().toISOString() }
          }
        }
      });
    } catch (error) {
      console.error('Error starting stage:', error);
    }
  };

  const handleQualityCheckForStage = (batch: ProductionBatchResponse, stage: ProcessStage) => {
    setSelectedBatch(batch);
    setShowQualityModal(true);
    // The QualityCheckModal should be enhanced to handle stage-specific checks
  };

  // Helper function to generate mock process stage data for the selected batch
  const generateMockProcessStageData = (batch: ProductionBatchResponse) => {
    // Mock data based on batch status - this would come from the API in real implementation
    const mockProcessStage = {
      current: batch.status === ProductionStatusEnum.PENDING ? 'mixing' as const :
               batch.status === ProductionStatusEnum.IN_PROGRESS ? 'baking' as const :
               batch.status === ProductionStatusEnum.QUALITY_CHECK ? 'cooling' as const :
               'finishing' as const,
      history: batch.status !== ProductionStatusEnum.PENDING ? [
        { stage: 'mixing' as const, timestamp: batch.actual_start_time || batch.planned_start_time, duration: 30 },
        ...(batch.status === ProductionStatusEnum.IN_PROGRESS || batch.status === ProductionStatusEnum.QUALITY_CHECK || batch.status === ProductionStatusEnum.COMPLETED ? [
          { stage: 'proofing' as const, timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), duration: 90 },
          { stage: 'shaping' as const, timestamp: new Date(Date.now() - 1 * 60 * 60 * 1000).toISOString(), duration: 15 }
        ] : []),
        ...(batch.status === ProductionStatusEnum.QUALITY_CHECK || batch.status === ProductionStatusEnum.COMPLETED ? [
          { stage: 'baking' as const, timestamp: new Date(Date.now() - 30 * 60 * 1000).toISOString(), duration: 45 }
        ] : [])
      ] : [],
      pendingQualityChecks: batch.status === ProductionStatusEnum.IN_PROGRESS ? [
        {
          id: 'qc1',
          name: 'Control de temperatura interna',
          stage: 'baking' as const,
          isRequired: true,
          isCritical: true,
          status: 'pending' as const,
          checkType: 'temperature' as const
        }
      ] : batch.status === ProductionStatusEnum.QUALITY_CHECK ? [
        {
          id: 'qc2',
          name: 'Inspección visual final',
          stage: 'cooling' as const,
          isRequired: true,
          isCritical: false,
          status: 'pending' as const,
          checkType: 'visual' as const
        }
      ] : [],
      completedQualityChecks: batch.status === ProductionStatusEnum.COMPLETED ? [
        {
          id: 'qc1',
          name: 'Control de temperatura interna',
          stage: 'baking' as const,
          isRequired: true,
          isCritical: true,
          status: 'completed' as const,
          checkType: 'temperature' as const
        },
        {
          id: 'qc2',
          name: 'Inspección visual final',
          stage: 'cooling' as const,
          isRequired: true,
          isCritical: false,
          status: 'completed' as const,
          checkType: 'visual' as const
        }
      ] : batch.status === ProductionStatusEnum.IN_PROGRESS ? [
        {
          id: 'qc3',
          name: 'Verificación de masa',
          stage: 'mixing' as const,
          isRequired: true,
          isCritical: false,
          status: 'completed' as const,
          checkType: 'visual' as const
        }
      ] : []
    };

    return mockProcessStage;
  };


  const batches = activeBatchesData?.batches || [];

  const filteredBatches = useMemo(() => {
    if (!searchQuery) return batches;

    const searchLower = searchQuery.toLowerCase();
    return batches.filter(batch =>
      batch.product_name.toLowerCase().includes(searchLower) ||
      batch.batch_number.toLowerCase().includes(searchLower) ||
      (batch.staff_assigned && batch.staff_assigned.some(staff =>
        staff.toLowerCase().includes(searchLower)
      ))
    );
  }, [batches, searchQuery]);

  // Calculate production stats from real data
  const productionStats = useMemo(() => {
    if (!dashboardData) {
      return {
        activeBatches: 0,
        todaysTarget: 0,
        capacityUtilization: 0,
        onTimeCompletion: 0,
        qualityScore: 0,
        totalOutput: 0,
        efficiency: 0
      };
    }

    return {
      activeBatches: dashboardData.active_batches || 0,
      todaysTarget: dashboardData.todays_production_plan?.length || 0,
      capacityUtilization: Math.round(dashboardData.capacity_utilization || 0),
      onTimeCompletion: Math.round(dashboardData.on_time_completion_rate || 0),
      qualityScore: Math.round(dashboardData.average_quality_score || 0),
      totalOutput: dashboardData.total_output_today || 0,
      efficiency: Math.round(dashboardData.efficiency_percentage || 0)
    };
  }, [dashboardData]);


  // Loading state
  if (!tenantId || dashboardLoading || batchesLoading) {
    return (
      <div className="flex items-center justify-center min-h-64">
        <LoadingSpinner text="Cargando producción..." />
      </div>
    );
  }

  // Error state
  if (dashboardError || batchesError) {
    return (
      <div className="text-center py-12">
        <AlertCircle className="mx-auto h-12 w-12 text-red-500 mb-4" />
        <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
          Error al cargar la producción
        </h3>
        <p className="text-[var(--text-secondary)] mb-4">
          {(dashboardError || batchesError)?.message || 'Ha ocurrido un error inesperado'}
        </p>
        <Button onClick={() => window.location.reload()}>
          Reintentar
        </Button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between mb-6">
        <PageHeader
          title="Gestión de Producción"
          description="Planifica y controla la producción diaria de tu panadería"
        />
        <div className="flex items-center gap-4">
          {/* AI/Manual Mode Segmented Control */}
          <div className="inline-flex p-1 bg-[var(--surface-secondary)] rounded-xl border border-[var(--border-primary)] shadow-sm">
            <button
              onClick={() => setIsAIMode(true)}
              className={`
                flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ease-in-out
                ${isAIMode
                  ? 'bg-[var(--color-primary)] text-white shadow-sm'
                  : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-tertiary)]'
                }
              `}
            >
              <Zap className="w-4 h-4" />
              Automático IA
            </button>
            <button
              onClick={() => setIsAIMode(false)}
              className={`
                flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ease-in-out
                ${!isAIMode
                  ? 'bg-[var(--color-primary)] text-white shadow-sm'
                  : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--surface-tertiary)]'
                }
              `}
            >
              <User className="w-4 h-4" />
              Manual
            </button>
          </div>

          {!isAIMode && (
            <Button
              variant="primary"
              size="md"
              onClick={() => setShowCreateModal(true)}
              className="flex items-center gap-2.5 px-6 py-3 text-sm font-semibold tracking-wide shadow-lg hover:shadow-xl transition-all duration-200"
            >
              <PlusCircle className="w-5 h-5" />
              Nueva Orden de Producción
            </Button>
          )}
        </div>
      </div>

      {/* Production Stats */}
      <StatsGrid
        stats={[
          {
            title: 'Lotes Activos',
            value: productionStats.activeBatches,
            variant: 'default' as const,
            icon: Package,
          },
          {
            title: 'Utilización Capacidad',
            value: `${productionStats.capacityUtilization}%`,
            variant: productionStats.capacityUtilization >= 80 ? 'success' as const : 'warning' as const,
            icon: Timer,
          },
          {
            title: 'Completado a Tiempo',
            value: `${productionStats.onTimeCompletion}%`,
            variant: productionStats.onTimeCompletion >= 90 ? 'success' as const : 'error' as const,
            icon: CheckCircle,
          },
          {
            title: 'Puntuación Calidad',
            value: `${productionStats.qualityScore}%`,
            variant: productionStats.qualityScore >= 85 ? 'success' as const : 'warning' as const,
            icon: Package,
          },
          {
            title: 'Producción Hoy',
            value: formatters.number(productionStats.totalOutput),
            variant: 'info' as const,
            icon: ChefHat,
          },
          {
            title: 'Eficiencia',
            value: `${productionStats.efficiency}%`,
            variant: productionStats.efficiency >= 75 ? 'success' as const : 'warning' as const,
            icon: Timer,
          },
        ]}
        columns={3}
      />

      {/* Tabs Navigation */}
      <div className="border-b border-[var(--border-primary)]">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('schedule')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'schedule'
                ? 'border-orange-500 text-[var(--color-primary)]'
                : 'border-transparent text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'
            }`}
          >
            Programación
          </button>
        </nav>
      </div>

      {/* Production Orders Tab */}
      {activeTab === 'schedule' && (
        <>
          {/* Search Controls */}
          <Card className="p-4">
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="flex-1">
                <Input
                  placeholder="Buscar lotes por producto, número de lote o personal..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full"
                />
              </div>
            </div>
          </Card>

          {/* Production Batches Grid */}
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {filteredBatches.map((batch) => (
              <ProductionStatusCard
                key={batch.id}
                batch={batch}
                onView={(batch) => {
                  setSelectedBatch(batch);
                  setModalMode('view');
                  setShowBatchModal(true);
                }}
                onEdit={(batch) => {
                  setSelectedBatch(batch);
                  setModalMode('edit');
                  setShowBatchModal(true);
                }}
                onStart={async (batch) => {
                  try {
                    await updateBatchStatusMutation.mutateAsync({
                      batchId: batch.id,
                      updates: { status: ProductionStatusEnum.IN_PROGRESS }
                    });
                  } catch (error) {
                    console.error('Error starting batch:', error);
                  }
                }}
                onPause={async (batch) => {
                  try {
                    await updateBatchStatusMutation.mutateAsync({
                      batchId: batch.id,
                      updates: { status: ProductionStatusEnum.ON_HOLD }
                    });
                  } catch (error) {
                    console.error('Error pausing batch:', error);
                  }
                }}
                onComplete={async (batch) => {
                  try {
                    await updateBatchStatusMutation.mutateAsync({
                      batchId: batch.id,
                      updates: { status: ProductionStatusEnum.QUALITY_CHECK }
                    });
                  } catch (error) {
                    console.error('Error completing batch:', error);
                  }
                }}
                onCancel={async (batch) => {
                  try {
                    await updateBatchStatusMutation.mutateAsync({
                      batchId: batch.id,
                      updates: { status: ProductionStatusEnum.CANCELLED }
                    });
                  } catch (error) {
                    console.error('Error cancelling batch:', error);
                  }
                }}
                onQualityCheck={(batch) => {
                  setSelectedBatch(batch);
                  setShowQualityModal(true);
                }}
                onViewHistory={(batch) => {
                  setSelectedBatch(batch);
                  setModalMode('view');
                  setShowBatchModal(true);
                }}
                showDetailedProgress={true}
              />
            ))}
          </div>

          {/* Empty State */}
          {filteredBatches.length === 0 && (
            <div className="text-center py-12">
              <ChefHat className="mx-auto h-12 w-12 text-[var(--text-tertiary)] mb-4" />
              <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
                No se encontraron lotes de producción
              </h3>
              <p className="text-[var(--text-secondary)] mb-4">
                {batches.length === 0
                  ? 'No hay lotes de producción activos. Crea el primer lote para comenzar.'
                  : 'Intenta ajustar la búsqueda o crear un nuevo lote de producción'
                }
              </p>
              <Button onClick={() => setShowCreateModal(true)}>
                <Plus className="w-4 h-4 mr-2" />
                Nueva Orden de Producción
              </Button>
            </div>
          )}
        </>
      )}



      {/* Production Batch Modal */}
      {showBatchModal && selectedBatch && (
        <StatusModal
          isOpen={showBatchModal}
          onClose={() => {
            setShowBatchModal(false);
            setSelectedBatch(null);
            setModalMode('view');
          }}
          mode={modalMode}
          onModeChange={setModalMode}
          title={selectedBatch.product_name}
          subtitle={`Lote de Producción #${selectedBatch.batch_number}`}
          statusIndicator={{
            color: statusColors.inProgress.primary,
            text: productionEnums.getProductionStatusLabel(selectedBatch.status),
            icon: Package
          }}
          size="lg"
          sections={[
            {
              title: 'Información General',
              icon: Package,
              fields: [
                {
                  label: 'Cantidad Planificada',
                  value: `${selectedBatch.planned_quantity} unidades`,
                  highlight: true
                },
                {
                  label: 'Cantidad Real',
                  value: selectedBatch.actual_quantity
                    ? `${selectedBatch.actual_quantity} unidades`
                    : 'Pendiente',
                  editable: modalMode === 'edit',
                  type: 'number'
                },
                {
                  label: 'Prioridad',
                  value: selectedBatch.priority,
                  type: 'select',
                  editable: modalMode === 'edit',
                  options: productionEnums.getProductionPriorityOptions()
                },
                {
                  label: 'Estado',
                  value: selectedBatch.status,
                  type: 'select',
                  editable: modalMode === 'edit',
                  options: productionEnums.getProductionStatusOptions()
                },
                {
                  label: 'Personal Asignado',
                  value: selectedBatch.staff_assigned?.join(', ') || 'No asignado',
                  editable: modalMode === 'edit',
                  type: 'text'
                }
              ]
            },
            {
              title: 'Cronograma',
              icon: Clock,
              fields: [
                {
                  label: 'Inicio Planificado',
                  value: selectedBatch.planned_start_time,
                  type: 'datetime'
                },
                {
                  label: 'Fin Planificado',
                  value: selectedBatch.planned_end_time,
                  type: 'datetime'
                },
                {
                  label: 'Inicio Real',
                  value: selectedBatch.actual_start_time || 'Pendiente',
                  type: 'datetime'
                },
                {
                  label: 'Fin Real',
                  value: selectedBatch.actual_end_time || 'Pendiente',
                  type: 'datetime'
                }
              ]
            },
            {
              title: 'Seguimiento de Proceso',
              icon: Timer,
              fields: [
                {
                  label: '',
                  value: (
                    <CompactProcessStageTracker
                      processStage={generateMockProcessStageData(selectedBatch)}
                      onAdvanceStage={(currentStage) => handleStageAdvance(selectedBatch.id, currentStage)}
                      onQualityCheck={(checkId) => {
                        setShowQualityModal(true);
                        console.log('Opening quality check:', checkId);
                      }}
                      className="w-full"
                    />
                  ),
                  span: 2
                }
              ]
            },
            {
              title: 'Calidad y Costos',
              icon: CheckCircle,
              fields: [
                {
                  label: 'Puntuación de Calidad',
                  value: selectedBatch.quality_score
                    ? `${selectedBatch.quality_score}/10`
                    : 'Pendiente'
                },
                {
                  label: 'Rendimiento',
                  value: selectedBatch.yield_percentage
                    ? `${selectedBatch.yield_percentage}%`
                    : 'Calculando...'
                },
                {
                  label: 'Costo Estimado',
                  value: selectedBatch.estimated_cost || 0,
                  type: 'currency'
                },
                {
                  label: 'Costo Real',
                  value: selectedBatch.actual_cost || 0,
                  type: 'currency'
                }
              ]
            }
          ]}
          onSave={async () => {
            try {
              // Implementation would depend on specific fields changed
              console.log('Saving batch changes:', selectedBatch.id);
              // await updateBatchStatusMutation.mutateAsync({
              //   batchId: selectedBatch.id,
              //   updates: selectedBatch
              // });
              setShowBatchModal(false);
              setSelectedBatch(null);
              setModalMode('view');
            } catch (error) {
              console.error('Error saving batch:', error);
            }
          }}
          onFieldChange={(sectionIndex, fieldIndex, value) => {
            if (!selectedBatch) return;

            const sections = [
              ['planned_quantity', 'actual_quantity', 'priority', 'status', 'staff_assigned'],
              ['planned_start_time', 'planned_end_time', 'actual_start_time', 'actual_end_time'],
              ['quality_score', 'yield_percentage', 'estimated_cost', 'actual_cost']
            ];

            // Get the field names from modal sections
            const sectionFields = [
              { fields: ['planned_quantity', 'actual_quantity', 'priority', 'status', 'staff_assigned'] },
              { fields: ['planned_start_time', 'planned_end_time', 'actual_start_time', 'actual_end_time'] },
              { fields: ['quality_score', 'yield_percentage', 'estimated_cost', 'actual_cost'] }
            ];

            const fieldMapping: Record<string, string> = {
              'Cantidad Real': 'actual_quantity',
              'Prioridad': 'priority',
              'Estado': 'status',
              'Personal Asignado': 'staff_assigned'
            };

            // Get section labels to map back to field names
            const sectionLabels = [
              ['Cantidad Planificada', 'Cantidad Real', 'Prioridad', 'Estado', 'Personal Asignado'],
              ['Inicio Planificado', 'Fin Planificado', 'Inicio Real', 'Fin Real'],
              ['Puntuación de Calidad', 'Rendimiento', 'Costo Estimado', 'Costo Real']
            ];

            const fieldLabel = sectionLabels[sectionIndex]?.[fieldIndex];
            const propertyName = fieldMapping[fieldLabel] || sectionFields[sectionIndex]?.fields[fieldIndex];

            if (propertyName) {
              let processedValue: any = value;

              if (propertyName === 'staff_assigned' && typeof value === 'string') {
                processedValue = value.split(',').map(s => s.trim()).filter(s => s.length > 0);
              } else if (propertyName === 'actual_quantity') {
                processedValue = parseFloat(value as string) || 0;
              }

              setSelectedBatch({
                ...selectedBatch,
                [propertyName]: processedValue
              });
            }
          }}
        />
      )}

      {/* Create Production Batch Modal */}
      <CreateProductionBatchModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onCreateBatch={handleCreateBatch}
      />

      {/* Quality Check Modal */}
      {showQualityModal && selectedBatch && (
        <QualityCheckModal
          isOpen={showQualityModal}
          onClose={() => {
            setShowQualityModal(false);
            setSelectedBatch(null);
          }}
          batch={selectedBatch}
          onComplete={async (result) => {
            console.log('Quality check completed:', result);
            // Optionally update batch status to completed or quality_passed
            try {
              await updateBatchStatusMutation.mutateAsync({
                batchId: selectedBatch.id,
                updates: {
                  status: result.overallPass ? ProductionStatusEnum.COMPLETED : ProductionStatusEnum.ON_HOLD
                }
              });
            } catch (error) {
              console.error('Error updating batch status after quality check:', error);
            }
          }}
        />
      )}
    </div>
  );
};

export default ProductionPage;