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 AppearanceCart() {
  const [loading, setLoading] = useState(true);
  const [layoutStyle, setLayoutStyle] = useState('fullwidth');
  const [summaryPosition, setSummaryPosition] = useState('right');
  
  const [elements, setElements] = useState({
    product_images: true,
    continue_shopping_button: true,
    coupon_field: true,
    shipping_calculator: false,
  });

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await api.get('/appearance/settings');
        const cart = response.data?.pages?.cart;
        
        if (cart) {
          if (cart.layout) {
            if (cart.layout.style) setLayoutStyle(cart.layout.style);
            if (cart.layout.summary_position) setSummaryPosition(cart.layout.summary_position);
          }
          if (cart.elements) {
            setElements({
              product_images: cart.elements.product_images ?? true,
              continue_shopping_button: cart.elements.continue_shopping_button ?? true,
              coupon_field: cart.elements.coupon_field ?? true,
              shipping_calculator: cart.elements.shipping_calculator ?? false,
            });
          }
        }
      } 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/pages/cart', {
        layout: { style: layoutStyle, summary_position: summaryPosition },
        elements,
      });
      toast.success('Cart page settings saved successfully');
    } catch (error) {
      console.error('Save error:', error);
      toast.error('Failed to save settings');
    }
  };

  return (
    <SettingsLayout
      title="Cart Page Settings"
      onSave={handleSave}
      isLoading={loading}
    >
      <SettingsCard
        title="Layout"
        description="Configure cart page layout"
      >
        <SettingsSection label="Style" htmlFor="layout-style">
          <Select value={layoutStyle} onValueChange={setLayoutStyle}>
            <SelectTrigger id="layout-style">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="fullwidth">Full Width</SelectItem>
              <SelectItem value="boxed">Boxed</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>

        <SettingsSection label="Summary Position" htmlFor="summary-position">
          <Select value={summaryPosition} onValueChange={setSummaryPosition}>
            <SelectTrigger id="summary-position">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="right">Right</SelectItem>
              <SelectItem value="bottom">Bottom</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>
      </SettingsCard>

      <SettingsCard
        title="Elements"
        description="Choose which elements to display on the cart page"
      >
        <div className="flex items-center justify-between">
          <Label htmlFor="element-product-images" className="cursor-pointer">
            Show product images
          </Label>
          <Switch
            id="element-product-images"
            checked={elements.product_images}
            onCheckedChange={() => toggleElement('product_images')}
          />
        </div>

        <div className="flex items-center justify-between">
          <Label htmlFor="element-continue-shopping" className="cursor-pointer">
            Show continue shopping button
          </Label>
          <Switch
            id="element-continue-shopping"
            checked={elements.continue_shopping_button}
            onCheckedChange={() => toggleElement('continue_shopping_button')}
          />
        </div>

        <div className="flex items-center justify-between">
          <Label htmlFor="element-coupon-field" className="cursor-pointer">
            Show coupon field
          </Label>
          <Switch
            id="element-coupon-field"
            checked={elements.coupon_field}
            onCheckedChange={() => toggleElement('coupon_field')}
          />
        </div>

        <div className="flex items-center justify-between">
          <Label htmlFor="element-shipping-calculator" className="cursor-pointer">
            Show shipping calculator
          </Label>
          <Switch
            id="element-shipping-calculator"
            checked={elements.shipping_calculator}
            onCheckedChange={() => toggleElement('shipping_calculator')}
          />
        </div>
      </SettingsCard>
    </SettingsLayout>
  );
}
