import React, { useState } from 'react';
import { Plus, Clock, Package, Eye, Edit, CheckCircle, AlertCircle, Timer, Users, Loader, Euro } from 'lucide-react';
import { Button, Badge, StatsGrid, StatusCard, getStatusColor, EditViewModal, Tabs, SearchAndFilter, type FilterConfig, EmptyState } from '../../../../components/ui';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { PageHeader } from '../../../../components/layout';
import {
  OrderStatus,
  OrderResponse,
  CustomerResponse,
  OrderCreate,
  CustomerCreate,
  CustomerUpdate,
  PaymentStatus,
  DeliveryMethod,
  PaymentMethod,
  OrderType,
  PriorityLevel,
  OrderSource,
  SalesChannel,
  PaymentTerms,
  CustomerType,
  CustomerSegment
} from '../../../../api/types/orders';
import { useOrders, useCustomers, useOrdersDashboard, useCreateOrder, useUpdateOrder, useCreateCustomer, useUpdateCustomer } from '../../../../api/hooks/orders';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useAuthUser } from '../../../../stores/auth.store';
import { OrderFormModal } from '../../../../components/domain/orders';
import { useTranslation } from 'react-i18next';
import { useTenantCurrency } from '../../../../hooks/useTenantCurrency';

const OrdersPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'orders' | 'customers'>('orders');
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = 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 { t } = useTranslation(['orders', 'common']);
  const { currencySymbol } = useTenantCurrency();

  // 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 updateOrderMutation = useUpdateOrder();
  const createCustomerMutation = useCreateCustomer();
  const updateCustomerMutation = useUpdateCustomer();

  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 => {
    const matchesSearch = order.order_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         order.id.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = !statusFilter || order.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  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: `${Number(orderStats.repeat_customers_rate).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}
      />

      {/* Search and Filter Controls */}
      <SearchAndFilter
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder={activeTab === 'orders'
          ? 'Buscar pedidos por número o ID...'
          : 'Buscar clientes por nombre, código o email...'
        }
        filters={activeTab === 'orders' ? [
          {
            key: 'status',
            label: 'Estado',
            type: 'dropdown',
            value: statusFilter,
            onChange: (value) => setStatusFilter(value as string),
            placeholder: 'Todos los estados',
            options: Object.values(OrderStatus).map(status => ({
              value: status,
              label: t(`orders:order_status.${status.toLowerCase()}`)
            }))
          }
        ] as FilterConfig[] : []}
      />

      {/* 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: `${currencySymbol}${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'}`,
                  `${t(`orders:delivery_methods.${order.delivery_method.toLowerCase()}`)}`,
                  ...(paymentNote ? [paymentNote] : [])
                ]}
                onClick={() => {
                  setSelectedOrder(order);
                  setIsCreating(false);
                  setModalMode('view');
                  setShowForm(true);
                }}
                actions={[
                  {
                    label: 'Ver Detalles',
                    icon: Eye,
                    variant: 'primary',
                    priority: 'primary',
                    onClick: () => {
                      setSelectedOrder(order);
                      setIsCreating(false);
                      setModalMode('view');
                      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={t(`orders:customer_types.${customer.customer_type.toLowerCase()}`)}
                primaryValue={customer.total_orders}
                primaryValueLabel="pedidos"
                secondaryInfo={{
                  label: 'Total',
                  value: `${currencySymbol}${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' })}`
                ]}
                onClick={() => {
                  setSelectedCustomer(customer);
                  setIsCreating(false);
                  setModalMode('view');
                  setShowForm(true);
                }}
                actions={[
                  {
                    label: 'Ver Detalles',
                    icon: Eye,
                    variant: 'primary',
                    priority: 'primary',
                    onClick: () => {
                      setSelectedCustomer(customer);
                      setIsCreating(false);
                      setModalMode('view');
                      setShowForm(true);
                    }
                  }
                ]}
              />
            );
          })
        )}
      </div>

      {/* Empty State */}
      {activeTab === 'orders' && filteredOrders.length === 0 && (
        <EmptyState
          icon={Package}
          title="No se encontraron pedidos"
          description="Intenta ajustar la búsqueda o crear un nuevo pedido"
          actionLabel="Nuevo Pedido"
          actionIcon={Plus}
          onAction={() => setShowNewOrderForm(true)}
        />
      )}

      {activeTab === 'customers' && filteredCustomers.length === 0 && (
        <EmptyState
          icon={Users}
          title="No se encontraron clientes"
          description="Intenta ajustar la búsqueda o crear un nuevo cliente"
          actionLabel="Nuevo Cliente"
          actionIcon={Plus}
          onAction={() => {
            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);
          }}
        />
      )}

      {/* 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: Object.values(OrderType).map(value => ({
                  value,
                  label: t(`orders:order_types.${value.toLowerCase()}`)
                }))
              },
              {
                label: 'Prioridad',
                value: selectedOrder.priority || PriorityLevel.NORMAL,
                type: 'select',
                editable: true,
                options: Object.values(PriorityLevel).map(value => ({
                  value,
                  label: t(`orders:priority_levels.${value.toLowerCase()}`)
                }))
              },
              {
                label: 'Método de Entrega',
                value: selectedOrder.delivery_method || DeliveryMethod.PICKUP,
                type: 'select',
                editable: true,
                options: Object.values(DeliveryMethod).map(value => ({
                  value,
                  label: t(`orders:delivery_methods.${value.toLowerCase()}`)
                }))
              },
              {
                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: Object.values(PaymentStatus).map(value => ({
                  value,
                  label: t(`orders:payment_status.${value.toLowerCase()}`)
                }))
              }
            ]
          },
          ...(selectedOrder.special_instructions ? [{
            title: 'Instrucciones Especiales',
            fields: [
              {
                label: 'Observaciones',
                value: selectedOrder.special_instructions,
                type: 'textarea',
                span: 2 as const,
                editable: true
              }
            ]
          }] : [])
        ];

        return (
          <EditViewModal
            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 () => {
              if (!selectedOrder || !tenantId) return;

              try {
                // Build the update payload from the selectedOrder state
                const updateData = {
                  status: selectedOrder.status,
                  priority: selectedOrder.priority,
                  requested_delivery_date: selectedOrder.requested_delivery_date,
                  delivery_method: selectedOrder.delivery_method,
                  delivery_address: selectedOrder.delivery_address,
                  delivery_instructions: selectedOrder.delivery_instructions,
                  delivery_window_start: selectedOrder.delivery_window_start,
                  delivery_window_end: selectedOrder.delivery_window_end,
                  payment_method: selectedOrder.payment_method,
                  payment_status: selectedOrder.payment_status,
                  special_instructions: selectedOrder.special_instructions,
                  custom_requirements: selectedOrder.custom_requirements,
                  allergen_warnings: selectedOrder.allergen_warnings,
                };

                await updateOrderMutation.mutateAsync({
                  tenantId: tenantId,
                  orderId: selectedOrder.id,
                  data: updateData
                });

                setShowForm(false);
              } catch (error) {
                console.error('Failed to update order:', error);
              }
            }}
            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: Object.values(CustomerType).map(value => ({
                  value,
                  label: t(`orders:customer_types.${value.toLowerCase()}`)
                }))
              },
              {
                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
              },
              {
                label: 'País',
                value: selectedCustomer.country || 'España',
                type: 'text',
                editable: isCreating,
                highlight: false
              }
            ]
          },
          {
            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: Object.values(DeliveryMethod).map(value => ({
                  value,
                  label: t(`orders:delivery_methods.${value.toLowerCase()}`)
                }))
              },
              {
                label: 'Términos de Pago',
                value: selectedCustomer.payment_terms || PaymentTerms.IMMEDIATE,
                type: 'select',
                editable: true,
                options: Object.values(PaymentTerms).map(value => ({
                  value,
                  label: t(`orders:payment_terms.${value.toLowerCase()}`)
                }))
              },
              {
                label: 'Descuento (%)',
                value: selectedCustomer.discount_percentage || 0,
                type: 'number',
                editable: true
              },
              {
                label: 'Segmento',
                value: selectedCustomer.customer_segment || CustomerSegment.REGULAR,
                type: 'select',
                editable: true,
                options: Object.values(CustomerSegment).map(value => ({
                  value,
                  label: t(`orders:customer_segments.${value.toLowerCase()}`)
                }))
              },
              {
                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 (
          <EditViewModal
            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 () => {
              if (!selectedCustomer || !tenantId) {
                console.error('Missing required data for customer save');
                return;
              }

              try {
                if (isCreating) {
                  // Create new customer
                  const customerData: CustomerCreate = {
                    tenant_id: tenantId,
                    customer_code: selectedCustomer.customer_code || `CUST-${Date.now()}`,
                    name: selectedCustomer.name,
                    business_name: selectedCustomer.business_name,
                    customer_type: selectedCustomer.customer_type,
                    email: selectedCustomer.email,
                    phone: selectedCustomer.phone,
                    city: selectedCustomer.city,
                    country: selectedCustomer.country || 'España',
                    is_active: selectedCustomer.is_active,
                    preferred_delivery_method: selectedCustomer.preferred_delivery_method,
                    payment_terms: selectedCustomer.payment_terms,
                    discount_percentage: selectedCustomer.discount_percentage,
                    customer_segment: selectedCustomer.customer_segment,
                    priority_level: selectedCustomer.priority_level,
                    special_instructions: selectedCustomer.special_instructions
                  };

                  await createCustomerMutation.mutateAsync(customerData);
                  console.log('Customer created successfully');
                } else {
                  // Update existing customer
                  const updateData: CustomerUpdate = {
                    name: selectedCustomer.name,
                    business_name: selectedCustomer.business_name,
                    customer_type: selectedCustomer.customer_type,
                    email: selectedCustomer.email,
                    phone: selectedCustomer.phone,
                    city: selectedCustomer.city,
                    preferred_delivery_method: selectedCustomer.preferred_delivery_method,
                    payment_terms: selectedCustomer.payment_terms,
                    discount_percentage: selectedCustomer.discount_percentage,
                    customer_segment: selectedCustomer.customer_segment,
                    is_active: selectedCustomer.is_active,
                    special_instructions: selectedCustomer.special_instructions
                  };

                  await updateCustomerMutation.mutateAsync({
                    tenantId,
                    customerId: selectedCustomer.id!,
                    data: updateData
                  });
                  console.log('Customer updated successfully');
                }

                // Close modal and reset state
                setShowForm(false);
                setSelectedCustomer(null);
                setIsCreating(false);
                setModalMode('view');
              } catch (error) {
                console.error('Error saving customer:', error);
                throw error; // Let the modal show the error
              }
            }}
            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',
                'País': 'country',
                '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;
