import React, { useState, useEffect } from 'react';
import { SettingsLayout } from '@/routes/Settings/components/SettingsLayout';
import { SettingsCard } from '@/routes/Settings/components/SettingsCard';
import { SettingsSection } from '@/routes/Settings/components/SettingsSection';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { toast } from 'sonner';
import { api } from '@/lib/api';

export default function AppearanceHeader() {
  const [loading, setLoading] = useState(true);
  const [style, setStyle] = useState('classic');
  const [sticky, setSticky] = useState(true);
  const [height, setHeight] = useState('normal');
  const [mobileMenu, setMobileMenu] = useState('hamburger');
  const [mobileLogo, setMobileLogo] = useState('left');
  const [logoWidth, setLogoWidth] = useState('auto');
  const [logoHeight, setLogoHeight] = useState('40px');
  
  const [elements, setElements] = useState({
    logo: true,
    navigation: true,
    search: true,
    account: true,
    cart: true,
    wishlist: false,
  });

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await api.get('/appearance/settings');
        const header = response.data?.header;
        
        if (header) {
          if (header.style) setStyle(header.style);
          if (header.sticky !== undefined) setSticky(header.sticky);
          if (header.height) setHeight(header.height);
          if (header.mobile_menu) setMobileMenu(header.mobile_menu);
          if (header.mobile_logo) setMobileLogo(header.mobile_logo);
          if (header.logo_width) setLogoWidth(header.logo_width);
          if (header.logo_height) setLogoHeight(header.logo_height);
          if (header.elements) setElements(header.elements);
        }
      } catch (error) {
        console.error('Failed to load settings:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadSettings();
  }, []);

  const toggleElement = (key: keyof typeof elements) => {
    setElements({ ...elements, [key]: !elements[key] });
  };

  const handleSave = async () => {
    try {
      await api.post('/appearance/header', {
        style,
        sticky,
        height,
        mobileMenu,
        mobileLogo,
        logoWidth,
        logoHeight,
        elements,
      });
      toast.success('Header settings saved successfully');
    } catch (error) {
      console.error('Save error:', error);
      toast.error('Failed to save settings');
    }
  };

  return (
    <SettingsLayout
      title="Header Settings"
      onSave={handleSave}
      isLoading={loading}
    >
      {/* Layout */}
      <SettingsCard
        title="Layout"
        description="Configure header layout and style"
      >
        <SettingsSection label="Style" htmlFor="header-style">
          <Select value={style} onValueChange={setStyle}>
            <SelectTrigger id="header-style">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="classic">Classic</SelectItem>
              <SelectItem value="modern">Modern</SelectItem>
              <SelectItem value="minimal">Minimal</SelectItem>
              <SelectItem value="centered">Centered</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>

        <div className="flex items-center justify-between">
          <div className="space-y-0.5">
            <Label htmlFor="sticky-header">Sticky Header</Label>
            <p className="text-sm text-muted-foreground">
              Header stays visible when scrolling
            </p>
          </div>
          <Switch
            id="sticky-header"
            checked={sticky}
            onCheckedChange={setSticky}
          />
        </div>

        <SettingsSection label="Height" htmlFor="header-height">
          <Select value={height} onValueChange={setHeight}>
            <SelectTrigger id="header-height">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="compact">Compact</SelectItem>
              <SelectItem value="normal">Normal</SelectItem>
              <SelectItem value="tall">Tall</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>

        <SettingsSection label="Logo Width" htmlFor="logo-width">
          <Select value={logoWidth} onValueChange={setLogoWidth}>
            <SelectTrigger id="logo-width">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="auto">Auto</SelectItem>
              <SelectItem value="100px">100px</SelectItem>
              <SelectItem value="150px">150px</SelectItem>
              <SelectItem value="200px">200px</SelectItem>
              <SelectItem value="250px">250px</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>

        <SettingsSection label="Logo Height" htmlFor="logo-height">
          <Select value={logoHeight} onValueChange={setLogoHeight}>
            <SelectTrigger id="logo-height">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="auto">Auto</SelectItem>
              <SelectItem value="30px">30px</SelectItem>
              <SelectItem value="40px">40px</SelectItem>
              <SelectItem value="50px">50px</SelectItem>
              <SelectItem value="60px">60px</SelectItem>
              <SelectItem value="80px">80px</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>
      </SettingsCard>

      {/* Elements */}
      <SettingsCard
        title="Elements"
        description="Choose which elements to display in the header"
      >
        {Object.entries(elements).map(([key, value]) => (
          <div key={key} className="flex items-center justify-between">
            <Label htmlFor={`element-${key}`} className="capitalize cursor-pointer">
              Show {key.replace(/([A-Z])/g, ' $1').toLowerCase()}
            </Label>
            <Switch
              id={`element-${key}`}
              checked={value}
              onCheckedChange={() => toggleElement(key as keyof typeof elements)}
            />
          </div>
        ))}
      </SettingsCard>

      {/* Mobile */}
      <SettingsCard
        title="Mobile Settings"
        description="Configure header behavior on mobile devices"
      >
        <SettingsSection label="Menu Style" htmlFor="mobile-menu">
          <Select value={mobileMenu} onValueChange={setMobileMenu}>
            <SelectTrigger id="mobile-menu">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="hamburger">Hamburger</SelectItem>
              <SelectItem value="bottom-nav">Bottom Navigation</SelectItem>
              <SelectItem value="slide-in">Slide-in Drawer</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>

        <SettingsSection label="Logo Position" htmlFor="mobile-logo">
          <Select value={mobileLogo} onValueChange={setMobileLogo}>
            <SelectTrigger id="mobile-logo">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="left">Left</SelectItem>
              <SelectItem value="center">Center</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>
      </SettingsCard>
    </SettingsLayout>
  );
}
