/*
 * Production Tab Component for Enterprise Dashboard
 * Shows network-wide production status and equipment monitoring
 */

import React, { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card';
import { Button } from '../ui/Button';
import { Factory, AlertTriangle, CheckCircle2, Activity, Timer, Brain, Cog, Wrench, Bell, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { ProductionStatusBlock } from './blocks/ProductionStatusBlock';
import StatusCard from '../ui/StatusCard/StatusCard';
import { useControlPanelData } from '../../api/hooks/useControlPanelData';
import { useSSEEvents } from '../../hooks/useSSE';
import { equipmentService } from '../../api/services/equipment';

interface ProductionTabProps {
  tenantId: string;
}

const ProductionTab: React.FC<ProductionTabProps> = ({ tenantId }) => {
  const { t } = useTranslation('dashboard');
  
  // Get control panel data for production information
  const { data: controlPanelData, isLoading: isControlPanelLoading } = useControlPanelData(tenantId);

  const isLoading = isControlPanelLoading;

  // Real-time SSE events
  const { events: sseEvents, isConnected: sseConnected } = useSSEEvents({ 
    channels: ['*.alerts', '*.notifications', 'recommendations'] 
  });

  // State for equipment data with real-time updates
  const [equipmentData, setEquipmentData] = useState<any[]>([]);
  const [equipmentLoading, setEquipmentLoading] = useState(true);

  // Fetch equipment data
  useEffect(() => {
    const fetchEquipmentData = async () => {
      setEquipmentLoading(true);
      try {
        const equipmentList = await equipmentService.getEquipment(tenantId);
        // Transform the equipment data to match the expected format
        const transformedData = equipmentList.map(eq => ({
          id: eq.id,
          name: eq.name,
          status: eq.status.toLowerCase(),
          temperature: eq.currentTemperature ? `${eq.currentTemperature}°C` : 'N/A',
          utilization: eq.efficiency || eq.uptime || 0,
          lastMaintenance: eq.lastMaintenance || new Date().toISOString().split('T')[0],
          nextMaintenance: eq.nextMaintenance || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // Default to 30 days from now
          lastEvent: null
        }));
        setEquipmentData(transformedData);
      } catch (error) {
        console.error('Error fetching equipment data:', error);
        // Set empty array but still mark loading as false
        setEquipmentData([]);
      } finally {
        setEquipmentLoading(false);
      }
    };

    fetchEquipmentData();
  }, [tenantId]);

  // Process SSE events for equipment status updates
  useEffect(() => {
    if (sseEvents.length === 0 || equipmentData.length === 0) return;

    // Filter equipment-related events
    const equipmentEvents = sseEvents.filter(event =>
      event.event_type.includes('equipment_') ||
      event.event_type === 'equipment_maintenance' ||
      event.entity_type === 'equipment'
    );

    if (equipmentEvents.length === 0) return;

    // Update equipment status based on events
    setEquipmentData(prevEquipment => {
      return prevEquipment.map(equipment => {
        // Find the latest event for this equipment
        const equipmentEvent = equipmentEvents.find(event =>
          event.entity_id === equipment.id ||
          event.event_metadata?.equipment_id === equipment.id
        );

        if (equipmentEvent) {
          // Update status based on event type
          let newStatus = equipment.status;
          let temperature = equipment.temperature;
          let utilization = equipment.utilization;

          switch (equipmentEvent.event_type) {
            case 'equipment_maintenance_required':
            case 'equipment_failure':
              newStatus = 'critical';
              break;
            case 'equipment_warning':
            case 'temperature_variance':
              newStatus = 'warning';
              break;
            case 'equipment_normal':
            case 'maintenance_completed':
              newStatus = 'normal';
              break;
          }

          // Update temperature if available in event metadata
          if (equipmentEvent.event_metadata?.temperature) {
            temperature = `${equipmentEvent.event_metadata.temperature}°C`;
          }

          // Update utilization if available in event metadata
          if (equipmentEvent.event_metadata?.utilization) {
            utilization = equipmentEvent.event_metadata.utilization;
          }

          return {
            ...equipment,
            status: newStatus,
            temperature: temperature,
            utilization: utilization,
            lastEvent: {
              type: equipmentEvent.event_type,
              timestamp: equipmentEvent.timestamp || new Date().toISOString(),
              message: equipmentEvent.message
            }
          };
        }

        return equipment;
      });
    });
  }, [sseEvents, equipmentData]);

  return (
    <div className="space-y-8">
      {/* Production Status Block - Reusing existing component */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-[var(--text-primary)] mb-4 flex items-center gap-2">
          <Factory className="w-6 h-6 text-[var(--color-primary)]" />
          {t('production.title')}
        </h2>
        <ProductionStatusBlock 
          lateToStartBatches={controlPanelData?.lateToStartBatches || []}
          runningBatches={controlPanelData?.runningBatches || []}
          pendingBatches={controlPanelData?.pendingBatches || []}
          alerts={controlPanelData?.alerts || []}
          equipmentAlerts={controlPanelData?.equipmentAlerts || []}
          productionAlerts={controlPanelData?.productionAlerts || []}
          loading={isLoading}
        />
      </div>

      {/* Equipment Status Grid */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-[var(--text-primary)] mb-4 flex items-center gap-2">
          <Cog className="w-6 h-6 text-[var(--color-secondary)]" />
          {t('production.equipment_status')}
        </h2>
        {equipmentLoading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {[...Array(4)].map((_, index) => (
              <Card key={index} className="animate-pulse">
                <CardContent className="p-6">
                  <div className="flex items-center justify-between mb-4">
                    <div className="h-4 bg-[var(--bg-tertiary)] rounded w-3/4"></div>
                    <div className="w-8 h-8 rounded-full bg-[var(--bg-tertiary)]"></div>
                  </div>
                  <div className="h-6 bg-[var(--bg-tertiary)] rounded w-1/2 mb-2"></div>
                  <div className="h-4 bg-[var(--bg-tertiary)] rounded w-full mb-4"></div>
                  <div className="h-2 bg-[var(--bg-tertiary)] rounded w-full mb-2"></div>
                  <div className="h-2 bg-[var(--bg-tertiary)] rounded w-3/4"></div>
                </CardContent>
              </Card>
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {equipmentData.map((equipment) => {
              // Determine status configuration
              const getStatusConfig = () => {
                switch (equipment.status) {
                  case 'critical':
                    return {
                      color: '#ef4444', // red-500
                      text: t('production.status_critical'),
                      icon: AlertTriangle,
                      isCritical: true
                    };
                  case 'warning':
                    return {
                      color: '#f59e0b', // amber-500
                      text: t('production.status_warning'),
                      icon: AlertTriangle,
                      isHighlight: true
                    };
                  default:
                    return {
                      color: '#10b981', // emerald-500
                      text: t('production.status_normal'),
                      icon: CheckCircle2
                    };
                }
              };

              const statusConfig = getStatusConfig();

              // Add real-time event indicator if there's a recent event
              const eventMetadata = [];
              if (equipment.lastEvent) {
                const eventTime = new Date(equipment.lastEvent.timestamp);
                eventMetadata.push(`🔔 ${equipment.lastEvent.type.replace(/_/g, ' ')} - ${eventTime.toLocaleTimeString()}`);
                if (equipment.lastEvent.message) {
                  eventMetadata.push(`${t('production.event_message')}: ${equipment.lastEvent.message}`);
                }
              }

              // Add SSE connection status to first card
              const additionalMetadata = [];
              if (equipment.id === equipmentData[0]?.id) {
                additionalMetadata.push(
                  sseConnected
                    ? `🟢 ${t('enterprise.live_updates')}`
                    : `🟡 ${t('enterprise.offline')}`
                );
              }

              return (
                <StatusCard
                  key={equipment.id}
                  id={equipment.id}
                  statusIndicator={statusConfig}
                  title={equipment.name}
                  subtitle={equipment.temperature ? `${t('production.temperature')}: ${equipment.temperature}` : undefined}
                  primaryValue={`${equipment.utilization}%`}
                  primaryValueLabel={t('production.utilization')}
                  secondaryInfo={{
                    label: t('production.next_maintenance'),
                    value: new Date(equipment.nextMaintenance).toLocaleDateString()
                  }}
                  progress={{
                    label: t('production.utilization'),
                    percentage: equipment.utilization,
                    color: statusConfig.color
                  }}
                  metadata={[...eventMetadata, ...additionalMetadata,
                    `${t('production.last_maintenance')}: ${new Date(equipment.lastMaintenance).toLocaleDateString()}`
                  ]}
                  actions={[
                    {
                      label: t('production.view_details'),
                      icon: Wrench,
                      variant: 'outline',
                      onClick: () => {
                        // In Phase 2, this will navigate to equipment detail page
                        console.log(`View details for ${equipment.name}`);
                      },
                      priority: 'primary'
                    }
                  ]}
                  onClick={() => {
                    // In Phase 2, this will navigate to equipment detail page
                    console.log(`Clicked ${equipment.name}`);
                  }}
                />
              );
            })}
            {equipmentData.length === 0 && !equipmentLoading && (
              <div className="col-span-full py-12">
                <div className="text-center text-[var(--text-secondary)]">
                  <Cog className="w-12 h-12 mx-auto mb-4 opacity-20" />
                  <p>{t('production.no_equipment')}</p>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Production Efficiency Metrics */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-[var(--text-primary)] mb-4 flex items-center gap-2">
          <Brain className="w-6 h-6 text-[var(--color-info)]" />
          {t('production.efficiency_metrics')}
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
          {/* On-time Batch Start Rate */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                {t('production.on_time_start_rate')}
              </CardTitle>
              <Timer className="w-5 h-5 text-[var(--color-success)]" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-[var(--color-success)]">
                {controlPanelData?.orchestrationSummary?.aiHandlingRate || 85}%
              </div>
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('production.batches_started_on_time')}
              </p>
            </CardContent>
          </Card>

          {/* Production Efficiency */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                {t('production.efficiency_rate')}
              </CardTitle>
              <Activity className="w-5 h-5 text-[var(--color-primary)]" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-[var(--color-primary)]">
                {Math.round((controlPanelData?.issuesPreventedByAI || 0) / 
                  Math.max(1, (controlPanelData?.issuesPreventedByAI || 0) + (controlPanelData?.issuesRequiringAction || 0)) * 100) || 92}%
              </div>
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('production.overall_efficiency')}
              </p>
            </CardContent>
          </Card>

          {/* Active Production Alerts */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                {t('production.active_alerts')}
              </CardTitle>
              <AlertTriangle className="w-5 h-5 text-[var(--color-warning)]" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-[var(--color-warning)]">
                {(controlPanelData?.productionAlerts?.length || 0) + (controlPanelData?.equipmentAlerts?.length || 0)}
              </div>
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('production.issues_require_attention')}
              </p>
            </CardContent>
          </Card>

          {/* AI Prevented Issues */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between pb-2">
              <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                {t('production.ai_prevented')}
              </CardTitle>
              <CheckCircle2 className="w-5 h-5 text-[var(--color-success)]" />
            </CardHeader>
            <CardContent>
              <div className="text-3xl font-bold text-[var(--color-success)]">
                {controlPanelData?.issuesPreventedByAI || 12}
              </div>
              <p className="text-xs text-[var(--text-secondary)] mt-1">
                {t('production.problems_prevented')}
              </p>
            </CardContent>
          </Card>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-[var(--text-primary)] mb-4 flex items-center gap-2">
          <Timer className="w-6 h-6 text-[var(--color-info)]" />
          {t('production.quick_actions')}
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <Factory className="w-6 h-6 text-[var(--color-primary)]" />
                <h3 className="text-lg font-semibold text-[var(--text-primary)]">{t('production.create_batch')}</h3>
              </div>
              <p className="text-[var(--text-secondary)] mb-4">{t('production.create_batch_description')}</p>
              <Button
                onClick={() => window.location.href = `/app/tenants/${tenantId}/production/batches/create`}
                className="w-full"
              >
                {t('production.create_batch')}
              </Button>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <Wrench className="w-6 h-6 text-[var(--color-success)]" />
                <h3 className="text-lg font-semibold text-[var(--text-primary)]">{t('production.maintenance')}</h3>
              </div>
              <p className="text-[var(--text-secondary)] mb-4">{t('production.schedule_maintenance')}</p>
              <Button
                onClick={() => window.location.href = `/app/tenants/${tenantId}/equipment`}
                variant="outline"
                className="w-full"
              >
                {t('production.manage_equipment')}
              </Button>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center gap-3 mb-4">
                <Cog className="w-6 h-6 text-[var(--color-info)]" />
                <h3 className="text-lg font-semibold text-[var(--text-primary)]">{t('production.quality_checks')}</h3>
              </div>
              <p className="text-[var(--text-secondary)] mb-4">{t('production.manage_quality')}</p>
              <Button
                onClick={() => window.location.href = `/app/tenants/${tenantId}/production/quality`}
                variant="outline"
                className="w-full"
              >
                {t('production.quality_management')}
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default ProductionTab;