import React, { useState } from 'react';
import { Plus, Clock, Package, Eye, Edit, CheckCircle, AlertCircle, Timer, Users, Loader, Euro } from 'lucide-react';
import { Button, Input, Card, Badge, StatsGrid, StatusCard, getStatusColor, StatusModal, Tabs } from '../../../../components/ui';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { PageHeader } from '../../../../components/layout';
import {
  OrderStatus,
  OrderResponse,
  CustomerResponse,
  OrderCreate,
  PaymentStatus,
  DeliveryMethod,
  PaymentMethod,
  OrderType,
  PriorityLevel,
  OrderSource,
  SalesChannel,
  PaymentTerms,
  CustomerType,
  CustomerSegment
} from '../../../../api/types/orders';
import { useOrders, useCustomers, useOrdersDashboard, useCreateOrder, useCreateCustomer } from '../../../../api/hooks/orders';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useAuthUser } from '../../../../stores/auth.store';
import { OrderFormModal } from '../../../../components/domain/orders';
import { useOrderEnums } from '../../../../utils/enumHelpers';

const OrdersPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'orders' | 'customers'>('orders');
  const [searchTerm, setSearchTerm] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
  const [selectedOrder, setSelectedOrder] = useState<OrderResponse | null>(null);
  const [selectedCustomer, setSelectedCustomer] = useState<CustomerResponse | null>(null);
  const [isCreating, setIsCreating] = useState(false);
  const [showNewOrderForm, setShowNewOrderForm] = useState(false);
  const [showNewCustomerForm, setShowNewCustomerForm] = useState(false);

  // Get tenant ID from tenant store (preferred) or auth user (fallback)
  const currentTenant = useCurrentTenant();
  const user = useAuthUser();
  const tenantId = currentTenant?.id || user?.tenant_id || '';
  const orderEnums = useOrderEnums();

  // API hooks for orders
  const {
    data: ordersData,
    isLoading: ordersLoading,
    error: ordersError
  } = useOrders({
    tenant_id: tenantId,
    status_filter: activeTab === 'orders' ? undefined : undefined,
    limit: 100
  });

  // API hooks for customers
  const {
    data: customersData,
    isLoading: customersLoading,
    error: customersError
  } = useCustomers({
    tenant_id: tenantId,
    active_only: true,
    limit: 100
  });

  // API hooks for dashboard data
  const {
    data: dashboardData,
    isLoading: dashboardLoading,
    error: dashboardError
  } = useOrdersDashboard(tenantId);

  // Mutations
  const createOrderMutation = useCreateOrder();
  const createCustomerMutation = useCreateCustomer();

  const orders = ordersData || [];
  const customers = customersData || [];

  const getOrderStatusConfig = (status: OrderStatus, paymentStatus?: PaymentStatus) => {
    const statusConfig = {
      [OrderStatus.PENDING]: { text: 'Pendiente', icon: Clock },
      [OrderStatus.CONFIRMED]: { text: 'Confirmado', icon: CheckCircle },
      [OrderStatus.IN_PRODUCTION]: { text: 'En Producción', icon: Timer },
      [OrderStatus.READY]: { text: 'Listo', icon: CheckCircle },
      [OrderStatus.OUT_FOR_DELIVERY]: { text: 'En Reparto', icon: Timer },
      [OrderStatus.DELIVERED]: { text: 'Entregado', icon: CheckCircle },
      [OrderStatus.CANCELLED]: { text: 'Cancelado', icon: AlertCircle },
      [OrderStatus.FAILED]: { text: 'Fallido', icon: AlertCircle },
    };

    const config = statusConfig[status];
    const Icon = config?.icon;
    const isPaymentPending = paymentStatus === PaymentStatus.PENDING;

    return {
      color: getStatusColor(
        status === OrderStatus.DELIVERED ? 'completed' :
        status === OrderStatus.PENDING ? 'pending' :
        status === OrderStatus.CANCELLED || status === OrderStatus.FAILED ? 'cancelled' :
        'in_progress'
      ),
      text: config?.text || status,
      icon: Icon,
      isCritical: status === OrderStatus.FAILED,
      isHighlight: isPaymentPending
    };
  };

  const getCustomerStatusConfig = (isActive: boolean) => {
    return {
      color: getStatusColor(isActive ? 'completed' : 'cancelled'),
      text: isActive ? 'Activo' : 'Inactivo',
      icon: isActive ? CheckCircle : AlertCircle,
      isCritical: false,
      isHighlight: false
    };
  };

  const filteredOrders = orders.filter(order => {
    return order.order_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
           order.id.toLowerCase().includes(searchTerm.toLowerCase());
  });

  const filteredCustomers = customers.filter(customer => {
    return customer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
           customer.customer_code.toLowerCase().includes(searchTerm.toLowerCase()) ||
           (customer.email && customer.email.toLowerCase().includes(searchTerm.toLowerCase()));
  });

  const orderStats = dashboardData || {
    total_orders_today: 0,
    total_orders_this_week: 0,
    total_orders_this_month: 0,
    revenue_today: 0,
    revenue_this_week: 0,
    revenue_this_month: 0,
    pending_orders: 0,
    confirmed_orders: 0,
    in_production_orders: 0,
    ready_orders: 0,
    delivered_orders: 0,
    total_customers: 0,
    new_customers_this_month: 0,
    repeat_customers_rate: 0,
    average_order_value: 0,
    order_fulfillment_rate: 0,
    on_time_delivery_rate: 0
  };

  const getStatsForActiveTab = () => {
    if (activeTab === 'orders') {
      return [
        {
          title: 'Pedidos Hoy',
          value: orderStats.total_orders_today,
          variant: 'default' as const,
          icon: Package,
        },
        {
          title: 'Pendientes',
          value: orderStats.pending_orders,
          variant: 'warning' as const,
          icon: Clock,
        },
        {
          title: 'En Producción',
          value: orderStats.in_production_orders,
          variant: 'info' as const,
          icon: Timer,
        },
        {
          title: 'Listos',
          value: orderStats.ready_orders,
          variant: 'success' as const,
          icon: CheckCircle,
        },
        {
          title: 'Ingresos Hoy',
          value: formatters.currency(orderStats.revenue_today),
          variant: 'success' as const,
          icon: Euro,
        },
        {
          title: 'Valor Promedio',
          value: formatters.currency(orderStats.average_order_value),
          variant: 'info' as const,
          icon: Euro,
        },
      ];
    } else {
      return [
        {
          title: 'Total Clientes',
          value: orderStats.total_customers,
          variant: 'default' as const,
          icon: Users,
        },
        {
          title: 'Nuevos Este Mes',
          value: orderStats.new_customers_this_month,
          variant: 'success' as const,
          icon: Users,
        },
        {
          title: 'Tasa de Repetición',
          value: `${(orderStats.repeat_customers_rate * 100).toFixed(1)}%`,
          variant: 'info' as const,
          icon: Users,
        },
        {
          title: 'Clientes Activos',
          value: customers.filter(c => c.is_active).length,
          variant: 'success' as const,
          icon: CheckCircle,
        },
        {
          title: 'Valor Total',
          value: formatters.currency(customers.reduce((sum, c) => sum + Number(c.total_spent || 0), 0)),
          variant: 'success' as const,
          icon: Euro,
        },
        {
          title: 'Promedio por Cliente',
          value: formatters.currency(customers.reduce((sum, c) => sum + Number(c.average_order_value || 0), 0) / Math.max(customers.length, 1)),
          variant: 'info' as const,
          icon: Euro,
        },
      ];
    }
  };

  const stats = getStatsForActiveTab();

  // Loading state
  if (ordersLoading || customersLoading || dashboardLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <Loader className="h-8 w-8 animate-spin mx-auto mb-4 text-[var(--primary)]" />
          <p className="text-[var(--text-secondary)]">
            Cargando {activeTab === 'orders' ? 'pedidos' : 'clientes'}...
          </p>
        </div>
      </div>
    );
  }

  // Error state
  if (ordersError || customersError || dashboardError) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <AlertCircle className="h-8 w-8 mx-auto mb-4 text-red-500" />
          <p className="text-red-600 mb-2">
            Error al cargar {activeTab === 'orders' ? 'los pedidos' : 'los clientes'}
          </p>
          <p className="text-[var(--text-secondary)] text-sm">
            {(ordersError as any)?.message || (customersError as any)?.message || (dashboardError as any)?.message || 'Error desconocido'}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4 sm:space-y-6">
      <PageHeader
        title={activeTab === 'orders' ? 'Gestión de Pedidos' : 'Gestión de Clientes'}
        description={activeTab === 'orders' ? 'Administra y supervisa todos los pedidos de la panadería' : 'Administra y supervisa todos los clientes de la panadería'}
        actions={[
          {
            id: "new",
            label: activeTab === 'orders' ? 'Nuevo Pedido' : 'Nuevo Cliente',
            variant: "primary" as const,
            icon: Plus,
            onClick: () => {
              if (activeTab === 'orders') {
                setShowNewOrderForm(true);
              } else {
                setSelectedCustomer({
                  name: '',
                  business_name: '',
                  customer_type: CustomerType.INDIVIDUAL,
                  email: '',
                  phone: '',
                  country: 'España',
                  is_active: true,
                  preferred_delivery_method: DeliveryMethod.PICKUP,
                  payment_terms: PaymentTerms.IMMEDIATE,
                  discount_percentage: 0,
                  customer_segment: CustomerSegment.REGULAR,
                  priority_level: PriorityLevel.NORMAL
                } as any);
                setIsCreating(true);
                setModalMode('edit');
                setShowForm(true);
              }
            }
          }
        ]}
      />

      {/* Tabs */}
      <Tabs
        items={[
          { id: 'orders', label: 'Pedidos' },
          { id: 'customers', label: 'Clientes' }
        ]}
        activeTab={activeTab}
        onTabChange={(tabId) => setActiveTab(tabId as 'orders' | 'customers')}
        fullWidth={true}
        variant="pills"
        size="md"
      />

      {/* Stats Grid */}
      <StatsGrid
        stats={stats}
        columns={3}
      />

      {/* Simplified Controls */}
      <Card className="p-4">
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="flex-1">
            <Input
              placeholder={activeTab === 'orders' ? 'Buscar pedidos por número o ID...' : 'Buscar clientes por nombre, código o email...'}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full"
            />
          </div>
        </div>
      </Card>

      {/* Content Grid - Mobile-first responsive */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {activeTab === 'orders' ? (
          filteredOrders.map((order) => {
            const statusConfig = getOrderStatusConfig(order.status, order.payment_status);
            const paymentNote = order.payment_status === PaymentStatus.PENDING ? 'Pago pendiente' : '';

            // Find customer data for better display
            const customer = customers.find(c => c.id === order.customer_id);
            const customerDisplayName = customer?.name || `Cliente ID: ${order.customer_id}`;

            return (
              <StatusCard
                key={order.id}
                id={order.id}
                statusIndicator={statusConfig}
                title={order.order_number}
                subtitle={customerDisplayName}
                primaryValue={order.items?.length || 0}
                primaryValueLabel="artículos"
                secondaryInfo={{
                  label: 'Total',
                  value: `€${formatters.compact(order.total_amount)}`
                }}
                metadata={[
                  `Pedido: ${new Date(order.order_date).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' })}`,
                  `Entrega: ${order.requested_delivery_date ?
                    new Date(order.requested_delivery_date).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit' }) :
                    'Sin fecha'}`,
                  `${orderEnums.getDeliveryMethodLabel(order.delivery_method)}`,
                  ...(paymentNote ? [paymentNote] : [])
                ]}
                actions={[
                  {
                    label: 'Ver Detalles',
                    icon: Eye,
                    variant: 'primary',
                    priority: 'primary',
                    onClick: () => {
                      setSelectedOrder(order);
                      setIsCreating(false);
                      setModalMode('view');
                      setShowForm(true);
                    }
                  },
                  {
                    label: 'Editar',
                    icon: Edit,
                    priority: 'secondary',
                    onClick: () => {
                      setSelectedOrder(order);
                      setIsCreating(false);
                      setModalMode('edit');
                      setShowForm(true);
                    }
                  }
                ]}
              />
            );
          })
        ) : (
          filteredCustomers.map((customer) => {
            const statusConfig = getCustomerStatusConfig(customer.is_active);

            return (
              <StatusCard
                key={customer.id}
                id={customer.id}
                statusIndicator={statusConfig}
                title={customer.name}
                subtitle={orderEnums.getCustomerTypeLabel(customer.customer_type)}
                primaryValue={customer.total_orders}
                primaryValueLabel="pedidos"
                secondaryInfo={{
                  label: 'Total',
                  value: `€${formatters.compact(customer.total_spent || 0)}`
                }}
                metadata={[
                  `${customer.customer_code}`,
                  customer.city || 'Sin ubicación',
                  customer.email || 'Sin email',
                  `Desde ${new Date(customer.created_at).toLocaleDateString('es-ES', { day: '2-digit', month: '2-digit', year: '2-digit' })}`
                ]}
                actions={[
                  {
                    label: 'Ver Detalles',
                    icon: Eye,
                    variant: 'primary',
                    priority: 'primary',
                    onClick: () => {
                      setSelectedCustomer(customer);
                      setIsCreating(false);
                      setModalMode('view');
                      setShowForm(true);
                    }
                  },
                  {
                    label: 'Editar',
                    icon: Edit,
                    priority: 'secondary',
                    onClick: () => {
                      setSelectedCustomer(customer);
                      setIsCreating(false);
                      setModalMode('edit');
                      setShowForm(true);
                    }
                  }
                ]}
              />
            );
          })
        )}
      </div>

      {/* Empty State */}
      {activeTab === 'orders' && filteredOrders.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 pedidos
          </h3>
          <p className="text-[var(--text-secondary)] mb-4">
            Intenta ajustar la búsqueda o crear un nuevo pedido
          </p>
          <Button onClick={() => setShowNewOrderForm(true)}>
            <Plus className="w-4 h-4 mr-2" />
            Nuevo Pedido
          </Button>
        </div>
      )}

      {activeTab === 'customers' && filteredCustomers.length === 0 && (
        <div className="text-center py-12">
          <Users 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 clientes
          </h3>
          <p className="text-[var(--text-secondary)] mb-4">
            Intenta ajustar la búsqueda o crear un nuevo cliente
          </p>
          <Button onClick={() => {
            setSelectedCustomer({
              name: '',
              business_name: '',
              customer_type: CustomerType.INDIVIDUAL,
              email: '',
              phone: '',
              country: 'España',
              is_active: true,
              preferred_delivery_method: DeliveryMethod.PICKUP,
              payment_terms: PaymentTerms.IMMEDIATE,
              discount_percentage: 0,
              customer_segment: CustomerSegment.REGULAR,
              priority_level: PriorityLevel.NORMAL
            } as any);
            setIsCreating(true);
            setModalMode('edit');
            setShowForm(true);
          }}>
            <Plus className="w-4 h-4 mr-2" />
            Nuevo Cliente
          </Button>
        </div>
      )}

      {/* Order Details Modal */}
      {showForm && selectedOrder && activeTab === 'orders' && (() => {
        const sections = [
          {
            title: 'Información del Pedido',
            icon: Package,
            fields: [
              {
                label: 'Número de Pedido',
                value: selectedOrder.order_number || '',
                type: 'text',
                highlight: true,
                editable: false
              },
              {
                label: 'Tipo de Pedido',
                value: selectedOrder.order_type || OrderType.STANDARD,
                type: 'select',
                editable: true,
                options: orderEnums.getOrderTypeOptions()
              },
              {
                label: 'Prioridad',
                value: selectedOrder.priority || PriorityLevel.NORMAL,
                type: 'select',
                editable: true,
                options: orderEnums.getPriorityLevelOptions()
              },
              {
                label: 'Método de Entrega',
                value: selectedOrder.delivery_method || DeliveryMethod.PICKUP,
                type: 'select',
                editable: true,
                options: orderEnums.getDeliveryMethodOptions()
              },
              {
                label: 'Fecha del Pedido',
                value: selectedOrder.order_date,
                type: 'datetime',
                editable: false
              },
              {
                label: 'Fecha de Entrega Solicitada',
                value: selectedOrder.requested_delivery_date,
                type: 'datetime',
                editable: true,
                highlight: true
              }
            ]
          },
          {
            title: 'Información Financiera',
            icon: Euro,
            fields: [
              {
                label: 'Subtotal',
                value: selectedOrder.subtotal,
                type: 'currency',
                editable: false
              },
              {
                label: 'Descuento',
                value: selectedOrder.discount_amount,
                type: 'currency',
                editable: true
              },
              {
                label: 'Impuestos',
                value: selectedOrder.tax_amount,
                type: 'currency',
                editable: false
              },
              {
                label: 'Gastos de Envío',
                value: selectedOrder.delivery_fee,
                type: 'currency',
                editable: true
              },
              {
                label: 'Total',
                value: selectedOrder.total_amount,
                type: 'currency',
                highlight: true,
                editable: false
              },
              {
                label: 'Estado del Pago',
                value: selectedOrder.payment_status || PaymentStatus.PENDING,
                type: 'select',
                editable: true,
                options: orderEnums.getPaymentStatusOptions()
              }
            ]
          },
          ...(selectedOrder.special_instructions ? [{
            title: 'Instrucciones Especiales',
            fields: [
              {
                label: 'Observaciones',
                value: selectedOrder.special_instructions,
                type: 'textarea',
                span: 2 as const,
                editable: true
              }
            ]
          }] : [])
        ];

        return (
          <StatusModal
            isOpen={showForm}
            onClose={() => {
              setShowForm(false);
              setSelectedOrder(null);
              setModalMode('view');
              setIsCreating(false);
            }}
            mode={modalMode}
            onModeChange={setModalMode}
            title={isCreating ? 'Nuevo Pedido' : selectedOrder.order_number || 'Pedido'}
            subtitle={isCreating ? 'Crear nuevo pedido' : `Cliente: ${selectedOrder.customer_id}`}
            statusIndicator={isCreating ? undefined : getOrderStatusConfig(selectedOrder.status, selectedOrder.payment_status)}
            size="lg"
            sections={sections}
            showDefaultActions={true}
            onSave={async () => {
              console.log('Saving order:', selectedOrder);
            }}
            onFieldChange={(sectionIndex, fieldIndex, value) => {
              const newOrder = { ...selectedOrder };
              const section = sections[sectionIndex];
              const field = section.fields[fieldIndex];

              const fieldMapping: { [key: string]: string } = {
                'Tipo de Pedido': 'order_type',
                'Prioridad': 'priority',
                'Método de Entrega': 'delivery_method',
                'Fecha de Entrega Solicitada': 'requested_delivery_date',
                'Descuento': 'discount_amount',
                'Gastos de Envío': 'delivery_fee',
                'Estado del Pago': 'payment_status',
                'Observaciones': 'special_instructions'
              };

              const propertyName = fieldMapping[field.label];
              if (propertyName) {
                (newOrder as any)[propertyName] = value;
                setSelectedOrder(newOrder);
              }
            }}
          />
        );
      })()}

      {/* Customer Details Modal */}
      {showForm && selectedCustomer && activeTab === 'customers' && (() => {
        const sections = [
          {
            title: 'Información de Contacto',
            icon: Users,
            fields: [
              {
                label: 'Nombre',
                value: selectedCustomer.name || '',
                type: 'text',
                highlight: true,
                editable: true,
                required: true
              },
              {
                label: 'Nombre Comercial',
                value: selectedCustomer.business_name || '',
                type: 'text',
                editable: true
              },
              {
                label: 'Tipo de Cliente',
                value: selectedCustomer.customer_type || CustomerType.INDIVIDUAL,
                type: 'select',
                editable: true,
                options: orderEnums.getCustomerTypeOptions()
              },
              {
                label: 'Email',
                value: selectedCustomer.email || '',
                type: 'email',
                editable: true
              },
              {
                label: 'Teléfono',
                value: selectedCustomer.phone || '',
                type: 'tel',
                editable: true
              },
              {
                label: 'Ciudad',
                value: selectedCustomer.city || '',
                type: 'text',
                editable: true
              }
            ]
          },
          {
            title: 'Configuración Comercial',
            icon: Euro,
            fields: [
              {
                label: 'Código de Cliente',
                value: selectedCustomer.customer_code || '',
                type: 'text',
                highlight: true,
                editable: isCreating
              },
              {
                label: 'Método de Entrega Preferido',
                value: selectedCustomer.preferred_delivery_method || DeliveryMethod.PICKUP,
                type: 'select',
                editable: true,
                options: orderEnums.getDeliveryMethodOptions()
              },
              {
                label: 'Términos de Pago',
                value: selectedCustomer.payment_terms || PaymentTerms.IMMEDIATE,
                type: 'select',
                editable: true,
                options: orderEnums.getPaymentTermsOptions()
              },
              {
                label: 'Descuento (%)',
                value: selectedCustomer.discount_percentage || 0,
                type: 'number',
                editable: true
              },
              {
                label: 'Segmento',
                value: selectedCustomer.customer_segment || CustomerSegment.REGULAR,
                type: 'select',
                editable: true,
                options: orderEnums.getCustomerSegmentOptions()
              },
              {
                label: 'Estado',
                value: selectedCustomer.is_active,
                type: 'boolean',
                editable: true
              }
            ]
          },
          ...(selectedCustomer.special_instructions ? [{
            title: 'Instrucciones Especiales',
            fields: [
              {
                label: 'Observaciones',
                value: selectedCustomer.special_instructions,
                type: 'textarea',
                span: 2 as const,
                editable: true
              }
            ]
          }] : [])
        ];

        return (
          <StatusModal
            isOpen={showForm}
            onClose={() => {
              setShowForm(false);
              setSelectedCustomer(null);
              setModalMode('view');
              setIsCreating(false);
            }}
            mode={modalMode}
            onModeChange={setModalMode}
            title={isCreating ? 'Nuevo Cliente' : selectedCustomer.name || 'Cliente'}
            subtitle={isCreating ? 'Crear nuevo cliente' : `Cliente ${selectedCustomer.customer_code || ''}`}
            statusIndicator={isCreating ? undefined : getCustomerStatusConfig(selectedCustomer.is_active)}
            size="lg"
            sections={sections}
            showDefaultActions={true}
            onSave={async () => {
              console.log('Saving customer:', selectedCustomer);
            }}
            onFieldChange={(sectionIndex, fieldIndex, value) => {
              const newCustomer = { ...selectedCustomer };
              const section = sections[sectionIndex];
              const field = section.fields[fieldIndex];

              const fieldMapping: { [key: string]: string } = {
                'Nombre': 'name',
                'Nombre Comercial': 'business_name',
                'Tipo de Cliente': 'customer_type',
                'Email': 'email',
                'Teléfono': 'phone',
                'Ciudad': 'city',
                'Código de Cliente': 'customer_code',
                'Método de Entrega Preferido': 'preferred_delivery_method',
                'Términos de Pago': 'payment_terms',
                'Descuento (%)': 'discount_percentage',
                'Segmento': 'customer_segment',
                'Estado': 'is_active',
                'Observaciones': 'special_instructions'
              };

              const propertyName = fieldMapping[field.label];
              if (propertyName) {
                (newCustomer as any)[propertyName] = value;
                setSelectedCustomer(newCustomer);
              }
            }}
          />
        );
      })()}

      {/* New Order Form Modal */}
      <OrderFormModal
        isOpen={showNewOrderForm}
        onClose={() => setShowNewOrderForm(false)}
        onSave={async (orderData) => {
          try {
            await createOrderMutation.mutateAsync(orderData);
            setShowNewOrderForm(false);
          } catch (error) {
            console.error('Error creating order:', error);
            throw error;
          }
        }}
      />
    </div>
  );
};

export default OrdersPage;