import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  Grid,
  TextField,
  Button,
  CircularProgress,
  Alert,
  Divider,
  Tabs,
  Tab,
  Card,
  CardContent,
  FormControlLabel,
  Switch,
  IconButton,
  InputAdornment,
  Tooltip,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Snackbar,
} from '@mui/material';
import {
  Save as SaveIcon,
  Refresh as RefreshIcon,
  Delete as DeleteIcon,
  ColorLens as ColorLensIcon,
  ExpandMore as ExpandMoreIcon,
} from '@mui/icons-material';
import { useAdminSettingsByCategory, useUpdateSetting, useUpdateSettings } from '../../hooks/settingsAdminHooks';
import ImageUploader from '@components/ImageUploader';
import { useQueryClient } from '@tanstack/react-query';

// Default theme colors to reset to
const DEFAULT_COLORS = {
  light: {
    primary: '#7e57c2', // deepPurple[400]
    secondary: '#ffb300', // amber[500]
    background: '#f5f5f5',
    surface: '#ffffff',
    text: '#000000',
  },
  dark: {
    primary: '#9575cd', // deepPurple[300]
    secondary: '#ffd54f', // amber[300]
    background: '#212121',
    surface: '#424242',
    text: '#ffffff',
  }
};

function ColorPickerInput({ label, value, onChange, defaultValue }) {
  const handleChange = (e) => {
    onChange(e.target.value);
  };
  
  const handleReset = () => {
    onChange(defaultValue);
  };

  return (
    <Box sx={{ mb: 2 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
        <Typography variant="body2" sx={{ mr: 1 }}>
          {label}
        </Typography>
        
        <Tooltip title="Reset to default">
          <IconButton onClick={handleReset} size="small">
            <RefreshIcon fontSize="small" />
          </IconButton>
        </Tooltip>
      </Box>
      
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <TextField
          fullWidth
          value={value}
          onChange={handleChange}
          type="color"
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <Box 
                  sx={{ 
                    width: 20, 
                    height: 20, 
                    bgcolor: value, 
                    borderRadius: '4px',
                    border: '1px solid #ddd'
                  }}
                />
              </InputAdornment>
            ),
          }}
        />
      </Box>
    </Box>
  );
}

