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 { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { toast } from 'sonner';
import { api } from '@/lib/api';

export default function AppearanceThankYou() {
  const [loading, setLoading] = useState(true);
  const [template, setTemplate] = useState('basic');
  const [headerVisibility, setHeaderVisibility] = useState('show');
  const [footerVisibility, setFooterVisibility] = useState('minimal');
  const [backgroundColor, setBackgroundColor] = useState('#f9fafb');
  const [customMessage, setCustomMessage] = useState('Thank you for your order! We\'ll send you a confirmation email shortly.');
  
  const [elements, setElements] = useState({
    order_details: true,
    continue_shopping_button: true,
    related_products: false,
  });

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await api.get('/appearance/settings');
        const thankyou = response.data?.pages?.thankyou;
        
        if (thankyou) {
          if (thankyou.template) setTemplate(thankyou.template);
          if (thankyou.header_visibility) setHeaderVisibility(thankyou.header_visibility);
          if (thankyou.footer_visibility) setFooterVisibility(thankyou.footer_visibility);
          if (thankyou.background_color) setBackgroundColor(thankyou.background_color);
          if (thankyou.custom_message) setCustomMessage(thankyou.custom_message);
          if (thankyou.elements) setElements(thankyou.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/pages/thankyou', {
        template,
        header_visibility: headerVisibility,
        footer_visibility: footerVisibility,
        background_color: backgroundColor,
        custom_message: customMessage,
        elements,
      });
      toast.success('Thank you page settings saved successfully');
    } catch (error) {
      console.error('Save error:', error);
      toast.error('Failed to save settings');
    }
  };

  return (
    <SettingsLayout
      title="Thank You Page Settings"
      onSave={handleSave}
      isLoading={loading}
    >
      <SettingsCard
        title="Template Style"
        description="Choose the visual style for your thank you page"
      >
        <SettingsSection label="Template" htmlFor="template-style">
          <RadioGroup value={template} onValueChange={setTemplate}>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="basic" id="template-basic" />
              <Label htmlFor="template-basic" className="cursor-pointer">
                <div>
                  <div className="font-medium">Basic Style</div>
                  <div className="text-sm text-gray-500">Modern card-based layout with clean design</div>
                </div>
              </Label>
            </div>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value="receipt" id="template-receipt" />
              <Label htmlFor="template-receipt" className="cursor-pointer">
                <div>
                  <div className="font-medium">Receipt Style</div>
                  <div className="text-sm text-gray-500">Classic receipt design with dotted lines and monospace font</div>
                </div>
              </Label>
            </div>
          </RadioGroup>
        </SettingsSection>
      </SettingsCard>

      <SettingsCard
        title="Header & Footer"
        description="Control header and footer visibility for focused order confirmation"
      >
        <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">
            Control main site header visibility on thank you page
          </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">
            Control main site footer visibility on thank you page
          </p>
        </SettingsSection>
      </SettingsCard>

      <SettingsCard
        title="Page Styling"
        description="Customize the visual appearance of the thank you 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 thank you page
          </p>
        </SettingsSection>
      </SettingsCard>

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

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

        <div className="flex items-center justify-between">
          <Label htmlFor="element-relatedProducts" className="cursor-pointer">
            Show related products
          </Label>
          <Switch
            id="element-related-products"
            checked={elements.related_products}
            onCheckedChange={() => toggleElement('related_products')}
          />
        </div>
      </SettingsCard>

      <SettingsCard
        title="Custom Message"
        description="Add a personalized message for customers after purchase"
      >
        <SettingsSection label="Message" htmlFor="custom-message">
          <Textarea
            id="custom-message"
            value={customMessage}
            onChange={(e) => setCustomMessage(e.target.value)}
            rows={4}
            placeholder="Thank you for your order!"
          />
        </SettingsSection>
      </SettingsCard>
    </SettingsLayout>
  );
}
