import React, { useState } from 'react';
import { Plus, Building2, Phone, Mail, Eye, Edit, CheckCircle, AlertCircle, Timer, Users, Euro, Loader, Trash2, DollarSign, Package } from 'lucide-react';
import { Button, Badge, StatsGrid, StatusCard, getStatusColor, EditViewModal, AddModal, SearchAndFilter, DialogModal, Modal, ModalHeader, ModalBody, type FilterConfig, EmptyState } from '../../../../components/ui';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { PageHeader } from '../../../../components/layout';
import { SupplierStatus, SupplierType, PaymentTerms } from '../../../../api/types/suppliers';
import { useSuppliers, useSupplierStatistics, useCreateSupplier, useUpdateSupplier, useApproveSupplier, useDeleteSupplier, useHardDeleteSupplier, useSupplierPriceLists, useCreateSupplierPriceList, useUpdateSupplierPriceList, useDeleteSupplierPriceList } from '../../../../api/hooks/suppliers';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useAuthUser } from '../../../../stores/auth.store';
import { useTranslation } from 'react-i18next';
import { useTenantCurrency } from '../../../../hooks/useTenantCurrency';
import { statusColors } from '../../../../styles/colors';
import { DeleteSupplierModal, SupplierPriceListViewModal, PriceListModal } from '../../../../components/domain/suppliers';
import { useQueryClient } from '@tanstack/react-query';
import { UnifiedAddWizard } from '../../../../components/domain/unified-wizard';
import type { ItemType } from '../../../../components/domain/unified-wizard';

