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 { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Plus, X, Upload, Trash2 } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/lib/api';
import { useModules } from '@/hooks/useModules';
import { MediaUploader } from '@/components/MediaUploader';
import { __ } from '@/lib/i18n';

interface SocialLink {
  id: string;
  platform: string;
  url: string;
}

interface FooterSection {
  id: string;
  title: string;
  type: 'menu' | 'contact' | 'social' | 'newsletter' | 'custom';
  content: any;
  visible: boolean;
}

interface ContactData {
  email: string;
  phone: string;
  address: string;
  show_email: boolean;
  show_phone: boolean;
  show_address: boolean;
}

interface PaymentMethod {
  id: string;
  url: string;
  label: string;
}

export default function AppearanceFooter() {
  const { isEnabled, isLoading: modulesLoading } = useModules();
  const [loading, setLoading] = useState(true);
  const [columns, setColumns] = useState('4');
  const [style, setStyle] = useState('detailed');

  const [copyright, setCopyright] = useState({
    enabled: true,
    text: '© 2024 WooNooW. All rights reserved.',
  });

  const [payment, setPayment] = useState<{
    enabled: boolean;
    title: string;
    methods: PaymentMethod[];
  }>({
    enabled: true,
    title: 'We accept',
    methods: []
  });

  // Legacy elements toggle (only for newsletter, social, menu, contact)
  const [elements, setElements] = useState({
    newsletter: true,
    social: true,
    menu: true,
    contact: true,
  });

  const [socialLinks, setSocialLinks] = useState<SocialLink[]>([]);
  const [sections, setSections] = useState<FooterSection[]>([]);
  const [contactData, setContactData] = useState<ContactData>({
    email: '',
    phone: '',
    address: '',
    show_email: true,
    show_phone: true,
    show_address: true,
  });

  const defaultSections: FooterSection[] = [
    { id: '1', title: 'Contact', type: 'contact', content: '', visible: true },
    { id: '2', title: 'Quick Links', type: 'menu', content: '', visible: true },
    { id: '3', title: 'Follow Us', type: 'social', content: '', visible: true },
    { id: '4', title: 'Newsletter', type: 'newsletter', content: '', visible: true },
  ];

  // Only keeping newsletter_description, titles are now managed per column
  const [labels, setLabels] = useState({
    newsletter_description: 'Subscribe to get updates',
  });

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await api.get('/appearance/settings');
        const footer = response.data?.footer;

        if (footer) {
          if (footer.columns) setColumns(footer.columns);
          if (footer.style) setStyle(footer.style);

          // Handle new structure vs backward compatibility
          if (footer.copyright) {
            setCopyright(footer.copyright);
          } else if (footer.copyright_text) {
            // Migration fallback
            setCopyright({
              enabled: footer.elements?.copyright ?? true,
              text: footer.copyright_text
            });
          }

          if (footer.payment) {
            setPayment(footer.payment);
          } else if (footer.elements?.payment) {
            // Migration fallback
            setPayment(prev => ({ ...prev, enabled: footer.elements.payment }));
          }

          if (footer.elements) {
            const { payment, copyright, ...rest } = footer.elements;
            setElements(prev => ({ ...prev, ...rest }));
          }

          if (footer.social_links) setSocialLinks(footer.social_links);
          if (footer.sections && footer.sections.length > 0) {
            setSections(footer.sections);
          } else {
            setSections(defaultSections);
          }
          if (footer.contact_data) setContactData(footer.contact_data);

          // Only sync description if it exists
          if (footer.labels?.newsletter_description) {
            setLabels({ newsletter_description: footer.labels.newsletter_description });
          }
        } else {
          setSections(defaultSections);
        }

        // Fetch store identity data
        try {
          const identityResponse = await api.get('/settings/store-identity');
          const identity = identityResponse.data;
          if (identity && !footer?.contact_data) {
            setContactData(prev => ({
              ...prev,
              email: identity.email || prev.email,
              phone: identity.phone || prev.phone,
              address: identity.address || prev.address,
            }));
          }
        } catch (err) {
          // Store identity endpoint is optional — silently ignore
        }
      } 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 addSocialLink = () => {
    setSocialLinks([
      ...socialLinks,
      { id: Date.now().toString(), platform: '', url: '' },
    ]);
  };

  const removeSocialLink = (id: string) => {
    setSocialLinks(socialLinks.filter(link => link.id !== id));
  };

  const updateSocialLink = (id: string, field: 'platform' | 'url', value: string) => {
    setSocialLinks(socialLinks.map(link =>
      link.id === id ? { ...link, [field]: value } : link
    ));
  };

  const addSection = () => {
    setSections([
      ...sections,
      {
        id: Date.now().toString(),
        title: 'New Column',
        type: 'custom',
        content: '',
        visible: true,
      },
    ]);
  };

  const removeSection = (id: string) => {
    setSections(sections.filter(s => s.id !== id));
  };

  const updateSection = (id: string, field: keyof FooterSection, value: any) => {
    setSections(sections.map(s => s.id === id ? { ...s, [field]: value } : s));
  };

  const addPaymentMethod = () => {
    setPayment({
      ...payment,
      methods: [...payment.methods, { id: Date.now().toString(), url: '', label: '' }]
    });
  };

  const removePaymentMethod = (id: string) => {
    setPayment({
      ...payment,
      methods: payment.methods.filter(m => m.id !== id)
    });
  };

  const updatePaymentMethod = (id: string, field: keyof PaymentMethod, value: string) => {
    setPayment({
      ...payment,
      methods: payment.methods.map(m => m.id === id ? { ...m, [field]: value } : m)
    });
  };

  const handleSave = async () => {
    try {
      const payload = {
        columns,
        style,
        copyright,
        payment,
        elements,
        socialLinks,
        sections,
        contactData,
        labels,
      };
      const response = await api.post('/appearance/footer', payload);
      toast.success('Footer settings saved successfully');
    } catch (error) {
      console.error('Save error:', error);
      toast.error('Failed to save settings');
    }
  };

  return (
    <SettingsLayout
      title="Footer Settings"
      onSave={handleSave}
      isLoading={loading}
    >
      {/* Layout */}
      <SettingsCard
        title="Layout"
        description="Configure footer layout and style"
      >
        <SettingsSection label="Columns" htmlFor="footer-columns">
          <Select value={columns} onValueChange={setColumns}>
            <SelectTrigger id="footer-columns">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="1">1 Column</SelectItem>
              <SelectItem value="2">2 Columns</SelectItem>
              <SelectItem value="3">3 Columns</SelectItem>
              <SelectItem value="4">4 Columns</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>

        <SettingsSection label="Style" htmlFor="footer-style">
          <Select value={style} onValueChange={setStyle}>
            <SelectTrigger id="footer-style">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="simple">Simple</SelectItem>
              <SelectItem value="detailed">Detailed</SelectItem>
              <SelectItem value="minimal">Minimal</SelectItem>
            </SelectContent>
          </Select>
        </SettingsSection>
      </SettingsCard>

      {/* Content & Contact */}
      <SettingsCard
        title="Content & Contact"
        description="Manage footer content and contact details"
      >
        <div className="space-y-6">
          <div>
            <h3 className="text-lg font-medium mb-4">Contact Information</h3>
            <SettingsSection label="Email" htmlFor="contact-email">
              <Input
                id="contact-email"
                type="email"
                value={contactData.email}
                onChange={(e) => setContactData({ ...contactData, email: e.target.value })}
                placeholder="info@store.com"
              />
              <div className="flex items-center gap-2 mt-2">
                <Switch
                  checked={contactData.show_email}
                  onCheckedChange={(checked) => setContactData({ ...contactData, show_email: checked })}
                />
                <Label className="text-sm text-muted-foreground">Show in footer</Label>
              </div>
            </SettingsSection>

            <SettingsSection label="Phone" htmlFor="contact-phone">
              <Input
                id="contact-phone"
                type="tel"
                value={contactData.phone}
                onChange={(e) => setContactData({ ...contactData, phone: e.target.value })}
                placeholder="(123) 456-7890"
              />
              <div className="flex items-center gap-2 mt-2">
                <Switch
                  checked={contactData.show_phone}
                  onCheckedChange={(checked) => setContactData({ ...contactData, show_phone: checked })}
                />
                <Label className="text-sm text-muted-foreground">Show in footer</Label>
              </div>
            </SettingsSection>

            <SettingsSection label="Address" htmlFor="contact-address">
              <Textarea
                id="contact-address"
                value={contactData.address}
                onChange={(e) => setContactData({ ...contactData, address: e.target.value })}
                placeholder="123 Main St, City, State 12345"
                rows={2}
              />
              <div className="flex items-center gap-2 mt-2">
                <Switch
                  checked={contactData.show_address}
                  onCheckedChange={(checked) => setContactData({ ...contactData, show_address: checked })}
                />
                <Label className="text-sm text-muted-foreground">Show in footer</Label>
              </div>
            </SettingsSection>
          </div>

          <div className="border-t pt-6">
            <h3 className="text-lg font-medium mb-4">General Content</h3>
            <SettingsSection label="Newsletter Description" htmlFor="newsletter-desc">
              <Input
                id="newsletter-desc"
                value={labels.newsletter_description}
                onChange={(e) => setLabels({ ...labels, newsletter_description: e.target.value })}
                placeholder="Subscribe to get updates"
              />
            </SettingsSection>

            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>Social Media Links</Label>
                <Button onClick={addSocialLink} variant="outline" size="sm">
                  <Plus className="mr-2 h-4 w-4" />
                  Add Link
                </Button>
              </div>

              <div className="space-y-3">
                {socialLinks.map((link) => (
                  <div key={link.id} className="flex gap-2">
                    <Input
                      placeholder="Platform (e.g., Facebook)"
                      value={link.platform}
                      onChange={(e) => updateSocialLink(link.id, 'platform', e.target.value)}
                      className="flex-1"
                    />
                    <Input
                      placeholder="URL"
                      value={link.url}
                      onChange={(e) => updateSocialLink(link.id, 'url', e.target.value)}
                      className="flex-1"
                    />
                    <Button
                      onClick={() => removeSocialLink(link.id)}
                      variant="ghost"
                      size="icon"
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </SettingsCard>

      {/* Custom Columns (was Custom Sections) */}
      <SettingsCard
        title="Custom Columns"
        description="Build footer columns with flexible content"
      >
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <Label>Footer Columns</Label>
            <Button onClick={addSection} variant="outline" size="sm">
              <Plus className="mr-2 h-4 w-4" />
              Add Column
            </Button>
          </div>

          {sections.map((section) => (
            <div key={section.id} className="border rounded-lg p-4 space-y-3">
              <div className="flex items-center justify-between">
                <Input
                  placeholder="Column Title"
                  value={section.title}
                  onChange={(e) => updateSection(section.id, 'title', e.target.value)}
                  className="flex-1 mr-2"
                />
                <Button
                  onClick={() => removeSection(section.id)}
                  variant="ghost"
                  size="icon"
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>

              <Select
                value={section.type}
                onValueChange={(value) => updateSection(section.id, 'type', value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="menu">Menu Links</SelectItem>
                  <SelectItem value="contact">Contact Info</SelectItem>
                  <SelectItem value="social">Social Links</SelectItem>
                  {isEnabled('newsletter') && (
                    <SelectItem value="newsletter">Newsletter Form</SelectItem>
                  )}
                  <SelectItem value="custom">Custom HTML</SelectItem>
                </SelectContent>
              </Select>

              {section.type === 'custom' && (
                <Textarea
                  placeholder="Custom content (HTML supported)"
                  value={section.content}
                  onChange={(e) => updateSection(section.id, 'content', e.target.value)}
                  rows={4}
                />
              )}

              <div className="flex items-center gap-2">
                <Switch
                  checked={section.visible}
                  onCheckedChange={(checked) => updateSection(section.id, 'visible', checked)}
                />
                <Label className="text-sm text-muted-foreground">Visible</Label>
              </div>
            </div>
          ))}

          {sections.length === 0 && (
            <p className="text-sm text-muted-foreground text-center py-4">
              No custom columns yet. Click "Add Column" to create one.
            </p>
          )}
        </div>
      </SettingsCard>

      {/* Payment Methods */}
      <SettingsCard
        title="Payment Methods"
        description="Configure accepted payment methods display"
      >
        <div className="flex items-center justify-between mb-4">
          <div className="space-y-0.5">
            <Label>Show Payment Methods</Label>
          </div>
          <Switch
            checked={payment.enabled}
            onCheckedChange={(checked) => setPayment({ ...payment, enabled: checked })}
          />
        </div>

        {payment.enabled && (
          <div className="space-y-4">
            <SettingsSection label="Section Title" htmlFor="payment-title">
              <Input
                id="payment-title"
                value={payment.title}
                onChange={(e) => setPayment({ ...payment, title: e.target.value })}
                placeholder="We accept"
              />
            </SettingsSection>

            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>Payment Logos</Label>
                <Button onClick={addPaymentMethod} variant="outline" size="sm">
                  <Plus className="mr-2 h-4 w-4" />
                  Add Method
                </Button>
              </div>

              <div className="grid gap-3">
                {payment.methods.map((method) => (
                  <div key={method.id} className="flex gap-3 items-center border p-3 rounded-lg">
                    <div className="shrink-0">
                      <MediaUploader
                        onSelect={(url) => updatePaymentMethod(method.id, 'url', url)}
                      >
                        {method.url ? (
                          <div className="w-12 h-8 border rounded overflow-hidden relative group cursor-pointer">
                            <img src={method.url} alt={method.label} className="w-full h-full object-contain" />
                            <div className="absolute inset-0 bg-black/40 hidden group-hover:flex items-center justify-center">
                              <Upload className="w-3 h-3 text-white" />
                            </div>
                          </div>
                        ) : (
                          <div className="w-12 h-8 border rounded bg-muted flex items-center justify-center cursor-pointer hover:bg-muted/80">
                            <Upload className="w-4 h-4 text-muted-foreground" />
                          </div>
                        )}
                      </MediaUploader>
                    </div>
                    <Input
                      placeholder="Label (e.g., Visa)"
                      value={method.label}
                      onChange={(e) => updatePaymentMethod(method.id, 'label', e.target.value)}
                      className="flex-1"
                    />
                    <Button
                      onClick={() => removePaymentMethod(method.id)}
                      variant="ghost"
                      size="icon"
                      className="shrink-0 text-destructive hover:text-destructive"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                ))}
                {payment.methods.length === 0 && (
                  <div className="text-sm text-center py-4 text-muted-foreground bg-muted/20 rounded-lg border border-dashed">
                    No payment methods added.
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </SettingsCard>

      {/* Copyright Section */}
      <SettingsCard
        title="Copyright"
        description="Configure copyright notice"
      >
        <div className="flex items-center justify-between mb-4">
          <div className="space-y-0.5">
            <Label>Show Copyright</Label>
          </div>
          <Switch
            checked={copyright.enabled}
            onCheckedChange={(checked) => setCopyright({ ...copyright, enabled: checked })}
          />
        </div>

        {copyright.enabled && (
          <SettingsSection label="Copyright Text" htmlFor="copyright-text">
            <Textarea
              id="copyright-text"
              value={copyright.text}
              onChange={(e) => setCopyright({ ...copyright, text: e.target.value })}
              rows={2}
              placeholder="© 2024 Your Store. All rights reserved."
            />
          </SettingsSection>
        )}
      </SettingsCard>
    </SettingsLayout>
  );
}
