import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Store, MapPin, Clock, Settings as SettingsIcon, Save, X, AlertCircle, Loader, Bell, Globe, Mail, Phone, Building2, CreditCard } from 'lucide-react';
import { Button, Card, Input, Select, SettingSection, SettingRow, SettingsSearch } from '../../../../components/ui';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../../../../components/ui/Tabs';
import { PageHeader } from '../../../../components/layout';
import { showToast } from '../../../../utils/toast';
import { useUpdateTenant } from '../../../../api/hooks/tenant';
import { useCurrentTenant, useTenantActions } from '../../../../stores/tenant.store';
import { useSettings, useUpdateSettings } from '../../../../api/hooks/settings';
import type {
  ProcurementSettings,
  InventorySettings,
  ProductionSettings,
  SupplierSettings,
  POSSettings,
  OrderSettings,
  NotificationSettings,
} from '../../../../api/types/settings';
import ProcurementSettingsCard from '../../database/ajustes/cards/ProcurementSettingsCard';
import InventorySettingsCard from '../../database/ajustes/cards/InventorySettingsCard';
import ProductionSettingsCard from '../../database/ajustes/cards/ProductionSettingsCard';
import SupplierSettingsCard from '../../database/ajustes/cards/SupplierSettingsCard';
import POSSettingsCard from '../../database/ajustes/cards/POSSettingsCard';
import OrderSettingsCard from '../../database/ajustes/cards/OrderSettingsCard';
import NotificationSettingsCard from '../../database/ajustes/cards/NotificationSettingsCard';

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

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