const SuppliersPage: React.FC = () => {
  const [activeTab] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
  const [selectedSupplier, setSelectedSupplier] = useState<any>(null);
  const [showAddModal, setShowAddModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showApprovalModal, setShowApprovalModal] = useState(false);
  const [supplierToApprove, setSupplierToApprove] = useState<any>(null);
  const [showPriceListView, setShowPriceListView] = useState(false);
  const [showAddPrice, setShowAddPrice] = useState(false);
  const [priceListSupplier, setPriceListSupplier] = useState<any>(null);
  const [isWizardOpen, setIsWizardOpen] = 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 { currencySymbol } = useTenantCurrency();

  // API hooks
  const {
    data: suppliersData,
    isLoading: suppliersLoading,
    error: suppliersError
  } = useSuppliers(tenantId, {
    search_term: searchTerm || undefined,
    status: activeTab !== 'all' ? activeTab as any : undefined,
    limit: 100
  });

  const {
    data: statisticsData,
    isLoading: statisticsLoading,
    error: statisticsError
  } = useSupplierStatistics(tenantId);

  const suppliers = suppliersData || [];
  const { t } = useTranslation(['suppliers', 'common']);
  const queryClient = useQueryClient();

  // Mutation hooks
  const createSupplierMutation = useCreateSupplier();
  const updateSupplierMutation = useUpdateSupplier();
  const approveSupplierMutation = useApproveSupplier();
  const softDeleteMutation = useDeleteSupplier();
  const hardDeleteMutation = useHardDeleteSupplier();

  // Price list hooks
  const {
    data: priceListsData,
    isLoading: priceListsLoading,
    isRefetching: isRefetchingPriceLists
  } = useSupplierPriceLists(
    tenantId,
    priceListSupplier?.id || '',
    !!priceListSupplier?.id && showPriceListView
  );

  const createPriceListMutation = useCreateSupplierPriceList();
  const updatePriceListMutation = useUpdateSupplierPriceList();
  const deletePriceListMutation = useDeleteSupplierPriceList();

  // Delete handlers
  // Handle wizard completion
  const handleWizardComplete = (itemType: ItemType, data?: any) => {
    console.log('✅ Wizard completed:', itemType, data);
    // Refresh the suppliers list
    queryClient.invalidateQueries({ queryKey: ['suppliers', tenantId] });
  };

  const handleSoftDelete = async (supplierId: string) => {
    await softDeleteMutation.mutateAsync({ tenantId, supplierId });
  };

  const handleHardDelete = async (supplierId: string) => {
    return await hardDeleteMutation.mutateAsync({ tenantId, supplierId });
  };

  // Price list handlers
  const handlePriceListSaveComplete = async () => {
    if (!tenantId || !priceListSupplier?.id) return;
    await queryClient.invalidateQueries({
      queryKey: ['supplier-price-lists', tenantId, priceListSupplier.id]
    });
  };

  const handleAddPriceSubmit = async (priceListData: any) => {
    if (!priceListSupplier) return;

    await createPriceListMutation.mutateAsync({
      tenantId,
      supplierId: priceListSupplier.id,
      priceListData
    });

    // Close the add modal
    setShowAddPrice(false);
  };

  const getSupplierStatusConfig = (status: SupplierStatus) => {
    const statusConfig = {
      [SupplierStatus.ACTIVE]: { text: t(`suppliers:status.${status.toLowerCase()}`), icon: CheckCircle },
      [SupplierStatus.INACTIVE]: { text: t(`suppliers:status.${status.toLowerCase()}`), icon: Timer },
      [SupplierStatus.PENDING_APPROVAL]: { text: t(`suppliers:status.${status.toLowerCase()}`), icon: AlertCircle },
      [SupplierStatus.SUSPENDED]: { text: t(`suppliers:status.${status.toLowerCase()}`), icon: AlertCircle },
      [SupplierStatus.BLACKLISTED]: { text: t(`suppliers:status.${status.toLowerCase()}`), icon: AlertCircle },
    };
    
    const config = statusConfig[status];
    const Icon = config?.icon;
    
    return {
      color: getStatusColor(status === SupplierStatus.ACTIVE ? 'completed' : 
             status === SupplierStatus.PENDING_APPROVAL ? 'pending' : 'cancelled'),
      text: config?.text || status,
      icon: Icon,
      isCritical: status === SupplierStatus.BLACKLISTED,
      isHighlight: status === SupplierStatus.PENDING_APPROVAL
    };
  };

  const getSupplierTypeText = (type: SupplierType): string => {
    return t(`suppliers:types.${type.toLowerCase()}`);
  };

  const getPaymentTermsText = (terms: PaymentTerms): string => {
    return t(`suppliers:payment_terms.${terms.toLowerCase()}`);
  };

  // Apply additional client-side filtering
  const filteredSuppliers = suppliers.filter(supplier => {
    const matchesStatus = !statusFilter || supplier.status === statusFilter;
    const matchesType = !typeFilter || supplier.supplier_type === typeFilter;
    return matchesStatus && matchesType;
  });

  const supplierStats = statisticsData || {
    total_suppliers: 0,
    active_suppliers: 0,
    pending_suppliers: 0,
    avg_quality_rating: 0,
    avg_delivery_rating: 0,
    total_spend: 0
  };

  const stats = [
    {
      title: 'Total Proveedores',
      value: supplierStats.total_suppliers,
      variant: 'default' as const,
      icon: Building2,
    },
    {
      title: 'Activos',
      value: supplierStats.active_suppliers,
      variant: 'success' as const,
      icon: CheckCircle,
    },
    {
      title: 'Pendientes',
      value: supplierStats.pending_suppliers,
      variant: 'warning' as const,
      icon: AlertCircle,
    },
    {
      title: 'Gasto Total',
      value: formatters.currency(supplierStats.total_spend),
      variant: 'info' as const,
      icon: Euro,
    },
    {
      title: 'Calidad Media',
      value: supplierStats.avg_quality_rating?.toFixed(1) || '0.0',
      variant: 'success' as const,
      icon: CheckCircle,
    },
    {
      title: 'Entrega Media',
      value: supplierStats.avg_delivery_rating?.toFixed(1) || '0.0',
      variant: 'info' as const,
      icon: Building2,
    },
  ];

  // Loading state
  if (suppliersLoading || statisticsLoading) {
    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 proveedores...</p>
        </div>
      </div>
    );
  }

  // Error state
  if (suppliersError || statisticsError) {
    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 los proveedores</p>
          <p className="text-[var(--text-secondary)] text-sm">
            {(suppliersError as any)?.message || (statisticsError as any)?.message || 'Error desconocido'}
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Gestión de Proveedores"
        description="Administra y supervisa todos los proveedores de la panadería"
        actions={[
          {
            id: "new",
            label: "Nuevo Proveedor",
            variant: "primary" as const,
            icon: Plus,
            onClick: () => setIsWizardOpen(true)
          }
        ]}
      />

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

      {/* Search and Filter Controls */}
      <SearchAndFilter
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="Buscar proveedores por nombre, código, email o contacto..."
        filters={[
          {
            key: 'status',
            label: 'Estado',
            type: 'dropdown',
            value: statusFilter,
            onChange: (value) => setStatusFilter(value as string),
            placeholder: 'Todos los estados',
            options: Object.values(SupplierStatus).map(status => ({
              value: status,
              label: t(`suppliers:status.${status.toLowerCase()}`)
            }))
          },
          {
            key: 'type',
            label: 'Tipo',
            type: 'dropdown',
            value: typeFilter,
            onChange: (value) => setTypeFilter(value as string),
            placeholder: 'Todos los tipos',
            options: Object.values(SupplierType).map(type => ({
              value: type,
              label: t(`suppliers:types.${type.toLowerCase()}`)
            }))
          }
        ] as FilterConfig[]}
      />

      {/* Suppliers Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {filteredSuppliers.map((supplier) => {
          const statusConfig = getSupplierStatusConfig(supplier.status);

          return (
            <StatusCard
              key={supplier.id}
              id={supplier.id}
              statusIndicator={statusConfig}
              title={supplier.name}
              subtitle={`${getSupplierTypeText(supplier.supplier_type)} • ${supplier.city || 'Sin ubicación'}`}
              primaryValue={supplier.standard_lead_time || 0}
              primaryValueLabel="días entrega"
              secondaryInfo={{
                label: 'Pedido Min.',
                value: `${currencySymbol}${formatters.compact(supplier.minimum_order_amount || 0)}`
              }}
              metadata={[
                supplier.contact_person || 'Sin contacto',
                supplier.email || 'Sin email',
                supplier.phone || 'Sin teléfono',
                `Creado: ${new Date(supplier.created_at).toLocaleDateString('es-ES')}`
              ]}
              onClick={() => {
                setSelectedSupplier(supplier);
                setModalMode('view');
                setShowForm(true);
              }}
              actions={[
                // Primary action - View supplier details
                {
                  label: 'Ver Detalles',
                  icon: Eye,
                  variant: 'primary',
                  priority: 'primary',
                  onClick: () => {
                    setSelectedSupplier(supplier);
                    setModalMode('view');
                    setShowForm(true);
                  }
                },
                // Manage products action
                {
                  label: t('suppliers:actions.manage_products'),
                  icon: Package,
                  variant: 'outline',
                  priority: 'secondary',
                  highlighted: true,
                  onClick: () => {
                    setPriceListSupplier(supplier);
                    setShowPriceListView(true);
                  }
                },
                // Approval action - Only show for pending suppliers + admin/super_admin
                ...(supplier.status === SupplierStatus.PENDING_APPROVAL &&
                    (user?.role === 'admin' || user?.role === 'super_admin')
                  ? [{
                      label: t('suppliers:actions.approve'),
                      icon: CheckCircle,
                      variant: 'primary' as const,
                      priority: 'primary' as const,
                      highlighted: true,
                      onClick: () => {
                        setSupplierToApprove(supplier);
                        setShowApprovalModal(true);
                      }
                    }]
                  : []
                ),
                // Delete action - Only show for admin/super_admin
                ...(user?.role === 'admin' || user?.role === 'super_admin'
                  ? [{
                      label: t('suppliers:actions.delete'),
                      icon: Trash2,
                      variant: 'outline' as const,
                      priority: 'secondary' as const,
                      destructive: true,
                      onClick: () => {
                        setSelectedSupplier(supplier);
                        setShowDeleteModal(true);
                      }
                    }]
                  : []
                )
              ]}
            />
          );
        })}
      </div>

      {/* Empty State */}
      {filteredSuppliers.length === 0 && (
        <EmptyState
          icon={Building2}
          title="No se encontraron proveedores"
          description="Intenta ajustar la búsqueda o crear un nuevo proveedor"
          actionLabel="Nuevo Proveedor"
          actionIcon={Plus}
          onAction={() => setIsWizardOpen(true)}
        />
      )}

      {/* Add Supplier Modal */}
      <AddModal
        isOpen={showAddModal}
        onClose={() => setShowAddModal(false)}
        title={t('suppliers:actions.new_supplier', 'Nuevo Proveedor')}
        subtitle={t('suppliers:actions.create_new_supplier', 'Crear nuevo proveedor')}
        size="lg"
        sections={[
          {
            title: t('suppliers:sections.contact_info'),
            icon: Users,
            fields: [
              {
                label: t('common:fields.name'),
                name: 'name',
                type: 'text',
                required: true,
                placeholder: t('suppliers:placeholders.name')
              },
              {
                label: t('common:fields.contact_person'),
                name: 'contact_person',
                type: 'text',
                placeholder: t('suppliers:placeholders.contact_person')
              },
              {
                label: t('common:fields.email'),
                name: 'email',
                type: 'email',
                placeholder: t('common:fields.email_placeholder')
              },
              {
                label: t('common:fields.phone'),
                name: 'phone',
                type: 'tel',
                placeholder: t('common:fields.phone_placeholder')
              },
              {
                label: t('suppliers:labels.mobile'),
                name: 'mobile',
                type: 'tel',
                placeholder: t('suppliers:placeholders.mobile')
              },
              {
                label: t('suppliers:labels.website'),
                name: 'website',
                type: 'text',
                placeholder: t('suppliers:placeholders.website')
              }
            ]
          },
          {
            title: t('suppliers:sections.address_info'),
            icon: Building2,
            fields: [
              {
                label: t('suppliers:labels.address_line1'),
                name: 'address_line1',
                type: 'text',
                placeholder: t('suppliers:placeholders.address_line1')
              },
              {
                label: t('suppliers:labels.address_line2'),
                name: 'address_line2',
                type: 'text',
                placeholder: t('suppliers:placeholders.address_line2')
              },
              {
                label: t('common:fields.city'),
                name: 'city',
                type: 'text',
                placeholder: t('common:fields.city')
              },
              {
                label: t('suppliers:labels.state_province'),
                name: 'state_province',
                type: 'text',
                placeholder: t('suppliers:placeholders.state_province')
              },
              {
                label: t('suppliers:labels.postal_code'),
                name: 'postal_code',
                type: 'text',
                placeholder: t('suppliers:placeholders.postal_code')
              },
              {
                label: t('common:fields.country'),
                name: 'country',
                type: 'text',
                placeholder: t('common:fields.country')
              }
            ]
          },
          {
            title: t('suppliers:sections.commercial_info'),
            icon: Euro,
            fields: [
              {
                label: t('suppliers:labels.supplier_code'),
                name: 'supplier_code',
                type: 'text',
                placeholder: t('suppliers:placeholders.supplier_code')
              },
              {
                label: t('suppliers:labels.supplier_type'),
                name: 'supplier_type',
                type: 'select',
                required: true,
                defaultValue: SupplierType.INGREDIENTS,
                options: Object.values(SupplierType).map(value => ({
                  value,
                  label: t(`suppliers:types.${value.toLowerCase()}`)
                }))
              },
              {
                label: t('suppliers:labels.payment_terms'),
                name: 'payment_terms',
                type: 'select',
                defaultValue: PaymentTerms.NET_30,
                options: Object.values(PaymentTerms).map(value => ({
                  value,
                  label: t(`suppliers:payment_terms.${value.toLowerCase()}`)
                }))
              },
              {
                label: t('suppliers:labels.currency'),
                name: 'currency',
                type: 'select',
                defaultValue: 'EUR',
                options: [
                  { value: 'EUR', label: t('suppliers:currencies.EUR') },
                  { value: 'USD', label: t('suppliers:currencies.USD') },
                  { value: 'GBP', label: t('suppliers:currencies.GBP') }
                ]
              },
              {
                label: t('suppliers:labels.lead_time'),
                name: 'standard_lead_time',
                type: 'number',
                defaultValue: 3,
                placeholder: '3'
              },
              {
                label: t('suppliers:labels.minimum_order'),
                name: 'minimum_order_amount',
                type: 'currency',
                defaultValue: 0,
                placeholder: '0.00'
              },
              {
                label: t('suppliers:labels.credit_limit'),
                name: 'credit_limit',
                type: 'currency',
                defaultValue: 0,
                placeholder: '0.00'
              }
            ]
          },
          {
            title: t('suppliers:sections.additional_info'),
            icon: Building2,
            fields: [
              {
                label: t('suppliers:labels.tax_id'),
                name: 'tax_id',
                type: 'text',
                placeholder: t('suppliers:placeholders.tax_id')
              },
              {
                label: t('suppliers:labels.registration_number'),
                name: 'registration_number',
                type: 'text',
                placeholder: t('suppliers:placeholders.registration_number')
              },
              {
                label: t('suppliers:labels.delivery_area'),
                name: 'delivery_area',
                type: 'text',
                placeholder: t('suppliers:placeholders.delivery_area')
              }
            ]
          }
        ]}
        onSave={async (formData) => {
          await createSupplierMutation.mutateAsync({
            tenantId,
            supplierData: {
              name: formData.name,
              supplier_code: formData.supplier_code || null,
              tax_id: formData.tax_id || null,
              registration_number: formData.registration_number || null,
              supplier_type: formData.supplier_type || SupplierType.INGREDIENTS,
              contact_person: formData.contact_person || null,
              email: formData.email || null,
              phone: formData.phone || null,
              mobile: formData.mobile || null,
              website: formData.website || null,
              address_line1: formData.address_line1 || null,
              address_line2: formData.address_line2 || null,
              city: formData.city || null,
              state_province: formData.state_province || null,
              postal_code: formData.postal_code || null,
              country: formData.country || null,
              payment_terms: formData.payment_terms || PaymentTerms.NET_30,
              credit_limit: formData.credit_limit || null,
              currency: formData.currency || 'EUR',
              standard_lead_time: formData.standard_lead_time || 3,
              minimum_order_amount: formData.minimum_order_amount || null,
              delivery_area: formData.delivery_area || null,
              notes: formData.notes || null
            }
          });
        }}
      />

      {/* Supplier Details Modal */}
      {showForm && selectedSupplier && (() => {
        const sections = [
          {
            title: t('suppliers:sections.contact_info'),
            icon: Users,
            fields: [
              {
                label: t('common:fields.name'),
                value: selectedSupplier.name || '',
                type: 'text' as const,
                highlight: true,
                editable: true,
                required: true,
                placeholder: t('suppliers:placeholders.name')
              },
              {
                label: t('common:fields.contact_person'),
                value: selectedSupplier.contact_person || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.contact_person')
              },
              {
                label: t('common:fields.email'),
                value: selectedSupplier.email || '',
                type: 'email' as const,
                editable: true,
                placeholder: t('common:fields.email_placeholder')
              },
              {
                label: t('common:fields.phone'),
                value: selectedSupplier.phone || '',
                type: 'tel' as const,
                editable: true,
                placeholder: t('common:fields.phone_placeholder')
              },
              {
                label: t('suppliers:labels.mobile'),
                value: selectedSupplier.mobile || '',
                type: 'tel' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.mobile')
              },
              {
                label: t('suppliers:labels.website'),
                value: selectedSupplier.website || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.website')
              }
            ]
          },
          {
            title: t('suppliers:sections.address_info'),
            icon: Building2,
            fields: [
              {
                label: t('suppliers:labels.address_line1'),
                value: selectedSupplier.address_line1 || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.address_line1')
              },
              {
                label: t('suppliers:labels.address_line2'),
                value: selectedSupplier.address_line2 || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.address_line2')
              },
              {
                label: t('common:fields.city'),
                value: selectedSupplier.city || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('common:fields.city')
              },
              {
                label: t('suppliers:labels.state_province'),
                value: selectedSupplier.state_province || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.state_province')
              },
              {
                label: t('suppliers:labels.postal_code'),
                value: selectedSupplier.postal_code || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.postal_code')
              },
              {
                label: t('common:fields.country'),
                value: selectedSupplier.country || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('common:fields.country')
              }
            ]
          },
          {
            title: t('suppliers:sections.commercial_info'),
            icon: Euro,
            fields: [
              {
                label: t('suppliers:labels.supplier_code'),
                value: selectedSupplier.supplier_code || '',
                type: 'text' as const,
                highlight: true,
                editable: true,
                placeholder: t('suppliers:placeholders.supplier_code')
              },
              {
                label: t('suppliers:labels.supplier_type'),
                value: modalMode === 'view'
                  ? getSupplierTypeText(selectedSupplier.supplier_type || SupplierType.INGREDIENTS)
                  : selectedSupplier.supplier_type || SupplierType.INGREDIENTS,
                type: modalMode === 'view' ? 'text' as const : 'select' as const,
                editable: true,
                required: true,
                options: modalMode === 'edit' ? Object.values(SupplierType).map(value => ({
                  value,
                  label: t(`suppliers:types.${value.toLowerCase()}`)
                })) : undefined
              },
              {
                label: t('suppliers:labels.payment_terms'),
                value: modalMode === 'view'
                  ? getPaymentTermsText(selectedSupplier.payment_terms || PaymentTerms.NET_30)
                  : selectedSupplier.payment_terms || PaymentTerms.NET_30,
                type: modalMode === 'view' ? 'text' as const : 'select' as const,
                editable: true,
                options: modalMode === 'edit' ? Object.values(PaymentTerms).map(value => ({
                  value,
                  label: t(`suppliers:payment_terms.${value.toLowerCase()}`)
                })) : undefined
              },
              {
                label: t('suppliers:labels.currency'),
                value: modalMode === 'view'
                  ? t(`suppliers:currencies.${selectedSupplier.currency || 'EUR'}`)
                  : selectedSupplier.currency || 'EUR',
                type: modalMode === 'view' ? 'text' as const : 'select' as const,
                editable: true,
                options: modalMode === 'edit' ? [
                  { value: 'EUR', label: t('suppliers:currencies.EUR') },
                  { value: 'USD', label: t('suppliers:currencies.USD') },
                  { value: 'GBP', label: t('suppliers:currencies.GBP') }
                ] : undefined
              },
              {
                label: t('suppliers:labels.lead_time'),
                value: selectedSupplier.standard_lead_time || 3,
                type: 'number' as const,
                editable: true,
                placeholder: '3'
              },
              {
                label: t('suppliers:labels.minimum_order'),
                value: selectedSupplier.minimum_order_amount || 0,
                type: 'currency' as const,
                editable: true,
                placeholder: '0.00'
              },
              {
                label: t('suppliers:labels.credit_limit'),
                value: selectedSupplier.credit_limit || 0,
                type: 'currency' as const,
                editable: true,
                placeholder: '0.00'
              }
            ]
          },
          {
            title: t('suppliers:sections.additional_info'),
            icon: Building2,
            fields: [
              {
                label: t('suppliers:labels.tax_id'),
                value: selectedSupplier.tax_id || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.tax_id')
              },
              {
                label: t('suppliers:labels.registration_number'),
                value: selectedSupplier.registration_number || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.registration_number')
              },
              {
                label: t('suppliers:labels.delivery_area'),
                value: selectedSupplier.delivery_area || '',
                type: 'text' as const,
                editable: true,
                placeholder: t('suppliers:placeholders.delivery_area')
              }
            ]
          },
          // Performance section
          {
            title: t('suppliers:sections.performance'),
            icon: CheckCircle,
            fields: [
              {
                label: t('suppliers:labels.created_date'),
                value: selectedSupplier.created_at,
                type: 'datetime' as const,
                highlight: true
              },
              {
                label: t('suppliers:labels.updated_date'),
                value: selectedSupplier.updated_at,
                type: 'datetime' as const
              }
            ]
          },
          ...(selectedSupplier.notes ? [{
            title: t('suppliers:sections.notes'),
            fields: [
              {
                label: t('suppliers:labels.notes'),
                value: selectedSupplier.notes,
                type: 'list' as const,
                span: 2 as const,
                editable: true,
                placeholder: t('suppliers:placeholders.notes')
              }
            ]
          }] : []),
        ];

        return (
          <EditViewModal
          isOpen={showForm}
          onClose={() => {
            setShowForm(false);
            setSelectedSupplier(null);
            setModalMode('view');
          }}
          mode={modalMode}
          onModeChange={setModalMode}
          title={selectedSupplier.name || 'Proveedor'}
          subtitle={`Proveedor ${selectedSupplier.supplier_code || ''}`}
          statusIndicator={getSupplierStatusConfig(selectedSupplier.status)}
          size="lg"
          sections={sections}
          showDefaultActions={true}
          onSave={async () => {
            try {
              // Update existing supplier
              await updateSupplierMutation.mutateAsync({
                tenantId,
                supplierId: selectedSupplier.id,
                updateData: {
                  name: selectedSupplier.name,
                  supplier_code: selectedSupplier.supplier_code || null,
                  tax_id: selectedSupplier.tax_id || null,
                  registration_number: selectedSupplier.registration_number || null,
                  supplier_type: selectedSupplier.supplier_type,
                  contact_person: selectedSupplier.contact_person || null,
                  email: selectedSupplier.email || null,
                  phone: selectedSupplier.phone || null,
                  mobile: selectedSupplier.mobile || null,
                  website: selectedSupplier.website || null,
                  address_line1: selectedSupplier.address_line1 || null,
                  address_line2: selectedSupplier.address_line2 || null,
                  city: selectedSupplier.city || null,
                  state_province: selectedSupplier.state_province || null,
                  postal_code: selectedSupplier.postal_code || null,
                  country: selectedSupplier.country || null,
                  payment_terms: selectedSupplier.payment_terms,
                  credit_limit: selectedSupplier.credit_limit || null,
                  currency: selectedSupplier.currency || 'EUR',
                  standard_lead_time: selectedSupplier.standard_lead_time || 3,
                  minimum_order_amount: selectedSupplier.minimum_order_amount || null,
                  delivery_area: selectedSupplier.delivery_area || null,
                  notes: selectedSupplier.notes || null
                }
              });
              // Close modal on success
              setShowForm(false);
              setSelectedSupplier(null);
              setModalMode('view');
            } catch (error) {
              console.error('Error saving supplier:', error);
              // Error will be handled by the modal's error display
              throw error;
            }
          }}
          onFieldChange={(sectionIndex, fieldIndex, value) => {
            // Update the selectedSupplier state when fields change
            const newSupplier = { ...selectedSupplier };
            const section = sections[sectionIndex];
            const field = section.fields[fieldIndex];

            // Map field labels to supplier properties
            const fieldMapping: { [key: string]: string } = {
              [t('common:fields.name')]: 'name',
              [t('common:fields.contact_person')]: 'contact_person',
              [t('common:fields.email')]: 'email',
              [t('common:fields.phone')]: 'phone',
              [t('suppliers:labels.mobile')]: 'mobile',
              [t('suppliers:labels.website')]: 'website',
              [t('suppliers:labels.address_line1')]: 'address_line1',
              [t('suppliers:labels.address_line2')]: 'address_line2',
              [t('common:fields.city')]: 'city',
              [t('suppliers:labels.state_province')]: 'state_province',
              [t('suppliers:labels.postal_code')]: 'postal_code',
              [t('common:fields.country')]: 'country',
              [t('suppliers:labels.supplier_code')]: 'supplier_code',
              [t('suppliers:labels.supplier_type')]: 'supplier_type',
              [t('suppliers:labels.payment_terms')]: 'payment_terms',
              [t('suppliers:labels.currency')]: 'currency',
              [t('suppliers:labels.lead_time')]: 'standard_lead_time',
              [t('suppliers:labels.minimum_order')]: 'minimum_order_amount',
              [t('suppliers:labels.credit_limit')]: 'credit_limit',
              [t('suppliers:labels.tax_id')]: 'tax_id',
              [t('suppliers:labels.registration_number')]: 'registration_number',
              [t('suppliers:labels.delivery_area')]: 'delivery_area',
              [t('suppliers:labels.notes')]: 'notes'
            };

            const propertyName = fieldMapping[field.label];
            if (propertyName) {
              newSupplier[propertyName] = value;
              setSelectedSupplier(newSupplier);
            }
          }}
        />
        );
      })()}

      {/* Delete Supplier Modal */}
      <DeleteSupplierModal
        isOpen={showDeleteModal}
        onClose={() => {
          setShowDeleteModal(false);
          setSelectedSupplier(null);
        }}
        supplier={selectedSupplier}
        onSoftDelete={handleSoftDelete}
        onHardDelete={handleHardDelete}
        isLoading={softDeleteMutation.isPending || hardDeleteMutation.isPending}
      />

      {/* Approval Confirmation Modal */}
      <DialogModal
        isOpen={showApprovalModal}
        onClose={() => {
          setShowApprovalModal(false);
          setSupplierToApprove(null);
        }}
        type="confirm"
        title={t('suppliers:confirm.approve_title', 'Aprobar Proveedor')}
        message={
          supplierToApprove ? (
            <div className="space-y-3">
              <p className="text-[var(--text-primary)]">
                {t('suppliers:confirm.approve_message', '¿Estás seguro de que deseas aprobar este proveedor?')}
              </p>
              <div className="bg-[var(--bg-secondary)] p-4 rounded-lg border border-[var(--border-primary)]">
                <div className="space-y-2">
                  <div className="flex items-center gap-2">
                    <Building2 className="w-4 h-4 text-[var(--color-primary)]" />
                    <span className="font-semibold text-[var(--text-primary)]">{supplierToApprove.name}</span>
                  </div>
                  {supplierToApprove.supplier_code && (
                    <p className="text-sm text-[var(--text-secondary)]">
                      {t('suppliers:labels.supplier_code')}: {supplierToApprove.supplier_code}
                    </p>
                  )}
                  {supplierToApprove.email && (
                    <p className="text-sm text-[var(--text-secondary)]">
                      {t('common:fields.email')}: {supplierToApprove.email}
                    </p>
                  )}
                </div>
              </div>
              <p className="text-sm text-[var(--text-secondary)]">
                {t('suppliers:confirm.approve_description', 'Una vez aprobado, el proveedor estará activo y podrá ser utilizado para realizar pedidos.')}
              </p>
            </div>
          ) : null
        }
        confirmLabel={t('suppliers:actions.approve', 'Aprobar')}
        cancelLabel={t('common:modals.actions.cancel', 'Cancelar')}
        onConfirm={async () => {
          if (supplierToApprove) {
            try {
              await approveSupplierMutation.mutateAsync({
                tenantId,
                supplierId: supplierToApprove.id,
                approvalData: { action: 'approve' }
              });
            } catch (error) {
              console.error('Error approving supplier:', error);
            }
          }
        }}
        loading={approveSupplierMutation.isPending}
      />

      {/* Price List View Modal */}
      {priceListSupplier && (
        <SupplierPriceListViewModal
          isOpen={showPriceListView}
          onClose={() => {
            setShowPriceListView(false);
            setPriceListSupplier(null);
          }}
          supplier={priceListSupplier}
          priceLists={priceListsData || []}
          loading={priceListsLoading}
          tenantId={tenantId}
          onAddPrice={() => setShowAddPrice(true)}
          onEditPrice={async (priceId, updateData) => {
            await updatePriceListMutation.mutateAsync({
              tenantId,
              supplierId: priceListSupplier.id,
              priceListId: priceId,
              priceListData: updateData
            });
          }}
          onDeletePrice={async (priceId) => {
            await deletePriceListMutation.mutateAsync({
              tenantId,
              supplierId: priceListSupplier.id,
              priceListId: priceId
            });
          }}
          waitForRefetch={true}
          isRefetching={isRefetchingPriceLists}
          onSaveComplete={handlePriceListSaveComplete}
        />
      )}

      {/* Add Price Modal */}
      {priceListSupplier && (
        <PriceListModal
          isOpen={showAddPrice}
          onClose={() => setShowAddPrice(false)}
          onSave={handleAddPriceSubmit}
          mode="create"
          loading={createPriceListMutation.isPending}
          excludeProductIds={priceListsData?.map(p => p.inventory_product_id) || []}
          waitForRefetch={true}
          isRefetching={isRefetchingPriceLists}
          onSaveComplete={handlePriceListSaveComplete}
        />
      )}

      {/* Unified Add Wizard */}
      <UnifiedAddWizard
        isOpen={isWizardOpen}
        onClose={() => setIsWizardOpen(false)}
        onComplete={handleWizardComplete}
        initialItemType="supplier"
      />
    </div>
  );
};

export default SuppliersPage;
