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 { Input } from '@/components/ui/input';
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 AppearanceCheckout() {
  const [loading, setLoading] = useState(true);
  const [layoutStyle, setLayoutStyle] = useState('two-column');
  const [orderSummary, setOrderSummary] = useState('sidebar');
  const [headerVisibility, setHeaderVisibility] = useState('minimal');
  const [footerVisibility, setFooterVisibility] = useState('minimal');
  const [backgroundColor, setBackgroundColor] = useState('#f9fafb');
  
  const [elements, setElements] = useState({
    order_notes: true,
    coupon_field: true,
    shipping_options: true,
    payment_icons: true,
  });

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await api.get('/appearance/settings');
        const checkout = response.data?.pages?.checkout;
        
        if (checkout) {
          if (checkout.layout) {
            if (checkout.layout.style) setLayoutStyle(checkout.layout.style);
            if (checkout.layout.order_summary) setOrderSummary(checkout.layout.order_summary);
            if (checkout.layout.header_visibility) setHeaderVisibility(checkout.layout.header_visibility);
            if (checkout.layout.footer_visibility) setFooterVisibility(checkout.layout.footer_visibility);
            if (checkout.layout.background_color) setBackgroundColor(checkout.layout.background_color);
          }
          if (checkout.elements) {
            setElements({
              order_notes: checkout.elements.order_notes ?? true,
              coupon_field: checkout.elements.coupon_field ?? true,
              shipping_options: checkout.elements.shipping_options ?? true,
              payment_icons: checkout.elements.payment_icons ?? true,
            });
          }
        }
      } 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/checkout', {
        layout: { 
          style: layoutStyle, 
          order_summary: orderSummary,
          header_visibility: headerVisibility,
          footer_visibility: footerVisibility,
          background_color: backgroundColor,
        },
        elements,
      });
      toast.success('Checkout page settings saved successfully');
    } catch (error) {
      console.error('Save error:', error);
      toast.error('Failed to save settings');
    }
  };

  return (
    <SettingsLayout
      title="Checkout Page Settings"
      onSave={handleSave}
      isLoading={loading}
    >
      <SettingsCard
        title="Layout"
        description="Configure checkout page layout"
      >
        <SettingsSection label="Style" htmlFor="layout-style">
          <Select value={layoutStyle} onValueChange={setLayoutStyle}>
            <SelectTrigger id="layout-style">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="single-column">Single Column</SelectItem>
              <SelectItem value="two-column">Two Columns</SelectItem>
            </SelectContent>
          </Select>
          <div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded-md">
            <p className="text-sm text-blue-900 font-medium mb-1">Layout Scenarios:</p>
            <ul className="text-sm text-blue-800 space-y-1 list-disc list-inside">
              <li><strong>Two Columns + Sidebar:</strong> Form left, summary right (Desktop standard)</li>
              <li><strong>Two Columns + Top:</strong> Summary top, form below (Mobile-friendly)</li>
              <li><strong>Single Column:</strong> Everything stacked vertically (Order Summary position ignored)</li>
            </ul>
          </div>
        </SettingsSection>

        <SettingsSection label="Order Summary Position" htmlFor="order-summary">
          <Select 
            value={orderSummary} 
            onValueChange={setOrderSummary}
            disabled={layoutStyle === 'single-column'}
          >
            <SelectTrigger id="order-summary">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="sidebar">Sidebar (Right)</SelectItem>
              <SelectItem value="top">Top (Above Form)</SelectItem>
            </SelectContent>
          </Select>
          {layoutStyle === 'single-column' && (
            <p className="text-sm text-muted-foreground mt-2">
              ⚠️ This setting is disabled in Single Column mode. Summary always appears at top.
            </p>
          )}
          {layoutStyle === 'two-column' && (
            <p className="text-sm text-muted-foreground mt-2">
              {orderSummary === 'sidebar' 
                ? '✓ Summary appears on right side (desktop), top on mobile'
                : '✓ Summary appears at top, form below. Place Order button moves to bottom.'}
            </p>
          )}
        </SettingsSection>
      </SettingsCard>

      <SettingsCard
        title="Header & Footer"
        description="Control header and footer visibility for distraction-free checkout"
      >
        <SettingsSection label="Header Visibility" htmlFor="header-visibility">
          <Select value={headerVisibility} onValueChange={setHeaderVisibility}>
            <SelectTrigger id="header-visibility">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="show">Show Full Header</SelectItem>
              <SelectItem value="minimal">Minimal (Logo Only)</SelectItem>
              <SelectItem value="hide">Hide Completely</SelectItem>
            </SelectContent>
          </Select>
          <p className="text-sm text-gray-500 mt-1">
            Minimal header reduces distractions and improves conversion by 5-10%
          </p>
        </SettingsSection>

        <SettingsSection label="Footer Visibility" htmlFor="footer-visibility">
          <Select value={footerVisibility} onValueChange={setFooterVisibility}>
            <SelectTrigger id="footer-visibility">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="show">Show Full Footer</SelectItem>
              <SelectItem value="minimal">Minimal (Trust Badges & Policies)</SelectItem>
              <SelectItem value="hide">Hide Completely</SelectItem>
            </SelectContent>
          </Select>
          <p className="text-sm text-gray-500 mt-1">
            Minimal footer with trust signals builds confidence without clutter
          </p>
        </SettingsSection>
      </SettingsCard>

      <SettingsCard
        title="Page Styling"
        description="Customize the visual appearance of the checkout page"
      >
        <SettingsSection label="Background Color" htmlFor="background-color">
          <div className="flex gap-2">
            <Input
              id="background-color"
              type="color"
              value={backgroundColor}
              onChange={(e) => setBackgroundColor(e.target.value)}
              className="w-20 h-10"
            />
            <Input
              type="text"
              value={backgroundColor}
              onChange={(e) => setBackgroundColor(e.target.value)}
              placeholder="#f9fafb"
              className="flex-1"
            />
          </div>
          <p className="text-sm text-gray-500 mt-1">
            Set the background color for the checkout page
          </p>
        </SettingsSection>
      </SettingsCard>

      <SettingsCard
        title="Elements"
        description="Choose which elements to display on the checkout page"
      >
        <div className="flex items-center justify-between">
          <Label htmlFor="element-order-notes" className="cursor-pointer">
            Show order notes field
          </Label>
          <Switch
            id="element-order-notes"
            checked={elements.order_notes}
            onCheckedChange={() => toggleElement('order_notes')}
          />
        </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-options" className="cursor-pointer">
            Show shipping options
          </Label>
          <Switch
            id="element-shipping-options"
            checked={elements.shipping_options}
            onCheckedChange={() => toggleElement('shipping_options')}
          />
        </div>

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