import React, { useState } from 'react';
import { Store, MapPin, Clock, Phone, Mail, Globe, Save, X, Edit3, Zap, Plus, Settings, Trash2, Wifi, WifiOff, AlertCircle, CheckCircle, Loader, Eye, EyeOff, Info } from 'lucide-react';
import { Button, Card, Input, Select, Modal, Badge, Tabs } from '../../../../components/ui';
import { PageHeader } from '../../../../components/layout';
import { showToast } from '../../../../utils/toast';
import { usePOSConfigurationData, usePOSConfigurationManager } from '../../../../api/hooks/pos';
import { POSConfiguration, POSProviderConfig } from '../../../../api/types/pos';
import { posService } from '../../../../api/services/pos';
import { useTenant, useUpdateTenant } from '../../../../api/hooks/tenant';
import { useCurrentTenant, useTenantActions } from '../../../../stores/tenant.store';

interface BakeryConfig {
  // General Info
  name: string;
  description: string;
  email: string;
  phone: string;
  website: string;
  // Location
  address: string;
  city: string;
  postalCode: string;
  country: string;
  // Business
  taxId: string;
  currency: string;
  timezone: string;
  language: string;
}

interface BusinessHours {
  [key: string]: {
    open: string;
    close: string;
    closed: boolean;
  };
}