const BakerySettingsPage: React.FC = () => {
  const { t } = useTranslation('settings');

  const currentTenant = useCurrentTenant();
  const { loadUserTenants, setCurrentTenant } = useTenantActions();
  const tenantId = currentTenant?.id || '';

  const { data: settings, isLoading: settingsLoading } = useSettings(tenantId, {
    enabled: !!tenantId,
  });

  const updateTenantMutation = useUpdateTenant();
  const updateSettingsMutation = useUpdateSettings();

  const [activeTab, setActiveTab] = useState('information');
  const [isLoading, setIsLoading] = useState(false);
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  const [config, setConfig] = useState<BakeryConfig>({
    name: '',
    description: '',
    email: '',
    phone: '',
    website: '',
    address: '',
    city: '',
    postalCode: '',
    country: '',
    taxId: '',
    currency: 'EUR',
    timezone: 'Europe/Madrid',
    language: 'es'
  });

  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 }
  });

  // Operational settings state
  const [procurementSettings, setProcurementSettings] = useState<ProcurementSettings | null>(null);
  const [inventorySettings, setInventorySettings] = useState<InventorySettings | null>(null);
  const [productionSettings, setProductionSettings] = useState<ProductionSettings | null>(null);
  const [supplierSettings, setSupplierSettings] = useState<SupplierSettings | null>(null);
  const [posSettings, setPosSettings] = useState<POSSettings | null>(null);
  const [orderSettings, setOrderSettings] = useState<OrderSettings | null>(null);
  const [notificationSettings, setNotificationSettings] = useState<NotificationSettings | null>(null);

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

  // Load tenant data
  React.useEffect(() => {
    loadUserTenants();
  }, [loadUserTenants]);

  // Update config when tenant data is loaded
  React.useEffect(() => {
    if (currentTenant) {
      setConfig({
        name: currentTenant.name || '',
        description: currentTenant.description || '',
        email: currentTenant.email || '',
        phone: currentTenant.phone || '',
        website: currentTenant.website || '',
        address: currentTenant.address || '',
        city: currentTenant.city || '',
        postalCode: currentTenant.postal_code || '',
        country: currentTenant.country || '',
        taxId: '',
        currency: currentTenant.currency || 'EUR',
        timezone: currentTenant.timezone || 'Europe/Madrid',
        language: currentTenant.language || 'es'
      });
      setHasUnsavedChanges(false);
    }
  }, [currentTenant]);

  // Load settings into local state
  React.useEffect(() => {
    if (settings) {
      setProcurementSettings(settings.procurement_settings);
      setInventorySettings(settings.inventory_settings);
      setProductionSettings(settings.production_settings);
      setSupplierSettings(settings.supplier_settings);
      setPosSettings(settings.pos_settings);
      setOrderSettings(settings.order_settings);
      setNotificationSettings(settings.notification_settings);
    }
  }, [settings]);

  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: 'eu', label: 'Euskara' },
    { value: 'en', label: 'English' }
  ];

  const validateConfig = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!config.name.trim()) {
      newErrors.name = t('bakery.information.fields.name') + ' ' + t('common.required');
    }

    if (!config.email.trim()) {
      newErrors.email = t('bakery.information.fields.email') + ' ' + t('common.required');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(config.email)) {
      newErrors.email = t('common.error');
    }

    if (!config.address.trim()) {
      newErrors.address = t('bakery.information.fields.address') + ' ' + t('common.required');
    }

    if (!config.city.trim()) {
      newErrors.city = t('bakery.information.fields.city') + ' ' + t('common.required');
    }

    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,
        // Regional/Localization settings
        currency: config.currency,
        timezone: config.timezone,
        language: config.language
      };

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

      if (updatedTenant) {
        setCurrentTenant(updatedTenant);
        await loadUserTenants();

        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(t('bakery.save_success'));
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : t('common.error');
      showToast.error(`${t('bakery.save_error')}: ${errorMessage}`);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSaveOperationalSettings = async () => {
    if (!tenantId || !procurementSettings || !inventorySettings || !productionSettings ||
        !supplierSettings || !posSettings || !orderSettings || !notificationSettings) {
      return;
    }

    setIsLoading(true);

    try {
      await updateSettingsMutation.mutateAsync({
        tenantId,
        updates: {
          procurement_settings: procurementSettings,
          inventory_settings: inventorySettings,
          production_settings: productionSettings,
          supplier_settings: supplierSettings,
          pos_settings: posSettings,
          order_settings: orderSettings,
          notification_settings: notificationSettings,
        },
      });

      setHasUnsavedChanges(false);
      showToast.success(t('bakery.save_success'));
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : t('common.error');
      showToast.error(`${t('bakery.save_error')}: ${errorMessage}`);
    } 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);
  };

  const handleOperationalSettingsChange = () => {
    setHasUnsavedChanges(true);
  };

  const handleDiscard = () => {
    if (currentTenant) {
      setConfig({
        name: currentTenant.name || '',
        description: currentTenant.description || '',
        email: currentTenant.email || '',
        phone: currentTenant.phone || '',
        website: currentTenant.website || '',
        address: currentTenant.address || '',
        city: currentTenant.city || '',
        postalCode: currentTenant.postal_code || '',
        country: currentTenant.country || '',
        taxId: '',
        currency: currentTenant.currency || 'EUR',
        timezone: currentTenant.timezone || 'Europe/Madrid',
        language: currentTenant.language || 'es'
      });
    }
    if (settings) {
      setProcurementSettings(settings.procurement_settings);
      setInventorySettings(settings.inventory_settings);
      setProductionSettings(settings.production_settings);
      setSupplierSettings(settings.supplier_settings);
      setPosSettings(settings.pos_settings);
      setOrderSettings(settings.order_settings);
      setNotificationSettings(settings.notification_settings);
    }
    setHasUnsavedChanges(false);
  };

  if (!currentTenant || settingsLoading) {
    return (
      <div className="p-4 sm:p-6 space-y-6">
        <PageHeader
          title={t('bakery.title')}
          description={t('bakery.description')}
        />
        <div className="flex items-center justify-center h-64">
          <Loader className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
          <span className="ml-2 text-[var(--text-secondary)]">{t('common.loading')}</span>
        </div>
      </div>
    );
  }

  const daysOfWeek = [
    { key: 'monday', label: t('bakery.hours.days.monday') },
    { key: 'tuesday', label: t('bakery.hours.days.tuesday') },
    { key: 'wednesday', label: t('bakery.hours.days.wednesday') },
    { key: 'thursday', label: t('bakery.hours.days.thursday') },
    { key: 'friday', label: t('bakery.hours.days.friday') },
    { key: 'saturday', label: t('bakery.hours.days.saturday') },
    { key: 'sunday', label: t('bakery.hours.days.sunday') }
  ];

  return (
    <div className="p-4 sm:p-6 space-y-6 pb-32">
      <PageHeader
        title={t('bakery.title')}
        description={t('bakery.description')}
      />

      {/* Tabs Navigation */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <Card className="p-2 bg-[var(--bg-secondary)]">
          <TabsList className="w-full grid grid-cols-2 sm:grid-cols-4 gap-2">
            <TabsTrigger value="information" className="flex items-center justify-center gap-2 data-[state=active]:bg-[var(--color-primary)] data-[state=active]:text-white">
              <Store className="w-4 h-4" />
              <span className="hidden sm:inline">{t('bakery.tabs.information')}</span>
              <span className="sm:hidden">Info</span>
            </TabsTrigger>
            <TabsTrigger value="hours" className="flex items-center justify-center gap-2 data-[state=active]:bg-[var(--color-primary)] data-[state=active]:text-white">
              <Clock className="w-4 h-4" />
              <span className="hidden sm:inline">{t('bakery.tabs.hours')}</span>
              <span className="sm:hidden">Hours</span>
            </TabsTrigger>
            <TabsTrigger value="operations" className="flex items-center justify-center gap-2 data-[state=active]:bg-[var(--color-primary)] data-[state=active]:text-white">
              <SettingsIcon className="w-4 h-4" />
              <span className="hidden sm:inline">{t('bakery.tabs.operations')}</span>
              <span className="sm:hidden">Ops</span>
            </TabsTrigger>
            <TabsTrigger value="notifications" className="flex items-center justify-center gap-2 data-[state=active]:bg-[var(--color-primary)] data-[state=active]:text-white">
              <Bell className="w-4 h-4" />
              <span className="hidden sm:inline">{t('bakery.tabs.notifications')}</span>
              <span className="sm:hidden">Notif</span>
            </TabsTrigger>
          </TabsList>
        </Card>

        {/* Tab 1: Information */}
        <TabsContent value="information">
          <div className="space-y-6">
            {/* General Information */}
            <SettingSection
              title={t('bakery.information.general_section')}
              description="Basic information about your bakery"
              icon={<Store className="w-5 h-5 text-[var(--color-primary)]" />}
            >
              <div className="p-6 bg-gradient-to-br from-[var(--bg-primary)] to-[var(--bg-secondary)]">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Input
                    label={t('bakery.information.fields.name')}
                    value={config.name}
                    onChange={handleInputChange('name')}
                    error={errors.name}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.name')}
                    leftIcon={<Store className="w-4 h-4" />}
                    required
                  />

                  <Input
                    type="email"
                    label={t('bakery.information.fields.email')}
                    value={config.email}
                    onChange={handleInputChange('email')}
                    error={errors.email}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.email')}
                    leftIcon={<Mail className="w-4 h-4" />}
                    required
                  />

                  <Input
                    type="tel"
                    label={t('bakery.information.fields.phone')}
                    value={config.phone}
                    onChange={handleInputChange('phone')}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.phone')}
                    leftIcon={<Phone className="w-4 h-4" />}
                  />

                  <Input
                    label={t('bakery.information.fields.website')}
                    value={config.website}
                    onChange={handleInputChange('website')}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.website')}
                    leftIcon={<Globe className="w-4 h-4" />}
                  />
                </div>

                <div className="mt-6 md:col-span-2">
                  <label className="block text-sm font-semibold text-[var(--text-primary)] mb-3">
                    {t('bakery.information.fields.description')}
                  </label>
                  <textarea
                    value={config.description}
                    onChange={handleInputChange('description')}
                    disabled={isLoading}
                    rows={4}
                    className="w-full px-4 py-3 border-2 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)] focus:ring-2 focus:ring-[var(--color-primary)] focus:border-[var(--color-primary)] transition-all"
                    placeholder={t('bakery.information.placeholders.description')}
                  />
                </div>
              </div>
            </SettingSection>

            {/* Location Information */}
            <SettingSection
              title={t('bakery.information.location_section')}
              description="Where your bakery is located"
              icon={<MapPin className="w-5 h-5 text-[var(--color-success)]" />}
            >
              <div className="p-6 bg-gradient-to-br from-[var(--bg-primary)] to-[var(--bg-secondary)]">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Input
                    label={t('bakery.information.fields.address')}
                    value={config.address}
                    onChange={handleInputChange('address')}
                    error={errors.address}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.address')}
                    leftIcon={<MapPin className="w-4 h-4" />}
                    className="md:col-span-2"
                    required
                  />

                  <Input
                    label={t('bakery.information.fields.city')}
                    value={config.city}
                    onChange={handleInputChange('city')}
                    error={errors.city}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.city')}
                    required
                  />

                  <Input
                    label={t('bakery.information.fields.postal_code')}
                    value={config.postalCode}
                    onChange={handleInputChange('postalCode')}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.postal_code')}
                  />

                  <Input
                    label={t('bakery.information.fields.country')}
                    value={config.country}
                    onChange={handleInputChange('country')}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.country')}
                  />
                </div>
              </div>
            </SettingSection>

            {/* Business Information */}
            <SettingSection
              title={t('bakery.information.business_section')}
              description="Tax and business configuration"
              icon={<Building2 className="w-5 h-5 text-[var(--color-info)]" />}
            >
              <div className="p-6 bg-gradient-to-br from-[var(--bg-primary)] to-[var(--bg-secondary)]">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Input
                    label={t('bakery.information.fields.tax_id')}
                    value={config.taxId}
                    onChange={handleInputChange('taxId')}
                    disabled={isLoading}
                    placeholder={t('bakery.information.placeholders.tax_id')}
                    leftIcon={<CreditCard className="w-4 h-4" />}
                  />

                  <Select
                    label={t('bakery.information.fields.currency')}
                    options={currencyOptions}
                    value={config.currency}
                    onChange={(value) => handleSelectChange('currency')(value as string)}
                    disabled={isLoading}
                  />

                  <Select
                    label={t('bakery.information.fields.timezone')}
                    options={timezoneOptions}
                    value={config.timezone}
                    onChange={(value) => handleSelectChange('timezone')(value as string)}
                    disabled={isLoading}
                  />

                  <Select
                    label={t('bakery.information.fields.language')}
                    options={languageOptions}
                    value={config.language}
                    onChange={(value) => handleSelectChange('language')(value as string)}
                    disabled={isLoading}
                  />
                </div>
              </div>
            </SettingSection>
          </div>
        </TabsContent>

        {/* Tab 2: Business Hours */}
        <TabsContent value="hours">
          <SettingSection
            title={t('bakery.hours.title')}
            description="Configure your opening hours for each day of the week"
            icon={<Clock className="w-5 h-5 text-[var(--color-warning)]" />}
          >
            {daysOfWeek.map((day) => {
              const hours = businessHours[day.key];
              return (
                <SettingRow
                  key={day.key}
                  label={day.label}
                  description={hours.closed ? t('bakery.hours.closed_all_day') : `${hours.open} - ${hours.close}`}
                  type="custom"
                  disabled={isLoading}
                >
                  <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 w-full sm:w-auto">
                    <label className="flex items-center gap-2 whitespace-nowrap">
                      <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">{t('bakery.hours.closed')}</span>
                    </label>

                    {!hours.closed && (
                      <>
                        <div className="flex items-center gap-2">
                          <input
                            type="time"
                            value={hours.open}
                            onChange={(e) => handleHoursChange(day.key, 'open', e.target.value)}
                            disabled={isLoading}
                            className="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)]"
                          />
                          <span className="text-sm text-text-tertiary">-</span>
                          <input
                            type="time"
                            value={hours.close}
                            onChange={(e) => handleHoursChange(day.key, 'close', e.target.value)}
                            disabled={isLoading}
                            className="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>
                </SettingRow>
              );
            })}
          </SettingSection>
        </TabsContent>

        {/* Tab 3: Operational Settings */}
        <TabsContent value="operations">
          <div className="space-y-6">
            {procurementSettings && (
              <ProcurementSettingsCard
                settings={procurementSettings}
                onChange={(newSettings) => {
                  setProcurementSettings(newSettings);
                  handleOperationalSettingsChange();
                }}
                disabled={isLoading}
              />
            )}

            {inventorySettings && (
              <InventorySettingsCard
                settings={inventorySettings}
                onChange={(newSettings) => {
                  setInventorySettings(newSettings);
                  handleOperationalSettingsChange();
                }}
                disabled={isLoading}
              />
            )}

            {productionSettings && (
              <ProductionSettingsCard
                settings={productionSettings}
                onChange={(newSettings) => {
                  setProductionSettings(newSettings);
                  handleOperationalSettingsChange();
                }}
                disabled={isLoading}
              />
            )}

            {supplierSettings && (
              <SupplierSettingsCard
                settings={supplierSettings}
                onChange={(newSettings) => {
                  setSupplierSettings(newSettings);
                  handleOperationalSettingsChange();
                }}
                disabled={isLoading}
              />
            )}

            {posSettings && (
              <POSSettingsCard
                settings={posSettings}
                onChange={(newSettings) => {
                  setPosSettings(newSettings);
                  handleOperationalSettingsChange();
                }}
                disabled={isLoading}
              />
            )}

            {orderSettings && (
              <OrderSettingsCard
                settings={orderSettings}
                onChange={(newSettings) => {
                  setOrderSettings(newSettings);
                  handleOperationalSettingsChange();
                }}
                disabled={isLoading}
              />
            )}
          </div>
        </TabsContent>

        {/* Tab 4: Notifications */}
        <TabsContent value="notifications">
          <div className="space-y-6">
            {notificationSettings && (
              <NotificationSettingsCard
                settings={notificationSettings}
                onChange={(newSettings) => {
                  setNotificationSettings(newSettings);
                  handleOperationalSettingsChange();
                }}
                disabled={isLoading}
              />
            )}
          </div>
        </TabsContent>
      </Tabs>

      {/* Floating Save Button */}
      {hasUnsavedChanges && (
        <div className="fixed bottom-6 right-4 sm:right-6 left-4 sm:left-auto z-50 animate-fade-in">
          <Card className="p-4 sm:p-5 shadow-2xl border-2 border-[var(--color-primary)] bg-[var(--bg-primary)]">
            <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-4">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg">
                  <AlertCircle className="w-5 h-5 text-yellow-600 dark:text-yellow-400 animate-pulse" />
                </div>
                <div>
                  <p className="text-sm font-semibold text-[var(--text-primary)]">{t('bakery.unsaved_changes')}</p>
                  <p className="text-xs text-[var(--text-secondary)]">Save or discard your changes</p>
                </div>
              </div>
              <div className="flex gap-3 sm:ml-4">
                <Button
                  variant="outline"
                  size="md"
                  onClick={handleDiscard}
                  disabled={isLoading}
                  className="flex-1 sm:flex-none border-2"
                >
                  <X className="w-4 h-4 mr-2" />
                  {t('common.discard')}
                </Button>
                <Button
                  variant="primary"
                  size="md"
                  onClick={activeTab === 'operations' || activeTab === 'notifications' ? handleSaveOperationalSettings : handleSaveConfig}
                  isLoading={isLoading}
                  loadingText={t('common.saving')}
                  className="flex-1 sm:flex-none shadow-lg"
                >
                  <Save className="w-4 h-4 mr-2" />
                  {t('common.save')}
                </Button>
              </div>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
};

export default BakerySettingsPage;