const BrandingPage = () => {
  const [activeTab, setActiveTab] = useState(0);
  const [logoImage, setLogoImage] = useState([]);
  const [faviconImage, setFaviconImage] = useState([]);
  const [notification, setNotification] = useState({ open: false, message: '', severity: 'success' });
  
  // Get the React Query client for cache invalidation
  const queryClient = useQueryClient();
  
  // Fetch branding settings
  const { data: brandingSettings, isLoading: settingsLoading, error: settingsError, refetch } = useAdminSettingsByCategory('branding');
  const [formData, setFormData] = useState({
    site_name: '',
    site_main_page_title: '',
    site_main_page_subtitle: '',
    site_main_newsletter_desc: '',
    site_main_bottom_sting: '',
    site_quicklinks_title: '',
    site_connect: '',
    blog_title: '',
    blog_desc: '',
    blog_no_content_title: '',
    blog_no_content_subtitle: '',
    blog_search: '',
    cart_empty: '',
    cart_empty_subtitle: '',
    product_title: '',
    orders_title: '',
    orders_empty: '',
    site_description: '',
    default_mode: 'light',
    light_primary_color: DEFAULT_COLORS.light.primary,
    light_secondary_color: DEFAULT_COLORS.light.secondary,
    light_background_color: DEFAULT_COLORS.light.background,
    light_surface_color: DEFAULT_COLORS.light.surface,
    light_text_color: DEFAULT_COLORS.light.text,
    dark_primary_color: DEFAULT_COLORS.dark.primary,
    dark_secondary_color: DEFAULT_COLORS.dark.secondary,
    dark_background_color: DEFAULT_COLORS.dark.background,
    dark_surface_color: DEFAULT_COLORS.dark.surface,
    dark_text_color: DEFAULT_COLORS.dark.text,
    logo_url: '',
    favicon_url: '',
    copyright_text: '',
  });
  // Update settings mutation
  const updateSettings = useUpdateSettings();
  const updateSetting = useUpdateSetting();
  
  // Handle tab change
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };
  
  // Handle notification close
  const handleCloseNotification = () => {
    setNotification({ ...notification, open: false });
  };
  
  // Initialize form data when settings are loaded
  useEffect(() => {
    if (brandingSettings) {
      const initialData = {};
      brandingSettings?.forEach(setting => {
        initialData[setting.key] = setting.value;
      });
      
      // Apply settings to form
      setFormData(prev => ({
        ...prev,
        ...initialData
      }));
      
      if (initialData.logo_url) {
        setLogoImage([{ path: initialData.logo_url, isPrimary: true }]);
      } else {
        setLogoImage([]);
      }
      
      if (initialData.favicon_url) {
        setFaviconImage([{ path: initialData.favicon_url, isPrimary: true }]);
      } else {
        setFaviconImage([]);
      }
    }
  }, [brandingSettings]);
  
  // Handle form input changes
  const handleChange = (e) => {
    const { name, value, checked, type } = e.target;
    setFormData({
      ...formData,
      [name]: type === 'checkbox' ? checked.toString() : value
    });
  };
  
  // Handle color picker changes
  const handleColorChange = (name, value) => {
    setFormData({
      ...formData,
      [name]: value
    });
  };
  
  // Handle logo image changes
  const handleLogoChange = (images) => {
    setLogoImage(images);
    if (images && images.length > 0) {
      setFormData({
        ...formData,
        logo_url: images[0].path
      });
    } else {
      setFormData({
        ...formData,
        logo_url: ''
      });
    }
  };
  
  // Handle favicon image changes
  const handleFaviconChange = (images) => {
    setFaviconImage(images);
    if (images && images.length > 0) {
      setFormData({
        ...formData,
        favicon_url: images[0].path
      });
    } else {
      setFormData({
        ...formData,
        favicon_url: ''
      });
    }
  };
  
  // Reset to default colors
  const handleResetColors = (mode) => {
    if (mode === 'light') {
      setFormData({
        ...formData,
        light_primary_color: DEFAULT_COLORS.light.primary,
        light_secondary_color: DEFAULT_COLORS.light.secondary,
        light_background_color: DEFAULT_COLORS.light.background,
        light_surface_color: DEFAULT_COLORS.light.surface,
        light_text_color: DEFAULT_COLORS.light.text,
      });
    } else {
      setFormData({
        ...formData,
        dark_primary_color: DEFAULT_COLORS.dark.primary,
        dark_secondary_color: DEFAULT_COLORS.dark.secondary,
        dark_background_color: DEFAULT_COLORS.dark.background,
        dark_surface_color: DEFAULT_COLORS.dark.surface,
        dark_text_color: DEFAULT_COLORS.dark.text,
      });
    }
  };
  
  // Save all settings
  const handleSaveSettings = async () => {
    const settingsToUpdate = [];
    
    // Convert form data to settings array
    Object.entries(formData).forEach(([key, value]) => {
      if (value !== undefined) {
        settingsToUpdate.push({
          key,
          value,
          category: 'branding'
        });
      }
    });
    
    if (settingsToUpdate.length > 0) {
      try {
        await updateSettings.mutateAsync(settingsToUpdate);
        
        // Show success notification
        setNotification({
          open: true,
          message: 'Branding settings saved successfully',
          severity: 'success'
        });
        
        // Invalidate the branding settings query to trigger a refresh in all components
        queryClient.invalidateQueries(['branding-settings']);
        
        // Refresh to get updated settings in this component
        refetch();
        
        // Update the favicon immediately if it was changed
        if (formData.favicon_url) {
          const link = document.querySelector("link[rel*='icon']") || document.createElement('link');
          link.type = 'image/x-icon';
          link.rel = 'shortcut icon';
          link.href = formData.favicon_url;
          document.getElementsByTagName('head')[0].appendChild(link);
        }
        
        // Update document title if site name changed
        if (formData.site_name) {
          document.title = formData.site_name;
        }
      } catch (error) {
        // Show error notification
        setNotification({
          open: true,
          message: `Failed to save settings: ${error.message}`,
          severity: 'error'
        });
        console.error('Failed to update settings:', error);
      }
    }
  };
  
  // Loading state
  if (settingsLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // Error state
  if (settingsError) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading branding settings: {settingsError.message}
      </Alert>
    );
  }
  
  return (
    <Box>
      <Typography variant="h4" component="h1" gutterBottom>
        Branding & Theme Settings
      </Typography>
      
      <Paper sx={{ mb: 4 }}>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs 
            value={activeTab} 
            onChange={handleTabChange} 
            aria-label="branding tabs"
          >
            <Tab label="General" id="branding-tab-0" />
            <Tab label="Colors & Theme" id="branding-tab-1" />
            <Tab label="Assets" id="branding-tab-2" />
          </Tabs>
        </Box>
        
        {/* General Settings Tab */}
        <TabPanel value={activeTab} index={0}>
          <Typography variant="h6" gutterBottom>
            General Settings
          </Typography>
          
          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="Site Name"
                name="site_name"
                value={formData.site_name || ''}
                onChange={handleChange}
                helperText="The name of your site (e.g., Rocks, Bones & Sticks)"
              />
            </Grid>
            
            <Grid item xs={12} md={6}>
              <FormControlLabel
                control={
                  <Switch
                    checked={formData.default_mode === 'dark'}
                    onChange={(e) => setFormData({
                      ...formData,
                      default_mode: e.target.checked ? 'dark' : 'light'
                    })}
                    name="default_mode"
                    color="primary"
                  />
                }
                label="Use Dark Mode by Default"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Site Description"
                name="site_description"
                multiline
                rows={2}
                value={formData.site_description || ''}
                onChange={handleChange}
                helperText="Short description for SEO and social media"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Copyright Text"
                name="copyright_text"
                value={formData.copyright_text || ''}
                onChange={handleChange}
                helperText="Text to display in the footer (e.g., © 2025 Your Company Name. All rights reserved.)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Main Banner Title"
                name="site_main_page_title"
                value={formData.site_main_page_title || ''}
                onChange={handleChange}
                helperText="Text to display in the Banner Title (e.g., Discover Natural Wonders)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Main Banner Subtitle"
                name="site_main_page_subtitle"
                value={formData.site_main_page_subtitle || ''}
                onChange={handleChange}
                helperText="Text to display in the Banner Subtitle (e.g., Unique rocks, bones, and sticks from around the world)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Newletter Description"
                name="site_main_newsletter_desc"
                value={formData.site_main_newsletter_desc || ''}
                onChange={handleChange}
                helperText="Text to display in the Footer (e.g., Subscribe to our newsletter for updates on new items and promotions)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Banner Bottom"
                name="site_main_bottom_sting"
                value={formData.site_main_bottom_sting || ''}
                onChange={handleChange}
                helperText="Text to display in the Bottom Banner (e.g., Ready to explore more?)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Site Description"
                name="site_description"
                value={formData.site_description || ''}
                onChange={handleChange}
                helperText="Text For the Site description (e.g., Your premier source for natural curiosities and unique specimens)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Quick Links Title"
                name="site_quicklinks_title"
                value={formData.site_quicklinks_title || ''}
                onChange={handleChange}
                helperText="Text For Quick links (e.g., Quick Links)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Connect us Title"
                name="site_connect"
                value={formData.site_connect || ''}
                onChange={handleChange}
                helperText="Text For Connect with us section(e.g., Connect with us )"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Blog Title"
                name="blog_title"
                value={formData.blog_title || ''}
                onChange={handleChange}
                helperText="Text For Blog Title(e.g., Our Story )"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Blog Description"
                name="blog_desc"
                value={formData.blog_desc || ''}
                onChange={handleChange}
                helperText="Text For Blog Description (e.g., Discover insights about our natural collections, sourcing adventures, and unique specimens )"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Blog No Content Title"
                name="blog_no_content_title"
                value={formData.blog_no_content_title || ''}
                onChange={handleChange}
                helperText="Text For no found Blog content (e.g., No blog posts found )"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Blog No Content Subtitle"
                name="blog_no_content_subtitle"
                value={formData.blog_no_content_subtitle || ''}
                onChange={handleChange}
                helperText="Subtitle For no found Blog content (e.g., Check back soon for new content)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Blog Search Text"
                name="blog_search"
                value={formData.blog_search || ''}
                onChange={handleChange}
                helperText="Search text Blog Page (e.g., Search blog posts)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Cart Empty Text"
                name="cart_empty"
                value={formData.cart_empty || ''}
                onChange={handleChange}
                helperText="Text for empty cart (e.g., Your Cart is Empty)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Cart Empty Subtitle"
                name="cart_empty_subtitle"
                value={formData.cart_empty_subtitle || ''}
                onChange={handleChange}
                helperText="Main Text for empty cart (e.g., Looks like you have not added any items to your cart yet.)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Product Page Title"
                name="product_title"
                value={formData.product_title || ''}
                onChange={handleChange}
                helperText="Text for Produce page title (e.g., Products)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Orders Page Title"
                name="orders_title"
                value={formData.orders_title || ''}
                onChange={handleChange}
                helperText="Text for Orders page title (e.g., My Orders)"
              />
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Orders No Content"
                name="orders_empty"
                value={formData.orders_empty || ''}
                onChange={handleChange}
                helperText="Text for Orders page no content (e.g., You have not placed any orders yet.)"
              />
            </Grid>
          </Grid>
        </TabPanel>
        
        {/* Colors & Theme Tab */}
        <TabPanel value={activeTab} index={1}>
          <Grid container spacing={4}>
            {/* Light Mode Colors */}
            <Grid item xs={12} md={6}>
              <Card variant="outlined">
                <CardContent>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                    <Typography variant="h6">Light Mode Colors</Typography>
                    <Button 
                      size="small" 
                      startIcon={<RefreshIcon />}
                      onClick={() => handleResetColors('light')}
                    >
                      Reset to Default
                    </Button>
                  </Box>
                  
                  <ColorPickerInput 
                    label="Primary Color" 
                    value={formData.light_primary_color || DEFAULT_COLORS.light.primary} 
                    onChange={(value) => handleColorChange('light_primary_color', value)}
                    defaultValue={DEFAULT_COLORS.light.primary}
                  />
                  
                  <ColorPickerInput 
                    label="Secondary Color" 
                    value={formData.light_secondary_color || DEFAULT_COLORS.light.secondary} 
                    onChange={(value) => handleColorChange('light_secondary_color', value)}
                    defaultValue={DEFAULT_COLORS.light.secondary}
                  />
                  
                  <Accordion sx={{ mb: 2 }}>
                    <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                      <Typography>Advanced Colors</Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                      <ColorPickerInput 
                        label="Background Color" 
                        value={formData.light_background_color || DEFAULT_COLORS.light.background} 
                        onChange={(value) => handleColorChange('light_background_color', value)}
                        defaultValue={DEFAULT_COLORS.light.background}
                      />
                      
                      <ColorPickerInput 
                        label="Surface Color" 
                        value={formData.light_surface_color || DEFAULT_COLORS.light.surface} 
                        onChange={(value) => handleColorChange('light_surface_color', value)}
                        defaultValue={DEFAULT_COLORS.light.surface}
                      />
                      
                      <ColorPickerInput 
                        label="Text Color" 
                        value={formData.light_text_color || DEFAULT_COLORS.light.text} 
                        onChange={(value) => handleColorChange('light_text_color', value)}
                        defaultValue={DEFAULT_COLORS.light.text}
                      />
                    </AccordionDetails>
                  </Accordion>
                  
                  <Box sx={{ bgcolor: formData.light_background_color, p: 3, borderRadius: 1, border: '1px solid #ddd' }}>
                    <Typography variant="h6" sx={{ color: formData.light_text_color }}>Preview</Typography>
                    <Box sx={{ 
                      display: 'flex', 
                      justifyContent: 'center', 
                      mt: 2, 
                      gap: 2 
                    }}>
                      <Button 
                        variant="contained" 
                        sx={{ 
                          bgcolor: formData.light_primary_color,
                          '&:hover': {
                            bgcolor: formData.light_primary_color,
                            filter: 'brightness(0.9)'
                          }
                        }}
                      >
                        Primary
                      </Button>
                      <Button 
                        variant="contained" 
                        sx={{ 
                          bgcolor: formData.light_secondary_color,
                          '&:hover': {
                            bgcolor: formData.light_secondary_color,
                            filter: 'brightness(0.9)'
                          }
                        }}
                      >
                        Secondary
                      </Button>
                    </Box>
                  </Box>
                </CardContent>
              </Card>
            </Grid>
            
            {/* Dark Mode Colors */}
            <Grid item xs={12} md={6}>
              <Card variant="outlined">
                <CardContent>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                    <Typography variant="h6">Dark Mode Colors</Typography>
                    <Button 
                      size="small" 
                      startIcon={<RefreshIcon />}
                      onClick={() => handleResetColors('dark')}
                    >
                      Reset to Default
                    </Button>
                  </Box>
                  
                  <ColorPickerInput 
                    label="Primary Color" 
                    value={formData.dark_primary_color || DEFAULT_COLORS.dark.primary} 
                    onChange={(value) => handleColorChange('dark_primary_color', value)}
                    defaultValue={DEFAULT_COLORS.dark.primary}
                  />
                  
                  <ColorPickerInput 
                    label="Secondary Color" 
                    value={formData.dark_secondary_color || DEFAULT_COLORS.dark.secondary} 
                    onChange={(value) => handleColorChange('dark_secondary_color', value)}
                    defaultValue={DEFAULT_COLORS.dark.secondary}
                  />
                  
                  <Accordion sx={{ mb: 2 }}>
                    <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                      <Typography>Advanced Colors</Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                      <ColorPickerInput 
                        label="Background Color" 
                        value={formData.dark_background_color || DEFAULT_COLORS.dark.background} 
                        onChange={(value) => handleColorChange('dark_background_color', value)}
                        defaultValue={DEFAULT_COLORS.dark.background}
                      />
                      
                      <ColorPickerInput 
                        label="Surface Color" 
                        value={formData.dark_surface_color || DEFAULT_COLORS.dark.surface} 
                        onChange={(value) => handleColorChange('dark_surface_color', value)}
                        defaultValue={DEFAULT_COLORS.dark.surface}
                      />
                      
                      <ColorPickerInput 
                        label="Text Color" 
                        value={formData.dark_text_color || DEFAULT_COLORS.dark.text} 
                        onChange={(value) => handleColorChange('dark_text_color', value)}
                        defaultValue={DEFAULT_COLORS.dark.text}
                      />
                    </AccordionDetails>
                  </Accordion>
                  
                  <Box sx={{ bgcolor: formData.dark_background_color, p: 3, borderRadius: 1, border: '1px solid #333' }}>
                    <Typography variant="h6" sx={{ color: formData.dark_text_color }}>Preview</Typography>
                    <Box sx={{ 
                      display: 'flex', 
                      justifyContent: 'center', 
                      mt: 2, 
                      gap: 2 
                    }}>
                      <Button 
                        variant="contained" 
                        sx={{ 
                          bgcolor: formData.dark_primary_color,
                          '&:hover': {
                            bgcolor: formData.dark_primary_color,
                            filter: 'brightness(0.9)'
                          }
                        }}
                      >
                        Primary
                      </Button>
                      <Button 
                        variant="contained" 
                        sx={{ 
                          bgcolor: formData.dark_secondary_color,
                          '&:hover': {
                            bgcolor: formData.dark_secondary_color,
                            filter: 'brightness(0.9)'
                          }
                        }}
                      >
                        Secondary
                      </Button>
                    </Box>
                  </Box>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </TabPanel>
        
        {/* Assets Tab */}
        <TabPanel value={activeTab} index={2}>
          <Grid container spacing={3}>
            
            {/* Favicon Upload */}
            <Grid item xs={12} md={6}>
              <Card variant="outlined">
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    Favicon
                  </Typography>
                  <Typography variant="body2" color="text.secondary" paragraph>
                    Upload a favicon for your site. This will appear in browser tabs. Recommended size: 32px by 32px.
                  </Typography>
                  
                  <ImageUploader 
                    images={faviconImage}
                    onChange={handleFaviconChange}
                    multiple={false}
                  />
                  
                  {faviconImage.length > 0 && (
                    <Box sx={{ mt: 2, p: 2, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }}>
                      <Typography variant="subtitle2" gutterBottom>
                        Current Favicon
                      </Typography>
                      <Box 
                        component="img" 
                        src={faviconImage[0].path} 
                        alt="Current favicon"
                        sx={{ 
                          width: '32px',
                          height: '32px',
                          display: 'block'
                        }}
                      />
                    </Box>
                  )}
                </CardContent>
              </Card>
            </Grid>


            {/* Logo Upload */}
            <Grid item xs={12} md={6}>
              <Card variant="outlined">
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    Logo
                  </Typography>
                  <Typography variant="body2" color="text.secondary" paragraph>
                    Upload your site logo. Recommended size: 200px by 50px.
                  </Typography>
                  
                  <ImageUploader 
                    images={logoImage}
                    onChange={handleLogoChange}
                    multiple={false}
                  />
                  
                  {logoImage.length > 0 && (
                    <Box sx={{ mt: 2, p: 2, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }}>
                      <Typography variant="subtitle2" gutterBottom>
                        Current Logo
                      </Typography>
                      <Box 
                        component="img" 
                        src={logoImage[0].path} 
                        alt="Current logo"
                        sx={{ 
                          maxWidth: '100%',
                          height: 'auto',
                          maxHeight: '100px',
                          display: 'block'
                        }}
                      />
                    </Box>
                  )}
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </TabPanel>
        
        <Box sx={{ display: 'flex', justifyContent: 'flex-end', p: 2 }}>
          <Button
            variant="outlined"
            startIcon={<RefreshIcon />}
            onClick={refetch}
            sx={{ mr: 2 }}
          >
            Refresh
          </Button>
          <Button
            variant="contained"
            startIcon={<SaveIcon />}
            onClick={handleSaveSettings}
            disabled={updateSettings.isLoading}
          >
            {updateSettings.isLoading ? <CircularProgress size={24} /> : 'Save Changes'}
          </Button>
        </Box>
      </Paper>
      
      {/* Notification */}
      <Snackbar
        open={notification.open}
        autoHideDuration={6000}
        onClose={handleCloseNotification}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
      >
        <Alert 
          onClose={handleCloseNotification} 
          severity={notification.severity}
          sx={{ width: '100%' }}
        >
          {notification.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

// TabPanel component
function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`branding-tabpanel-${index}`}
      aria-labelledby={`branding-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
}

export default BrandingPage;