const BakeryConfigPage: React.FC = () => {
  
  const currentTenant = useCurrentTenant();
  const { loadUserTenants, setCurrentTenant } = useTenantActions();
  const tenantId = currentTenant?.id || '';
  
  // Use the current tenant from the store instead of making additional API calls
  // to avoid the 422 validation error on the tenant GET endpoint
  const tenant = currentTenant;
  const tenantLoading = !currentTenant;
  const tenantError = null;
  
  const updateTenantMutation = useUpdateTenant();
  
  // POS Configuration hooks
  const posData = usePOSConfigurationData(tenantId);
  const posManager = usePOSConfigurationManager(tenantId);
  
  const [activeTab, setActiveTab] = useState<'general' | 'location' | 'business' | 'hours' | 'pos'>('general');
  const [isLoading, setIsLoading] = useState(false);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

  // POS Configuration State
  const [showAddPosModal, setShowAddPosModal] = useState(false);
  const [showEditPosModal, setShowEditPosModal] = useState(false);
  const [selectedPosConfig, setSelectedPosConfig] = useState<POSConfiguration | null>(null);
  const [posFormData, setPosFormData] = useState<any>({});
  const [testingConnection, setTestingConnection] = useState<string | null>(null);
  const [showCredentials, setShowCredentials] = useState<Record<string, boolean>>({});
  
  const [config, setConfig] = useState<BakeryConfig>({
    name: '',
    description: '',
    email: '',
    phone: '',
    website: '',
    address: '',
    city: '',
    postalCode: '',
    country: '',
    taxId: '',
    currency: 'EUR',
    timezone: 'Europe/Madrid',
    language: 'es'
  });
  
  // Load user tenants on component mount to ensure fresh data
  React.useEffect(() => {
    loadUserTenants();
  }, [loadUserTenants]);


  // Update config when tenant data is loaded
  React.useEffect(() => {
    if (tenant) {
      setConfig({
        name: tenant.name || '',
        description: tenant.description || '',
        email: tenant.email || '',
        phone: tenant.phone || '',
        website: tenant.website || '',
        address: tenant.address || '',
        city: tenant.city || '',
        postalCode: tenant.postal_code || '',
        country: tenant.country || '',
        taxId: '',  // Not supported by backend yet
        currency: 'EUR',  // Default value
        timezone: 'Europe/Madrid',  // Default value
        language: 'es'  // Default value
      });
      setHasUnsavedChanges(false); // Reset unsaved changes when loading fresh data
    }
  }, [tenant]);

  const [businessHours, setBusinessHours] = useState<BusinessHours>({
    monday: { open: '07:00', close: '20:00', closed: false },
    tuesday: { open: '07:00', close: '20:00', closed: false },
    wednesday: { open: '07:00', close: '20:00', closed: false },
    thursday: { open: '07:00', close: '20:00', closed: false },
    friday: { open: '07:00', close: '20:00', closed: false },
    saturday: { open: '08:00', close: '14:00', closed: false },
    sunday: { open: '09:00', close: '13:00', closed: false }
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  // POS Providers Configuration
  const supportedProviders: POSProviderConfig[] = [
    {
      id: 'toast',
      name: 'Toast POS',
      logo: '🍞',
      description: 'Sistema POS líder para restaurantes y panaderías. Muy popular en España.',
      features: ['Gestión de pedidos', 'Sincronización de inventario', 'Pagos integrados', 'Reportes en tiempo real'],
      required_fields: [
        { field: 'api_key', label: 'API Key', type: 'password', required: true, help_text: 'Obten tu API key desde Toast Dashboard > Settings > Integrations' },
        { field: 'restaurant_guid', label: 'Restaurant GUID', type: 'text', required: true, help_text: 'ID único del restaurante en Toast' },
        { field: 'location_id', label: 'Location ID', type: 'text', required: true, help_text: 'ID de la ubicación específica' },
        { field: 'environment', label: 'Entorno', type: 'select', required: true, options: [
          { value: 'sandbox', label: 'Sandbox (Pruebas)' },
          { value: 'production', label: 'Producción' }
        ]},
      ],
    },
    {
      id: 'square',
      name: 'Square POS',
      logo: '⬜',
      description: 'Solución POS completa con tarifas transparentes. Ampliamente utilizada por pequeñas empresas.',
      features: ['Procesamiento de pagos', 'Gestión de inventario', 'Análisis de ventas', 'Integración con e-commerce'],
      required_fields: [
        { field: 'application_id', label: 'Application ID', type: 'text', required: true, help_text: 'ID de aplicación de Square Developer Dashboard' },
        { field: 'access_token', label: 'Access Token', type: 'password', required: true, help_text: 'Token de acceso para la API de Square' },
        { field: 'location_id', label: 'Location ID', type: 'text', required: true, help_text: 'ID de la ubicación de Square' },
        { field: 'webhook_signature_key', label: 'Webhook Signature Key', type: 'password', required: false, help_text: 'Clave para verificar webhooks (opcional)' },
        { field: 'environment', label: 'Entorno', type: 'select', required: true, options: [
          { value: 'sandbox', label: 'Sandbox (Pruebas)' },
          { value: 'production', label: 'Producción' }
        ]},
      ],
    },
    {
      id: 'lightspeed',
      name: 'Lightspeed POS',
      logo: '⚡',
      description: 'Sistema POS empresarial con API abierta e integración con múltiples herramientas.',
      features: ['API REST completa', 'Gestión multi-ubicación', 'Reportes avanzados', 'Integración con contabilidad'],
      required_fields: [
        { field: 'api_key', label: 'API Key', type: 'password', required: true, help_text: 'Clave API de Lightspeed Retail' },
        { field: 'api_secret', label: 'API Secret', type: 'password', required: true, help_text: 'Secreto API de Lightspeed Retail' },
        { field: 'account_id', label: 'Account ID', type: 'text', required: true, help_text: 'ID de cuenta de Lightspeed' },
        { field: 'shop_id', label: 'Shop ID', type: 'text', required: true, help_text: 'ID de la tienda específica' },
        { field: 'server_region', label: 'Región del Servidor', type: 'select', required: true, options: [
          { value: 'eu', label: 'Europa' },
          { value: 'us', label: 'Estados Unidos' },
          { value: 'ca', label: 'Canadá' }
        ]},
      ],
    },
  ];

  const tabs = [
    { id: 'general', label: '🏪 General' },
    { id: 'location', label: '📍 Ubicación' },
    { id: 'business', label: '🏢 Empresa' },
    { id: 'hours', label: '🕐 Horarios' },
    { id: 'pos', label: '⚡ Sistemas POS' }
  ];

  const daysOfWeek = [
    { key: 'monday', label: 'Lunes' },
    { key: 'tuesday', label: 'Martes' },
    { key: 'wednesday', label: 'Miércoles' },
    { key: 'thursday', label: 'Jueves' },
    { key: 'friday', label: 'Viernes' },
    { key: 'saturday', label: 'Sábado' },
    { key: 'sunday', label: 'Domingo' }
  ];

  const currencyOptions = [
    { value: 'EUR', label: 'EUR (€)' },
    { value: 'USD', label: 'USD ($)' },
    { value: 'GBP', label: 'GBP (£)' }
  ];

  const timezoneOptions = [
    { value: 'Europe/Madrid', label: 'Madrid (CET/CEST)' },
    { value: 'Atlantic/Canary', label: 'Canarias (WET/WEST)' },
    { value: 'Europe/London', label: 'Londres (GMT/BST)' }
  ];

  const languageOptions = [
    { value: 'es', label: 'Español' },
    { value: 'ca', label: 'Català' },
    { value: 'en', label: 'English' }
  ];

  // Load POS configurations function for refetching after updates
  const loadPosConfigurations = () => {
    // This will trigger a refetch of POS configurations
    // Note: posManager may not have refetch method available
    console.log('POS configurations updated, consider implementing refetch if needed');
  };

  const validateConfig = (): boolean => {
    const newErrors: Record<string, string> = {};
    
    if (!config.name.trim()) {
      newErrors.name = 'El nombre es requerido';
    }
    
    if (!config.email.trim()) {
      newErrors.email = 'El email es requerido';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(config.email)) {
      newErrors.email = 'Email inválido';
    }
    
    if (!config.address.trim()) {
      newErrors.address = 'La dirección es requerida';
    }
    
    if (!config.city.trim()) {
      newErrors.city = 'La ciudad es requerida';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSaveConfig = async () => {
    if (!validateConfig() || !tenantId) return;

    setIsLoading(true);

    try {
      const updateData = {
        name: config.name,
        description: config.description,
        email: config.email,
        phone: config.phone,
        website: config.website,
        address: config.address,
        city: config.city,
        postal_code: config.postalCode,
        country: config.country
      };

      const updatedTenant = await updateTenantMutation.mutateAsync({
        tenantId,
        updateData
      });

      // Update the tenant store with the new data
      if (updatedTenant) {
        setCurrentTenant(updatedTenant);
        // Force reload tenant list to ensure cache consistency
        await loadUserTenants();

        // Update localStorage to persist the changes
        const tenantStorage = localStorage.getItem('tenant-storage');
        if (tenantStorage) {
          const parsedStorage = JSON.parse(tenantStorage);
          if (parsedStorage.state && parsedStorage.state.currentTenant) {
            parsedStorage.state.currentTenant = updatedTenant;
            localStorage.setItem('tenant-storage', JSON.stringify(parsedStorage));
          }
        }
      }

      setHasUnsavedChanges(false);
      showToast.success('Configuración actualizada correctamente');
    } catch (error) {
      showToast.error(`Error al actualizar: ${error instanceof Error ? error.message : 'Error desconocido'}`);
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (field: keyof BakeryConfig) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setConfig(prev => ({ ...prev, [field]: e.target.value }));
    setHasUnsavedChanges(true);
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const handleSelectChange = (field: keyof BakeryConfig) => (value: string) => {
    setConfig(prev => ({ ...prev, [field]: value }));
    setHasUnsavedChanges(true);
  };

  const handleHoursChange = (day: string, field: 'open' | 'close' | 'closed', value: string | boolean) => {
    setBusinessHours(prev => ({
      ...prev,
      [day]: {
        ...prev[day],
        [field]: value
      }
    }));
    setHasUnsavedChanges(true);
  };

  // POS Configuration Handlers
  const handleAddPosConfiguration = () => {
    setPosFormData({
      provider: '',
      config_name: '',
      credentials: {},
      sync_settings: {
        auto_sync_enabled: true,
        sync_interval_minutes: 5,
        sync_sales: true,
        sync_inventory: true,
        sync_customers: true,
      },
    });
    setShowAddPosModal(true);
  };

  const handleEditPosConfiguration = (config: POSConfiguration) => {
    setSelectedPosConfig(config);
    setPosFormData({
      provider: (config as any).provider || (config as any).pos_system || '',
      config_name: (config as any).config_name || (config as any).provider_name || '',
      credentials: (config as any).credentials || {},
      sync_settings: (config as any).sync_settings || {
        auto_sync_enabled: true,
        sync_interval_minutes: 5,
        sync_sales: true,
        sync_inventory: true,
        sync_customers: true,
      },
    });
    setShowEditPosModal(true);
  };

  const handleSavePosConfiguration = async () => {
    try {
      const provider = supportedProviders.find(p => p.id === posFormData.provider);
      if (!provider) return;

      // Validate required fields
      const missingFields = provider.required_fields
        .filter(field => field.required && !posFormData.credentials[field.field])
        .map(field => field.label);

      if (missingFields.length > 0) {
        showToast.error(`Campos requeridos: ${missingFields.join(', ')}`);
        return;
      }

      if (selectedPosConfig) {
        // Update existing
        await posService.updatePOSConfiguration({
          tenant_id: tenantId,
          config_id: selectedPosConfig.id,
          ...posFormData,
        });
        showToast.success('Configuración actualizada correctamente');
        setShowEditPosModal(false);
        loadPosConfigurations();
      } else {
        // Create new
        await posService.createPOSConfiguration({
          tenant_id: tenantId,
          ...posFormData,
        });
        showToast.success('Configuración creada correctamente');
        setShowAddPosModal(false);
        loadPosConfigurations();
      }
    } catch (error) {
      showToast.error('Error al guardar la configuración');
    }
  };

  const handleTestPosConnection = async (configId: string) => {
    try {
      setTestingConnection(configId);
      const response = await posService.testPOSConnection({
        tenant_id: tenantId,
        config_id: configId,
      });
      
      if (response.success) {
        showToast.success('Conexión exitosa');
      } else {
        showToast.error(`Error en la conexión: ${response.message || 'Error desconocido'}`);
      }
    } catch (error) {
      showToast.error('Error al probar la conexión');
    } finally {
      setTestingConnection(null);
    }
  };

  const handleDeletePosConfiguration = async (configId: string) => {
    if (!window.confirm('¿Estás seguro de que deseas eliminar esta configuración?')) {
      return;
    }

    try {
      await posService.deletePOSConfiguration({
        tenant_id: tenantId,
        config_id: configId,
      });
      showToast.success('Configuración eliminada correctamente');
      loadPosConfigurations();
    } catch (error) {
      showToast.error('Error al eliminar la configuración');
    }
  };

  // POS Configuration Form Renderer
  const renderPosConfigurationForm = () => {
    const selectedProvider = supportedProviders.find(p => p.id === posFormData.provider);

    return (
      <div className="space-y-6">
        <div>
          <label className="block text-sm font-medium mb-2">Sistema POS</label>
          <Select
            value={posFormData.provider}
            onChange={(value) => setPosFormData((prev: any) => ({ ...prev, provider: value as string, credentials: {} }))}
            placeholder="Selecciona un sistema POS"
            options={supportedProviders.map(provider => ({
              value: provider.id,
              label: `${provider.logo} ${provider.name}`,
              description: provider.description
            }))}
          />
        </div>

        {selectedProvider && (
          <>
            <div className="p-4 bg-blue-50 rounded-lg">
              <h4 className="font-medium text-blue-900 mb-2">{selectedProvider.name}</h4>
              <p className="text-sm text-blue-700 mb-3">{selectedProvider.description}</p>
              <div className="flex flex-wrap gap-2">
                {selectedProvider.features.map((feature, idx) => (
                  <Badge key={idx} variant="secondary" className="text-xs">
                    {feature}
                  </Badge>
                ))}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium mb-2">Nombre de la Configuración</label>
              <Input
                value={posFormData.config_name}
                onChange={(e) => setPosFormData((prev: any) => ({ ...prev, config_name: e.target.value }))}
                placeholder={`Mi ${selectedProvider.name} ${new Date().getFullYear()}`}
              />
            </div>

            <div className="space-y-4">
              <h4 className="font-medium text-sm">Credenciales de API</h4>
              {selectedProvider.required_fields.map(field => (
                <div key={field.field}>
                  <div className="flex items-center justify-between mb-2">
                    <label className="block text-sm font-medium">
                      {field.label} {field.required && <span className="text-red-500">*</span>}
                    </label>
                    {field.type === 'password' && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => setShowCredentials(prev => ({
                          ...prev,
                          [field.field]: !prev[field.field]
                        }))}
                      >
                        {showCredentials[field.field] ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </Button>
                    )}
                  </div>
                  
                  {field.type === 'select' ? (
                    <Select
                      value={posFormData.credentials[field.field] || ''}
                      onChange={(value) => setPosFormData(prev => ({
                        ...prev,
                        credentials: { ...prev.credentials, [field.field]: value }
                      }))}
                      placeholder={`Selecciona ${field.label.toLowerCase()}`}
                      options={field.options?.map(option => ({
                        value: option.value,
                        label: option.label
                      })) || []}
                    />
                  ) : (
                    <Input
                      type={field.type === 'password' && !showCredentials[field.field] ? 'password' : 'text'}
                      value={posFormData.credentials[field.field] || ''}
                      onChange={(e) => setPosFormData(prev => ({
                        ...prev,
                        credentials: { ...prev.credentials, [field.field]: e.target.value }
                      }))}
                      placeholder={field.placeholder}
                    />
                  )}
                  
                  {field.help_text && (
                    <p className="text-xs text-gray-500 mt-1 flex items-start">
                      <Info className="w-3 h-3 mt-0.5 mr-1 flex-shrink-0" />
                      {field.help_text}
                    </p>
                  )}
                </div>
              ))}
            </div>

            <div className="space-y-4">
              <h4 className="font-medium text-sm">Configuración de Sincronización</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={posFormData.sync_settings?.auto_sync_enabled || false}
                      onChange={(e) => setPosFormData(prev => ({
                        ...prev,
                        sync_settings: { ...prev.sync_settings, auto_sync_enabled: e.target.checked }
                      }))}
                    />
                    <span className="text-sm">Sincronización automática</span>
                  </label>
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">Intervalo (minutos)</label>
                  <Select
                    value={posFormData.sync_settings?.sync_interval_minutes?.toString() || '5'}
                    onChange={(value) => setPosFormData(prev => ({
                      ...prev,
                      sync_settings: { ...prev.sync_settings, sync_interval_minutes: parseInt(value as string) }
                    }))}
                    options={[
                      { value: '5', label: '5 minutos' },
                      { value: '15', label: '15 minutos' },
                      { value: '30', label: '30 minutos' },
                      { value: '60', label: '1 hora' }
                    ]}
                  />
                </div>
                <div>
                  <label className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={posFormData.sync_settings?.sync_sales || false}
                      onChange={(e) => setPosFormData((prev: any) => ({
                        ...prev,
                        sync_settings: { ...prev.sync_settings, sync_sales: e.target.checked }
                      }))}
                    />
                    <span className="text-sm">Sincronizar ventas</span>
                  </label>
                </div>
                <div>
                  <label className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={posFormData.sync_settings?.sync_inventory || false}
                      onChange={(e) => setPosFormData((prev: any) => ({
                        ...prev,
                        sync_settings: { ...prev.sync_settings, sync_inventory: e.target.checked }
                      }))}
                    />
                    <span className="text-sm">Sincronizar inventario</span>
                  </label>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    );
  };

  if (tenantLoading || !currentTenant) {
    return (
      <div className="p-6 space-y-6">
        <PageHeader
          title="Configuración de Panadería"
          description="Configurando datos básicos y preferencias de tu panadería"
        />
        <div className="flex items-center justify-center h-64">
          <Loader className="w-8 h-8 animate-spin" />
          <span className="ml-2">Cargando configuración...</span>
        </div>
      </div>
    );
  }

  if (tenantError) {
    return (
      <div className="p-6 space-y-6">
        <PageHeader
          title="Configuración de Panadería"
          description="Error al cargar la configuración"
        />
        <Card className="p-6">
          <div className="text-red-600">
            Error al cargar la configuración: {
              tenantError instanceof Error 
                ? tenantError.message 
                : typeof tenantError === 'string' 
                  ? tenantError 
                  : 'Error desconocido'
            }
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <PageHeader
        title="Configuración de Panadería"
        description="Configura los datos básicos y preferencias de tu panadería"
      />

      {/* Bakery Header */}
      <Card className="p-6">
        <div className="flex items-center gap-6">
          <div className="w-16 h-16 bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-dark)] rounded-lg flex items-center justify-center text-white font-bold text-xl">
            {config.name.charAt(0)}
          </div>
          <div className="flex-1">
            <h1 className="text-2xl font-bold text-text-primary mb-1">
              {config.name}
            </h1>
            <p className="text-text-secondary">{config.email}</p>
            <p className="text-text-tertiary text-sm">{config.address}, {config.city}</p>
          </div>
          <div className="flex gap-2">
            {hasUnsavedChanges && (
              <div className="flex items-center gap-2 text-sm text-yellow-600">
                <AlertCircle className="w-4 h-4" />
                Cambios sin guardar
              </div>
            )}
          </div>
        </div>
      </Card>

      {/* Configuration Tabs */}
      <div className="space-y-6">
        <Tabs
          items={tabs}
          activeTab={activeTab}
          onTabChange={setActiveTab}
          variant="underline"
          size="md"
          fullWidth={false}
        />

        <Card className="p-6">
          {activeTab === 'general' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-text-primary">Información General</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                <Input
                  label="Nombre de la Panadería"
                  value={config.name}
                  onChange={handleInputChange('name')}
                  error={errors.name}
                  disabled={isLoading}
                  placeholder="Nombre de tu panadería"
                  leftIcon={<Store className="w-4 h-4" />}
                />
                
                <Input
                  type="email"
                  label="Email de Contacto"
                  value={config.email}
                  onChange={handleInputChange('email')}
                  error={errors.email}
                  disabled={isLoading}
                  placeholder="contacto@panaderia.com"
                  leftIcon={<Mail className="w-4 h-4" />}
                />
                
                <Input
                  type="tel"
                  label="Teléfono"
                  value={config.phone}
                  onChange={handleInputChange('phone')}
                  error={errors.phone}
                  disabled={isLoading}
                  placeholder="+34 912 345 678"
                  leftIcon={<Phone className="w-4 h-4" />}
                />
                
                <Input
                  label="Sitio Web"
                  value={config.website}
                  onChange={handleInputChange('website')}
                  disabled={isLoading}
                  placeholder="https://tu-panaderia.com"
                  leftIcon={<Globe className="w-4 h-4" />}
                  className="md:col-span-2 xl:col-span-3"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-text-secondary mb-2">
                  Descripción
                </label>
                <textarea
                  value={config.description}
                  onChange={handleInputChange('description')}
                  disabled={isLoading}
                  rows={3}
                  className="w-full px-3 py-2 border border-[var(--border-primary)] rounded-lg resize-none bg-[var(--bg-primary)] text-[var(--text-primary)] disabled:bg-[var(--bg-secondary)] disabled:text-[var(--text-secondary)]"
                  placeholder="Describe tu panadería..."
                />
              </div>
            </div>
          )}

          {activeTab === 'location' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-text-primary">Ubicación</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                <Input
                  label="Dirección"
                  value={config.address}
                  onChange={handleInputChange('address')}
                  error={errors.address}
                  disabled={isLoading}
                  placeholder="Calle, número, etc."
                  leftIcon={<MapPin className="w-4 h-4" />}
                  className="md:col-span-2"
                />
                
                <Input
                  label="Ciudad"
                  value={config.city}
                  onChange={handleInputChange('city')}
                  error={errors.city}
                  disabled={isLoading}
                  placeholder="Ciudad"
                />
                
                <Input
                  label="Código Postal"
                  value={config.postalCode}
                  onChange={handleInputChange('postalCode')}
                  disabled={isLoading}
                  placeholder="28001"
                />
                
                <Input
                  label="País"
                  value={config.country}
                  onChange={handleInputChange('country')}
                  disabled={isLoading}
                  placeholder="España"
                />
              </div>
            </div>
          )}

          {activeTab === 'business' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-text-primary">Datos de Empresa</h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                <Input
                  label="NIF/CIF"
                  value={config.taxId}
                  onChange={handleInputChange('taxId')}
                  disabled={isLoading}
                  placeholder="B12345678"
                />
                
                <Select
                  label="Moneda"
                  options={currencyOptions}
                  value={config.currency}
                  onChange={(value) => handleSelectChange('currency')(value as string)}
                  disabled={isLoading}
                />
                
                <Select
                  label="Zona Horaria"
                  options={timezoneOptions}
                  value={config.timezone}
                  onChange={(value) => handleSelectChange('timezone')(value as string)}
                  disabled={isLoading}
                />
                
                <Select
                  label="Idioma"
                  options={languageOptions}
                  value={config.language}
                  onChange={(value) => handleSelectChange('language')(value as string)}
                  disabled={isLoading}
                />
              </div>
            </div>
          )}

          {activeTab === 'hours' && (
            <div className="space-y-6">
              <h3 className="text-lg font-semibold text-text-primary">Horarios de Apertura</h3>
              
              <div className="space-y-4">
                {daysOfWeek.map((day) => {
                  const hours = businessHours[day.key];
                  return (
                    <div key={day.key} className="grid grid-cols-12 items-center gap-4 p-4 border border-border-primary rounded-lg">
                      {/* Day Name */}
                      <div className="col-span-2">
                        <span className="text-sm font-medium text-text-secondary">{day.label}</span>
                      </div>
                      
                      {/* Closed Checkbox */}
                      <div className="col-span-2">
                        <label className="flex items-center gap-2">
                          <input
                            type="checkbox"
                            checked={hours.closed}
                            onChange={(e) => handleHoursChange(day.key, 'closed', e.target.checked)}
                            disabled={isLoading}
                            className="rounded border-border-primary"
                          />
                          <span className="text-sm text-text-secondary">Cerrado</span>
                        </label>
                      </div>

                      {/* Time Inputs */}
                      <div className="col-span-8 flex items-center gap-6">
                        {!hours.closed ? (
                          <>
                            <div className="flex-1">
                              <label className="block text-xs text-text-tertiary mb-1">Apertura</label>
                              <input
                                type="time"
                                value={hours.open}
                                onChange={(e) => handleHoursChange(day.key, 'open', e.target.value)}
                                disabled={isLoading}
                                className="w-full px-3 py-2 border border-[var(--border-primary)] rounded-lg text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] disabled:bg-[var(--bg-secondary)] disabled:text-[var(--text-secondary)]"
                              />
                            </div>
                            <div className="flex-1">
                              <label className="block text-xs text-text-tertiary mb-1">Cierre</label>
                              <input
                                type="time"
                                value={hours.close}
                                onChange={(e) => handleHoursChange(day.key, 'close', e.target.value)}
                                disabled={isLoading}
                                className="w-full px-3 py-2 border border-[var(--border-primary)] rounded-lg text-sm bg-[var(--bg-primary)] text-[var(--text-primary)] disabled:bg-[var(--bg-secondary)] disabled:text-[var(--text-secondary)]"
                              />
                            </div>
                          </>
                        ) : (
                          <div className="text-sm text-text-tertiary italic">
                            Cerrado todo el día
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {activeTab === 'pos' && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-lg font-semibold text-text-primary">Sistemas POS</h3>
                  <p className="text-sm text-text-secondary">Configura e integra tus sistemas de punto de venta</p>
                </div>
                <Button onClick={handleAddPosConfiguration} className="flex items-center">
                  <Plus className="w-4 h-4 mr-2" />
                  Agregar Sistema POS
                </Button>
              </div>

              {posData.isLoading ? (
                <div className="flex items-center justify-center h-32">
                  <Loader className="w-8 h-8 animate-spin" />
                </div>
              ) : posData.configurations.length === 0 ? (
                <Card className="p-8 text-center">
                  <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Zap className="w-8 h-8 text-gray-400" />
                  </div>
                  <h3 className="text-lg font-medium mb-2">No hay sistemas POS configurados</h3>
                  <p className="text-gray-500 mb-4">
                    Configura tu primer sistema POS para comenzar a sincronizar datos de ventas.
                  </p>
                  <Button onClick={handleAddPosConfiguration}>
                    Agregar Sistema POS
                  </Button>
                </Card>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  {posData.configurations.map(config => {
                    const provider = posData.supportedSystems.find(p => p.id === config.pos_system);
                    return (
                      <Card key={config.id} className="p-6">
                        <div className="flex items-start justify-between mb-4">
                          <div className="flex items-center">
                            <div className="text-2xl mr-3">📊</div>
                            <div>
                              <h3 className="font-medium">{config.provider_name}</h3>
                              <p className="text-sm text-gray-500">{provider?.name || config.pos_system}</p>
                            </div>
                          </div>
                          <div className="flex items-center space-x-1">
                            {config.is_connected ? (
                              <Wifi className="w-4 h-4 text-green-500" />
                            ) : (
                              <WifiOff className="w-4 h-4 text-red-500" />
                            )}
                            <Badge variant={config.is_active ? 'success' : 'error'} size="sm">
                              {config.is_active ? 'Activo' : 'Inactivo'}
                            </Badge>
                          </div>
                        </div>

                        <div className="space-y-2 mb-4">
                          <div className="flex items-center justify-between text-sm">
                            <span>Estado de conexión:</span>
                            <div className="flex items-center">
                              {config.is_active ? (
                                <>
                                  <CheckCircle className="w-4 h-4 text-green-500 mr-1" />
                                  <span className="text-green-600">Conectado</span>
                                </>
                              ) : (
                                <>
                                  <AlertCircle className="w-4 h-4 text-yellow-500 mr-1" />
                                  <span className="text-yellow-600">Desconectado</span>
                                </>
                              )}
                            </div>
                          </div>
                          
                          {config.last_sync_at && (
                            <div className="flex justify-between text-sm text-gray-500">
                              <span>Última sincronización:</span>
                              <span>{new Date(config.last_sync_at).toLocaleString('es-ES')}</span>
                            </div>
                          )}
                        </div>

                        <div className="flex space-x-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleTestPosConnection(config.id)}
                            disabled={testingConnection === config.id}
                            className="flex-1"
                          >
                            {testingConnection === config.id ? (
                              <Loader className="w-4 h-4 animate-spin" />
                            ) : (
                              <Wifi className="w-4 h-4" />
                            )}
                            Probar
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleEditPosConfiguration(config)}
                            className="flex-1"
                          >
                            <Settings className="w-4 h-4" />
                            Editar
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleDeletePosConfiguration(config.id)}
                            className="text-red-600 hover:text-red-700 border-red-200 hover:border-red-300"
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      </Card>
                    );
                  })}
                </div>
              )}
            </div>
          )}
        </Card>
        </div>


      {/* Floating Save Button */}
      {hasUnsavedChanges && (
        <div className="fixed bottom-6 right-6 z-50">
          <Card className="p-4 shadow-lg">
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-2 text-sm text-text-secondary">
                <AlertCircle className="w-4 h-4 text-yellow-500" />
                Tienes cambios sin guardar
              </div>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    // Reset to original values
                    if (tenant) {
                      setConfig({
                        name: tenant.name || '',
                        description: tenant.description || '',
                        email: tenant.email || '',
                        phone: tenant.phone || '',
                        website: tenant.website || '',
                        address: tenant.address || '',
                        city: tenant.city || '',
                        postalCode: tenant.postal_code || '',
                        country: tenant.country || '',
                        taxId: '',
                        currency: 'EUR',
                        timezone: 'Europe/Madrid',
                        language: 'es'
                      });
                    }
                    setHasUnsavedChanges(false);
                  }}
                  disabled={isLoading}
                >
                  <X className="w-4 h-4" />
                  Descartar
                </Button>
                <Button
                  variant="primary"
                  size="sm"
                  onClick={handleSaveConfig}
                  isLoading={isLoading}
                  loadingText="Guardando..."
                >
                  <Save className="w-4 h-4" />
                  Guardar
                </Button>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* POS Configuration Modals */}
      {/* Add Configuration Modal */}
      <Modal
        isOpen={showAddPosModal}
        onClose={() => setShowAddPosModal(false)}
        title="Agregar Sistema POS"
        size="lg"
      >
        <div className="space-y-4">
          {renderPosConfigurationForm()}
          <div className="flex justify-end space-x-3 pt-4 border-t">
            <Button variant="outline" onClick={() => setShowAddPosModal(false)}>
              Cancelar
            </Button>
            <Button onClick={handleSavePosConfiguration}>
              Guardar Configuración
            </Button>
          </div>
        </div>
      </Modal>

      {/* Edit Configuration Modal */}
      <Modal
        isOpen={showEditPosModal}
        onClose={() => setShowEditPosModal(false)}
        title="Editar Sistema POS"
        size="lg"
      >
        <div className="space-y-4">
          {renderPosConfigurationForm()}
          <div className="flex justify-end space-x-3 pt-4 border-t">
            <Button variant="outline" onClick={() => setShowEditPosModal(false)}>
              Cancelar
            </Button>
            <Button onClick={handleSavePosConfiguration}>
              Actualizar Configuración
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default BakeryConfigPage;
