import React, { useState } from 'react';
import { Plus, Search, Download, ShoppingCart, Truck, DollarSign, Calendar, Clock, CheckCircle, AlertCircle, Package, Eye, Loader, Edit, ArrowRight, Play, Pause, X, Save, Building2 } from 'lucide-react';
import { Button, Input, Card, StatsGrid, StatusCard, getStatusColor, StatusModal } from '../../../../components/ui';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { PageHeader } from '../../../../components/layout';
import {
  useProcurementDashboard,
  useProcurementPlans,
  useCurrentProcurementPlan,
  useCriticalRequirements,
  usePlanRequirements,
  useGenerateProcurementPlan,
  useUpdateProcurementPlanStatus,
  useTriggerDailyScheduler
} from '../../../../api';
import { useTenantStore } from '../../../../stores/tenant.store';

const ProcurementPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState('plans');
  const [searchTerm, setSearchTerm] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
  const [selectedPlan, setSelectedPlan] = useState<any>(null);
  const [editingPlan, setEditingPlan] = useState<any>(null);
  const [editFormData, setEditFormData] = useState<any>({});
  const [selectedPlanForRequirements, setSelectedPlanForRequirements] = useState<string | null>(null);
  const [showCriticalRequirements, setShowCriticalRequirements] = useState(false);

  const { currentTenant } = useTenantStore();
  const tenantId = currentTenant?.id || '';

  // Real API data hooks
  const { data: dashboardData, isLoading: isDashboardLoading } = useProcurementDashboard(tenantId);
  const { data: procurementPlans, isLoading: isPlansLoading } = useProcurementPlans({
    tenant_id: tenantId,
    limit: 50,
    offset: 0
  });
  const { data: currentPlan, isLoading: isCurrentPlanLoading } = useCurrentProcurementPlan(tenantId);
  const { data: criticalRequirements, isLoading: isCriticalLoading } = useCriticalRequirements(tenantId);

  // Get plan requirements for selected plan
  const { data: planRequirements, isLoading: isPlanRequirementsLoading } = usePlanRequirements({
    tenant_id: tenantId,
    plan_id: selectedPlanForRequirements || '',
    status: 'critical' // Only get critical requirements
  }, {
    enabled: !!selectedPlanForRequirements && !!tenantId
  });
  
  const generatePlanMutation = useGenerateProcurementPlan();
  const updatePlanStatusMutation = useUpdateProcurementPlanStatus();
  const triggerSchedulerMutation = useTriggerDailyScheduler();

  // Helper functions for stage transitions and edit functionality
  const getNextStage = (currentStatus: string): string | null => {
    const stageFlow: { [key: string]: string } = {
      'draft': 'pending_approval',
      'pending_approval': 'approved',
      'approved': 'in_execution',
      'in_execution': 'completed'
    };
    return stageFlow[currentStatus] || null;
  };

  const getStageActionConfig = (status: string) => {
    const configs: { [key: string]: { label: string; icon: any; variant: 'primary' | 'outline'; color?: string } } = {
      'draft': { label: 'Enviar a Aprobación', icon: ArrowRight, variant: 'primary' },
      'pending_approval': { label: 'Aprobar', icon: CheckCircle, variant: 'primary' },
      'approved': { label: 'Iniciar Ejecución', icon: Play, variant: 'primary' },
      'in_execution': { label: 'Completar', icon: CheckCircle, variant: 'primary' }
    };
    return configs[status];
  };

  const canEdit = (status: string): boolean => {
    return status === 'draft';
  };

  const handleStageTransition = (planId: string, currentStatus: string) => {
    const nextStage = getNextStage(currentStatus);
    if (nextStage) {
      updatePlanStatusMutation.mutate({
        tenant_id: tenantId,
        plan_id: planId,
        status: nextStage as any
      });
    }
  };

  const handleCancelPlan = (planId: string) => {
    updatePlanStatusMutation.mutate({
      tenant_id: tenantId,
      plan_id: planId,
      status: 'cancelled'
    });
  };

  const handleEditPlan = (plan: any) => {
    setEditingPlan(plan);
    setEditFormData({
      special_requirements: plan.special_requirements || '',
      planning_horizon_days: plan.planning_horizon_days || 14,
      priority: plan.priority || 'medium'
    });
  };

  const handleSaveEdit = () => {
    // For now, we'll just update the special requirements since that's the main editable field
    // In a real implementation, you might have a separate API endpoint for updating plan details
    console.log('Saving plan edits:', editFormData);
    setEditingPlan(null);
    setEditFormData({});
    // Here you would typically call an update API
  };

  const handleCancelEdit = () => {
    setEditingPlan(null);
    setEditFormData({});
  };

  const handleShowCriticalRequirements = (planId: string) => {
    setSelectedPlanForRequirements(planId);
    setShowCriticalRequirements(true);
  };

  const handleCloseCriticalRequirements = () => {
    setShowCriticalRequirements(false);
    setSelectedPlanForRequirements(null);
  };

  if (!tenantId) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="text-center">
          <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
            No hay tenant seleccionado
          </h3>
          <p className="text-[var(--text-secondary)]">
            Selecciona un tenant para ver los datos de procurement
          </p>
        </div>
      </div>
    );
  }


  const getPlanStatusConfig = (status: string) => {
    const statusConfig = {
      draft: { text: 'Borrador', icon: Clock },
      pending_approval: { text: 'Pendiente Aprobación', icon: Clock },
      approved: { text: 'Aprobado', icon: CheckCircle },
      in_execution: { text: 'En Ejecución', icon: Truck },
      completed: { text: 'Completado', icon: CheckCircle },
      cancelled: { text: 'Cancelado', icon: AlertCircle },
    };
    
    const config = statusConfig[status as keyof typeof statusConfig];
    const Icon = config?.icon;
    
    return {
      color: getStatusColor(status === 'in_execution' ? 'inTransit' : status === 'pending_approval' ? 'pending' : status),
      text: config?.text || status,
      icon: Icon,
      isCritical: status === 'cancelled',
      isHighlight: status === 'pending_approval'
    };
  };

  const filteredPlans = procurementPlans?.plans?.filter(plan => {
    const matchesSearch = plan.plan_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
      plan.status.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (plan.special_requirements && plan.special_requirements.toLowerCase().includes(searchTerm.toLowerCase()));
    
    return matchesSearch;
  }) || [];

  const stats = {
    totalPlans: dashboardData?.summary?.total_plans || 0,
    activePlans: dashboardData?.summary?.active_plans || 0,
    pendingRequirements: dashboardData?.summary?.pending_requirements || 0,
    criticalRequirements: dashboardData?.summary?.critical_requirements || 0,
    totalEstimatedCost: dashboardData?.summary?.total_estimated_cost || 0,
    totalApprovedCost: dashboardData?.summary?.total_approved_cost || 0,
  };

  const procurementStats = [
    {
      title: 'Planes Totales',
      value: stats.totalPlans,
      variant: 'default' as const,
      icon: Package,
    },
    {
      title: 'Planes Activos',
      value: stats.activePlans,
      variant: 'success' as const,
      icon: CheckCircle,
    },
    {
      title: 'Requerimientos Pendientes',
      value: stats.pendingRequirements,
      variant: 'warning' as const,
      icon: Clock,
    },
    {
      title: 'Críticos',
      value: stats.criticalRequirements,
      variant: 'warning' as const,
      icon: AlertCircle,
    },
    {
      title: 'Costo Estimado',
      value: formatters.currency(stats.totalEstimatedCost),
      variant: 'info' as const,
      icon: DollarSign,
    },
    {
      title: 'Costo Aprobado',
      value: formatters.currency(stats.totalApprovedCost),
      variant: 'success' as const,
      icon: DollarSign,
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Planificación de Compras"
        description="Administra planes de compras, requerimientos y análisis de procurement"
        actions={[
          {
            id: "export",
            label: "Exportar",
            variant: "outline" as const,
            icon: Download,
            onClick: () => console.log('Export procurement data')
          },
          {
            id: "generate",
            label: "Generar Plan",
            variant: "primary" as const,
            icon: Plus,
            onClick: () => generatePlanMutation.mutate({
              tenantId,
              request: {
                force_regenerate: false,
                planning_horizon_days: 14,
                include_safety_stock: true,
                safety_stock_percentage: 20
              }
            })
          },
          {
            id: "trigger",
            label: triggerSchedulerMutation.isPending ? "Ejecutando..." : "Ejecutar Programador",
            variant: "outline" as const,
            icon: triggerSchedulerMutation.isPending ? Loader : Calendar,
            onClick: () => {
              triggerSchedulerMutation.mutate(tenantId, {
                onSuccess: (data) => {
                  console.log('✅ Scheduler ejecutado exitosamente:', data.message);
                  // Show success notification (if you have a notification system)
                  // toast.success(data.message);
                },
                onError: (error) => {
                  console.error('❌ Error ejecutando scheduler:', error);
                  // Show error notification
                  // toast.error('Error ejecutando el programador de compras');
                }
              })
            },
            disabled: triggerSchedulerMutation.isPending
          }
        ]}
      />

      {/* Stats Grid */}
      {isDashboardLoading ? (
        <div className="flex justify-center items-center h-32">
          <Loader className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
        </div>
      ) : (
        <StatsGrid 
          stats={procurementStats}
          columns={3}
        />
      )}

      {/* Tabs Navigation */}
      <div className="border-b border-[var(--border-primary)]">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('plans')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'plans'
                ? 'border-orange-500 text-[var(--color-primary)]'
                : 'border-transparent text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'
            }`}
          >
            Planes de Compra
          </button>
          <button
            onClick={() => setActiveTab('requirements')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'requirements'
                ? 'border-orange-500 text-[var(--color-primary)]'
                : 'border-transparent text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'
            }`}
          >
            Requerimientos Críticos
          </button>
          <button
            onClick={() => setActiveTab('analytics')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'analytics'
                ? 'border-orange-500 text-[var(--color-primary)]'
                : 'border-transparent text-[var(--text-tertiary)] hover:text-[var(--text-secondary)] hover:border-[var(--border-secondary)]'
            }`}
          >
            Análisis
          </button>
        </nav>
      </div>

      {activeTab === 'plans' && (
        <Card className="p-4">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1">
              <Input
                placeholder="Buscar planes por número, estado o notas..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full"
              />
            </div>
            <Button variant="outline" onClick={() => console.log('Export filtered')}>
              <Download className="w-4 h-4 mr-2" />
              Exportar
            </Button>
          </div>
        </Card>
      )}

      {/* Procurement Plans Grid - Mobile-Optimized */}
      {activeTab === 'plans' && (
        <div className="grid gap-4 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3">
          {isPlansLoading ? (
            <div className="col-span-full flex justify-center items-center h-32">
              <Loader className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
            </div>
          ) : (
            filteredPlans.map((plan) => {
              const statusConfig = getPlanStatusConfig(plan.status);
              const nextStageConfig = getStageActionConfig(plan.status);
              const isEditing = editingPlan?.id === plan.id;
              const isEditable = canEdit(plan.status);
              
              // Build actions array with proper priority hierarchy for better UX
              const actions = [];
              
              // Edit mode actions (highest priority when editing)
              if (isEditing) {
                actions.push(
                  {
                    label: 'Guardar',
                    icon: Save,
                    variant: 'primary' as const,
                    priority: 'primary' as const,
                    onClick: handleSaveEdit
                  },
                  {
                    label: 'Cancelar',
                    icon: X,
                    variant: 'outline' as const,
                    priority: 'primary' as const,
                    destructive: true,
                    onClick: handleCancelEdit
                  }
                );
              } else {
                // Primary action: Stage transition (most important)
                if (nextStageConfig) {
                  actions.push({
                    label: nextStageConfig.label,
                    icon: nextStageConfig.icon,
                    variant: nextStageConfig.variant,
                    priority: 'primary' as const,
                    onClick: () => handleStageTransition(plan.id, plan.status)
                  });
                }

                // Secondary actions: Edit and View
                if (isEditable) {
                  actions.push({
                    label: 'Editar',
                    icon: Edit,
                    variant: 'outline' as const,
                    priority: 'secondary' as const,
                    onClick: () => handleEditPlan(plan)
                  });
                }

                actions.push({
                  label: 'Ver',
                  icon: Eye,
                  variant: 'outline' as const,
                  priority: 'secondary' as const,
                  onClick: () => {
                    setSelectedPlan(plan);
                    setModalMode('view');
                    setShowForm(true);
                  }
                });

                // Show Critical Requirements button
                actions.push({
                  label: 'Req. Críticos',
                  icon: AlertCircle,
                  variant: 'outline' as const,
                  priority: 'secondary' as const,
                  onClick: () => handleShowCriticalRequirements(plan.id)
                });

                // Tertiary action: Cancel (least prominent, destructive)
                if (!['completed', 'cancelled'].includes(plan.status)) {
                  actions.push({
                    label: 'Cancelar',
                    icon: X,
                    variant: 'outline' as const,
                    priority: 'tertiary' as const,
                    destructive: true,
                    onClick: () => handleCancelPlan(plan.id)
                  });
                }
              }

              return (
                <div key={plan.id} className="space-y-2">
                  <StatusCard
                    id={plan.plan_number}
                    statusIndicator={statusConfig}
                    title={`Plan ${plan.plan_number}`}
                    subtitle={`${new Date(plan.plan_date).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: '2-digit' })} • ${plan.procurement_strategy}`}
                    primaryValue={plan.total_requirements}
                    primaryValueLabel="requerimientos"
                    secondaryInfo={{
                      label: 'Presupuesto',
                      value: `€${formatters.compact(plan.total_estimated_cost)}`
                    }}
                    progress={plan.planning_horizon_days ? {
                      label: `${plan.planning_horizon_days} días de horizonte`,
                      percentage: Math.min((plan.planning_horizon_days / 30) * 100, 100),
                      color: plan.planning_horizon_days > 14 ? '#10b981' : plan.planning_horizon_days > 7 ? '#f59e0b' : '#ef4444'
                    } : undefined}
                    metadata={[
                      `Período: ${new Date(plan.plan_period_start).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' })} - ${new Date(plan.plan_period_end).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' })}`,
                      `Creado: ${new Date(plan.created_at).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' })}`,
                      ...(plan.special_requirements ? [`Req. especiales: ${plan.special_requirements}`] : [])
                    ]}
                    actions={actions}
                  />

                  {/* Inline Edit Form for Draft Plans */}
                  {isEditing && (
                    <Card className="p-4 border-l-4 border-l-[var(--color-primary)] bg-[var(--color-primary)]/5">
                      <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3">
                        Editando Plan {plan.plan_number}
                      </h4>
                      <div className="space-y-3">
                        <div>
                          <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                            Requerimientos Especiales
                          </label>
                          <textarea
                            value={editFormData.special_requirements}
                            onChange={(e) => setEditFormData((prev: any) => ({ ...prev, special_requirements: e.target.value }))}
                            placeholder="Ingrese requerimientos especiales para este plan..."
                            className="w-full px-3 py-2 text-sm border border-[var(--border-primary)] rounded-lg
                              bg-[var(--bg-primary)] text-[var(--text-primary)] placeholder-[var(--text-tertiary)]
                              focus:ring-2 focus:ring-[var(--color-primary)]/20 focus:border-[var(--color-primary)]
                              transition-colors duration-200 resize-vertical min-h-[60px]"
                            rows={2}
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                              Días de Horizonte
                            </label>
                            <Input
                              type="number"
                              value={editFormData.planning_horizon_days}
                              onChange={(e) => setEditFormData((prev: any) => ({ ...prev, planning_horizon_days: parseInt(e.target.value) }))}
                              min="1"
                              max="365"
                              className="w-full"
                            />
                          </div>
                          <div>
                            <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                              Prioridad
                            </label>
                            <select
                              value={editFormData.priority}
                              onChange={(e) => setEditFormData((prev: any) => ({ ...prev, priority: e.target.value }))}
                              className="w-full px-3 py-2 text-sm border border-[var(--border-primary)] rounded-lg
                                bg-[var(--bg-primary)] text-[var(--text-primary)]
                                focus:ring-2 focus:ring-[var(--color-primary)]/20 focus:border-[var(--color-primary)]
                                transition-colors duration-200"
                            >
                              <option value="low">Baja</option>
                              <option value="medium">Media</option>
                              <option value="high">Alta</option>
                              <option value="urgent">Urgente</option>
                            </select>
                          </div>
                        </div>
                      </div>
                    </Card>
                  )}
                </div>
              );
            })
          )}
        </div>
      )}

      {/* Empty State for Procurement Plans */}
      {activeTab === 'plans' && !isPlansLoading && filteredPlans.length === 0 && (
        <div className="text-center py-12">
          <Package 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 planes de compra
          </h3>
          <p className="text-[var(--text-secondary)] mb-4">
            Intenta ajustar la búsqueda o generar un nuevo plan de compra
          </p>
          <Button 
            onClick={() => generatePlanMutation.mutate({
              tenantId,
              request: {
                force_regenerate: false,
                planning_horizon_days: 14,
                include_safety_stock: true,
                safety_stock_percentage: 20
              }
            })}
            disabled={generatePlanMutation.isPending}
          >
            {generatePlanMutation.isPending ? (
              <Loader className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Plus className="w-4 h-4 mr-2" />
            )}
            Generar Plan de Compra
          </Button>
        </div>
      )}

      {activeTab === 'requirements' && (
        <div className="space-y-4">
          {isCriticalLoading ? (
            <div className="flex justify-center items-center h-32">
              <Loader className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
            </div>
          ) : criticalRequirements && criticalRequirements.length > 0 ? (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {criticalRequirements.map((requirement) => (
                <StatusCard
                  key={requirement.id}
                  id={requirement.requirement_number}
                  statusIndicator={{
                    color: getStatusColor('danger'),
                    text: 'Crítico',
                    icon: AlertCircle,
                    isCritical: true
                  }}
                  title={requirement.product_name}
                  subtitle={`${requirement.requirement_number} • ${requirement.supplier_name || 'Sin proveedor'}`}
                  primaryValue={requirement.required_quantity}
                  primaryValueLabel={requirement.unit_of_measure}
                  secondaryInfo={{
                    label: 'Límite',
                    value: new Date(requirement.required_by_date).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' })
                  }}
                  progress={requirement.current_stock_level && requirement.required_quantity ? {
                    label: `${Math.round((requirement.current_stock_level / requirement.required_quantity) * 100)}% cubierto`,
                    percentage: Math.min((requirement.current_stock_level / requirement.required_quantity) * 100, 100),
                    color: requirement.current_stock_level >= requirement.required_quantity ? '#10b981' : requirement.current_stock_level >= requirement.required_quantity * 0.5 ? '#f59e0b' : '#ef4444'
                  } : undefined}
                  metadata={[
                    `Stock: ${requirement.current_stock_level || 0} ${requirement.unit_of_measure}`,
                    `Necesario: ${requirement.required_quantity - (requirement.current_stock_level || 0)} ${requirement.unit_of_measure}`,
                    `Costo: €${formatters.compact(requirement.estimated_total_cost || 0)}`,
                    `Días restantes: ${Math.ceil((new Date(requirement.required_by_date).getTime() - Date.now()) / (1000 * 60 * 60 * 24))}`
                  ]}
                  actions={[
                    {
                      label: 'Ver Detalles',
                      icon: Eye,
                      variant: 'primary',
                      priority: 'primary',
                      onClick: () => console.log('View requirement details')
                    },
                    {
                      label: 'Asignar Proveedor',
                      icon: Building2,
                      priority: 'secondary',
                      onClick: () => console.log('Assign supplier')
                    },
                    {
                      label: 'Comprar Ahora',
                      icon: ShoppingCart,
                      priority: 'secondary',
                      onClick: () => console.log('Purchase now')
                    }
                  ]}
                />
              ))}
            </div>
          ) : (
            <div className="text-center py-12">
              <CheckCircle className="mx-auto h-12 w-12 text-green-500 mb-4" />
              <h3 className="text-lg font-medium text-[var(--text-primary)] mb-2">
                No hay requerimientos críticos
              </h3>
              <p className="text-[var(--text-secondary)]">
                Todos los requerimientos están bajo control
              </p>
            </div>
          )}
        </div>
      )}

      {activeTab === 'analytics' && (
        <div className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Card className="p-6">
              <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Costos de Procurement</h3>
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-[var(--text-secondary)]">Costo Estimado Total</span>
                  <span className="text-lg font-semibold text-[var(--text-primary)]">
                    {formatters.currency(stats.totalEstimatedCost)}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-[var(--text-secondary)]">Costo Aprobado</span>
                  <span className="text-lg font-semibold text-green-600">
                    {formatters.currency(stats.totalApprovedCost)}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-sm text-[var(--text-secondary)]">Varianza</span>
                  <span className="text-lg font-semibold text-[var(--text-primary)]">
                    {formatters.currency(stats.totalEstimatedCost - stats.totalApprovedCost)}
                  </span>
                </div>
              </div>
            </Card>

            <Card className="p-6">
              <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Alertas Críticas</h3>
              <div className="space-y-3">
                {dashboardData?.low_stock_alerts?.slice(0, 5).map((alert: any, index: number) => (
                  <div key={index} className="flex items-center justify-between p-3 bg-red-50 rounded-lg">
                    <div className="flex items-center">
                      <AlertCircle className="w-4 h-4 text-red-500 mr-2" />
                      <span className="text-sm text-[var(--text-primary)]">{alert.product_name || `Alerta ${index + 1}`}</span>
                    </div>
                    <span className="text-xs text-red-600 font-medium">
                      Stock Bajo
                    </span>
                  </div>
                )) || (
                  <div className="text-center py-8">
                    <CheckCircle className="mx-auto h-8 w-8 text-green-500 mb-2" />
                    <p className="text-sm text-[var(--text-secondary)]">No hay alertas críticas</p>
                  </div>
                )}
              </div>
            </Card>
          </div>

          <Card className="p-6">
            <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-4">Resumen de Performance</h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                <p className="text-2xl font-bold text-[var(--color-primary)]">{stats.totalPlans}</p>
                <p className="text-sm text-[var(--text-secondary)] mt-1">Planes Totales</p>
              </div>
              <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                <p className="text-2xl font-bold text-green-600">{stats.activePlans}</p>
                <p className="text-sm text-[var(--text-secondary)] mt-1">Planes Activos</p>
              </div>
              <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                <p className="text-2xl font-bold text-yellow-600">{stats.pendingRequirements}</p>
                <p className="text-sm text-[var(--text-secondary)] mt-1">Pendientes</p>
              </div>
              <div className="text-center p-4 bg-[var(--bg-secondary)] rounded-lg">
                <p className="text-2xl font-bold text-red-600">{stats.criticalRequirements}</p>
                <p className="text-sm text-[var(--text-secondary)] mt-1">Críticos</p>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* Procurement Plan Modal */}
      {showForm && selectedPlan && (
        <StatusModal
          isOpen={showForm}
          onClose={() => {
            setShowForm(false);
            setSelectedPlan(null);
            setModalMode('view');
          }}
          mode={modalMode}
          onModeChange={setModalMode}
          title={`Plan de Compra ${selectedPlan.plan_number}`}
          subtitle={new Date(selectedPlan.plan_date).toLocaleDateString('es-ES')}
          statusIndicator={getPlanStatusConfig(selectedPlan.status)}
          size="lg"
          sections={[
            {
              title: 'Información del Plan',
              icon: Package,
              fields: [
                {
                  label: 'Número de Plan',
                  value: selectedPlan.plan_number,
                  highlight: true
                },
                {
                  label: 'Tipo de Plan',
                  value: selectedPlan.plan_type
                },
                {
                  label: 'Estrategia',
                  value: selectedPlan.procurement_strategy
                },
                {
                  label: 'Prioridad',
                  value: selectedPlan.priority,
                  type: 'status'
                }
              ]
            },
            {
              title: 'Fechas y Períodos',
              icon: Calendar,
              fields: [
                {
                  label: 'Fecha del Plan',
                  value: selectedPlan.plan_date,
                  type: 'date'
                },
                {
                  label: 'Período de Inicio',
                  value: selectedPlan.plan_period_start,
                  type: 'date'
                },
                {
                  label: 'Período de Fin',
                  value: selectedPlan.plan_period_end,
                  type: 'date',
                  highlight: true
                },
                {
                  label: 'Horizonte de Planificación',
                  value: `${selectedPlan.planning_horizon_days} días`
                }
              ]
            },
            {
              title: 'Información Financiera',
              icon: DollarSign,
              fields: [
                {
                  label: 'Costo Estimado Total',
                  value: selectedPlan.total_estimated_cost,
                  type: 'currency',
                  highlight: true
                },
                {
                  label: 'Costo Aprobado Total',
                  value: selectedPlan.total_approved_cost,
                  type: 'currency'
                },
                {
                  label: 'Varianza de Costo',
                  value: selectedPlan.cost_variance,
                  type: 'currency'
                }
              ]
            },
            {
              title: 'Estadísticas',
              icon: ShoppingCart,
              fields: [
                {
                  label: 'Total de Requerimientos',
                  value: `${selectedPlan.total_requirements} requerimientos`
                },
                {
                  label: 'Demanda Total (Cantidad)',
                  value: `${selectedPlan.total_demand_quantity} unidades`
                },
                {
                  label: 'Proveedores Primarios',
                  value: `${selectedPlan.primary_suppliers_count} proveedores`
                },
                {
                  label: 'Proveedores de Respaldo',
                  value: `${selectedPlan.backup_suppliers_count} proveedores`
                }
              ]
            },
            ...(selectedPlan.special_requirements ? [{
              title: 'Requerimientos Especiales',
              fields: [
                {
                  label: 'Observaciones',
                  value: selectedPlan.special_requirements,
                  span: 2 as const,
                  editable: true,
                  placeholder: 'Añadir requerimientos especiales para el plan...'
                }
              ]
            }] : [])
          ]}
          onEdit={() => {
            console.log('Editing procurement plan:', selectedPlan.id);
          }}
        />
      )}
    </div>
  );
};

export default ProcurementPage;