'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useLanguage } from '@/context/LanguageContext';
import { siteSettingsApi, eventsApi, legalSettingsApi, SiteSettings, TimezoneOption, Event, LegalSettingsData } from '@/lib/api';
import { parseDate } from '@/lib/utils';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import {
  Cog6ToothIcon,
  GlobeAltIcon,
  ClockIcon,
  EnvelopeIcon,
  WrenchScrewdriverIcon,
  CheckCircleIcon,
  StarIcon,
  ScaleIcon,
} from '@heroicons/react/24/outline';
import toast from 'react-hot-toast';

type SettingsTab = 'general' | 'legal';

export default function AdminSettingsPage() {
  const { t, locale } = useLanguage();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [savingLegal, setSavingLegal] = useState(false);
  const [activeTab, setActiveTab] = useState<SettingsTab>('general');
  const [timezones, setTimezones] = useState<TimezoneOption[]>([]);
  const [featuredEvent, setFeaturedEvent] = useState<Event | null>(null);
  const [clearingFeatured, setClearingFeatured] = useState(false);
  
  const [settings, setSettings] = useState<SiteSettings>({
    timezone: 'America/Asuncion',
    siteName: 'Spanglish',
    siteDescription: null,
    siteDescriptionEs: null,
    contactEmail: null,
    contactPhone: null,
    facebookUrl: null,
    instagramUrl: null,
    twitterUrl: null,
    linkedinUrl: null,
    featuredEventId: null,
    maintenanceMode: false,
    maintenanceMessage: null,
    maintenanceMessageEs: null,
  });

  const [legalSettings, setLegalSettings] = useState<LegalSettingsData>({
    companyName: null,
    legalEntityName: null,
    rucNumber: null,
    companyAddress: null,
    companyCity: null,
    companyCountry: null,
    supportEmail: null,
    legalEmail: null,
    governingLaw: null,
    jurisdictionCity: null,
  });

  const [legalErrors, setLegalErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const [settingsRes, timezonesRes, legalRes] = await Promise.all([
        siteSettingsApi.get(),
        siteSettingsApi.getTimezones(),
        legalSettingsApi.get().catch(() => ({ settings: {} as LegalSettingsData })),
      ]);
      setSettings(settingsRes.settings);
      setTimezones(timezonesRes.timezones);
      setLegalSettings(legalRes.settings);
      
      // Load featured event details if one is set
      if (settingsRes.settings.featuredEventId) {
        try {
          const { event } = await eventsApi.getById(settingsRes.settings.featuredEventId);
          setFeaturedEvent(event);
        } catch {
          // Featured event may no longer exist
          setFeaturedEvent(null);
        }
      }
    } catch (error) {
      toast.error('Failed to load settings');
    } finally {
      setLoading(false);
    }
  };

  const handleClearFeatured = async () => {
    setClearingFeatured(true);
    try {
      await siteSettingsApi.setFeaturedEvent(null);
      setSettings(prev => ({ ...prev, featuredEventId: null }));
      setFeaturedEvent(null);
      toast.success(locale === 'es' ? 'Evento destacado eliminado' : 'Featured event removed');
    } catch (error: any) {
      toast.error(error.message || 'Failed to clear featured event');
    } finally {
      setClearingFeatured(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const response = await siteSettingsApi.update(settings);
      setSettings(response.settings);
      toast.success(locale === 'es' ? 'Configuración guardada' : 'Settings saved');
    } catch (error: any) {
      toast.error(error.message || 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const validateLegalSettings = (): boolean => {
    const errors: Record<string, string> = {};

    // Validate email formats if provided
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (legalSettings.supportEmail && !emailRegex.test(legalSettings.supportEmail)) {
      errors.supportEmail = locale === 'es' ? 'Email no válido' : 'Invalid email address';
    }
    if (legalSettings.legalEmail && !emailRegex.test(legalSettings.legalEmail)) {
      errors.legalEmail = locale === 'es' ? 'Email no válido' : 'Invalid email address';
    }

    setLegalErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSaveLegal = async () => {
    if (!validateLegalSettings()) return;

    setSavingLegal(true);
    try {
      const response = await legalSettingsApi.update(legalSettings);
      setLegalSettings(response.settings);
      toast.success(locale === 'es' ? 'Configuración legal guardada' : 'Legal settings saved');
    } catch (error: any) {
      toast.error(error.message || 'Failed to save legal settings');
    } finally {
      setSavingLegal(false);
    }
  };

  const updateSetting = <K extends keyof SiteSettings>(key: K, value: SiteSettings[K]) => {
    setSettings((prev) => ({ ...prev, [key]: value }));
  };

  const updateLegalSetting = <K extends keyof LegalSettingsData>(key: K, value: LegalSettingsData[K]) => {
    setLegalSettings((prev) => ({ ...prev, [key]: value }));
    // Clear error for this field when user types
    if (legalErrors[key]) {
      setLegalErrors((prev) => {
        const next = { ...prev };
        delete next[key];
        return next;
      });
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin w-8 h-8 border-4 border-primary-yellow border-t-transparent rounded-full" />
      </div>
    );
  }

  const tabs: { id: SettingsTab; label: string; labelEs: string; icon: React.ReactNode }[] = [
    {
      id: 'general',
      label: 'General Settings',
      labelEs: 'Configuración General',
      icon: <Cog6ToothIcon className="w-4 h-4" />,
    },
    {
      id: 'legal',
      label: 'Legal Settings',
      labelEs: 'Configuración Legal',
      icon: <ScaleIcon className="w-4 h-4" />,
    },
  ];

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-primary-dark flex items-center gap-3">
            <Cog6ToothIcon className="w-7 h-7" />
            {locale === 'es' ? 'Configuración del Sitio' : 'Site Settings'}
          </h1>
          <p className="text-gray-500 mt-1">
            {locale === 'es' 
              ? 'Configura las opciones generales del sitio web' 
              : 'Configure general website settings'}
          </p>
        </div>
        {activeTab === 'general' && (
          <Button onClick={handleSave} isLoading={saving}>
            <CheckCircleIcon className="w-5 h-5 mr-2" />
            {locale === 'es' ? 'Guardar Cambios' : 'Save Changes'}
          </Button>
        )}
        {activeTab === 'legal' && (
          <Button onClick={handleSaveLegal} isLoading={savingLegal}>
            <CheckCircleIcon className="w-5 h-5 mr-2" />
            {locale === 'es' ? 'Guardar Cambios' : 'Save Changes'}
          </Button>
        )}
      </div>

      {/* Tabs */}
      <div className="border-b border-secondary-light-gray mb-6">
        <nav className="flex space-x-0" aria-label="Tabs">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-3 border-b-2 text-sm font-medium transition-colors ${
                activeTab === tab.id
                  ? 'border-primary-yellow text-primary-dark'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              {tab.icon}
              {locale === 'es' ? tab.labelEs : tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* General Settings Tab */}
      {activeTab === 'general' && (
        <div className="space-y-6">
          {/* Timezone Settings */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                  <ClockIcon className="w-5 h-5 text-blue-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Zona Horaria' : 'Timezone'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es' 
                      ? 'Zona horaria para mostrar las fechas de eventos' 
                      : 'Timezone used for displaying event dates'}
                  </p>
                </div>
              </div>

              <div className="max-w-md">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {locale === 'es' ? 'Zona Horaria del Sitio' : 'Site Timezone'}
                </label>
                <select
                  value={settings.timezone}
                  onChange={(e) => updateSetting('timezone', e.target.value)}
                  className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
                >
                  {timezones.map((tz) => (
                    <option key={tz.value} value={tz.value}>
                      {tz.label}
                    </option>
                  ))}
                </select>
                <p className="text-xs text-gray-400 mt-1">
                  {locale === 'es' 
                    ? 'Esta zona horaria se usará como referencia para las fechas de eventos.'
                    : 'This timezone will be used as reference for event dates.'}
                </p>
              </div>
            </div>
          </Card>

          {/* Featured Event */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center">
                  <StarIcon className="w-5 h-5 text-amber-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Evento Destacado' : 'Featured Event'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es' 
                      ? 'El evento destacado aparece en la página de inicio y linktree' 
                      : 'The featured event is displayed on the homepage and linktree'}
                  </p>
                </div>
              </div>

              {featuredEvent ? (
                <div className="bg-amber-50 border border-amber-200 rounded-lg p-4">
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex items-center gap-3">
                      {featuredEvent.bannerUrl && (
                        <img 
                          src={featuredEvent.bannerUrl} 
                          alt={featuredEvent.title}
                          className="w-16 h-16 rounded-lg object-cover"
                        />
                      )}
                      <div>
                        <p className="font-medium text-amber-900">{featuredEvent.title}</p>
                        <p className="text-sm text-amber-700">
                          {parseDate(featuredEvent.startDatetime).toLocaleDateString(locale === 'es' ? 'es-ES' : 'en-US', {
                            month: 'long',
                            day: 'numeric',
                            year: 'numeric',
                            timeZone: 'America/Asuncion',
                          })}
                        </p>
                        <p className="text-xs text-amber-600 mt-1">
                          {locale === 'es' ? 'Estado:' : 'Status:'} {featuredEvent.status}
                        </p>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Link 
                        href="/admin/events"
                        className="text-sm text-amber-700 hover:text-amber-900 underline"
                      >
                        {locale === 'es' ? 'Cambiar' : 'Change'}
                      </Link>
                      <button
                        onClick={handleClearFeatured}
                        disabled={clearingFeatured}
                        className="text-sm text-red-600 hover:text-red-800 underline disabled:opacity-50"
                      >
                        {clearingFeatured 
                          ? (locale === 'es' ? 'Eliminando...' : 'Removing...') 
                          : (locale === 'es' ? 'Eliminar' : 'Remove')}
                      </button>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
                  <p className="text-gray-600 mb-3">
                    {locale === 'es' 
                      ? 'No hay evento destacado. El próximo evento publicado se mostrará automáticamente.' 
                      : 'No featured event set. The next upcoming published event will be shown automatically.'}
                  </p>
                  <Link 
                    href="/admin/events"
                    className="text-sm text-primary-yellow hover:underline font-medium"
                  >
                    {locale === 'es' ? 'Ir a Eventos para destacar uno' : 'Go to Events to feature one'}
                  </Link>
                </div>
              )}

              <p className="text-xs text-gray-400 mt-3">
                {locale === 'es' 
                  ? 'Cuando el evento destacado termine o se despublique, el sistema mostrará automáticamente el próximo evento.' 
                  : 'When the featured event ends or is unpublished, the system will automatically show the next upcoming event.'}
              </p>
            </div>
          </Card>

          {/* Site Information */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                  <GlobeAltIcon className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Información del Sitio' : 'Site Information'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es' 
                      ? 'Información básica del sitio web' 
                      : 'Basic website information'}
                  </p>
                </div>
              </div>

              <div className="space-y-4">
                <div className="max-w-md">
                  <Input
                    label={locale === 'es' ? 'Nombre del Sitio' : 'Site Name'}
                    value={settings.siteName}
                    onChange={(e) => updateSetting('siteName', e.target.value)}
                    placeholder="Spanglish"
                  />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      {locale === 'es' ? 'Descripción (Inglés)' : 'Description (English)'}
                    </label>
                    <textarea
                      value={settings.siteDescription || ''}
                      onChange={(e) => updateSetting('siteDescription', e.target.value || null)}
                      rows={3}
                      className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
                      placeholder="Brief site description..."
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      {locale === 'es' ? 'Descripción (Español)' : 'Description (Spanish)'}
                    </label>
                    <textarea
                      value={settings.siteDescriptionEs || ''}
                      onChange={(e) => updateSetting('siteDescriptionEs', e.target.value || null)}
                      rows={3}
                      className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
                      placeholder="Descripción breve del sitio..."
                    />
                  </div>
                </div>
              </div>
            </div>
          </Card>

          {/* Contact Information */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center">
                  <EnvelopeIcon className="w-5 h-5 text-purple-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Información de Contacto' : 'Contact Information'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es' 
                      ? 'Datos de contacto del sitio' 
                      : 'Site contact details'}
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Input
                  label={locale === 'es' ? 'Email de Contacto' : 'Contact Email'}
                  type="email"
                  value={settings.contactEmail || ''}
                  onChange={(e) => updateSetting('contactEmail', e.target.value || null)}
                  placeholder="contact@example.com"
                />
                <Input
                  label={locale === 'es' ? 'Teléfono de Contacto' : 'Contact Phone'}
                  type="tel"
                  value={settings.contactPhone || ''}
                  onChange={(e) => updateSetting('contactPhone', e.target.value || null)}
                  placeholder="+595 981 123456"
                />
              </div>

              <div className="mt-6 pt-6 border-t border-secondary-light-gray">
                <h4 className="font-medium mb-4">
                  {locale === 'es' ? 'Redes Sociales' : 'Social Media Links'}
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Input
                    label="Facebook URL"
                    type="url"
                    value={settings.facebookUrl || ''}
                    onChange={(e) => updateSetting('facebookUrl', e.target.value || null)}
                    placeholder="https://facebook.com/..."
                  />
                  <Input
                    label="Instagram URL"
                    type="url"
                    value={settings.instagramUrl || ''}
                    onChange={(e) => updateSetting('instagramUrl', e.target.value || null)}
                    placeholder="https://instagram.com/..."
                  />
                  <Input
                    label="Twitter URL"
                    type="url"
                    value={settings.twitterUrl || ''}
                    onChange={(e) => updateSetting('twitterUrl', e.target.value || null)}
                    placeholder="https://twitter.com/..."
                  />
                  <Input
                    label="LinkedIn URL"
                    type="url"
                    value={settings.linkedinUrl || ''}
                    onChange={(e) => updateSetting('linkedinUrl', e.target.value || null)}
                    placeholder="https://linkedin.com/..."
                  />
                </div>
              </div>
            </div>
          </Card>

          {/* Maintenance Mode */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-orange-100 rounded-full flex items-center justify-center">
                  <WrenchScrewdriverIcon className="w-5 h-5 text-orange-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Modo de Mantenimiento' : 'Maintenance Mode'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es' 
                      ? 'Habilita el modo de mantenimiento cuando necesites hacer cambios' 
                      : 'Enable maintenance mode when you need to make changes'}
                  </p>
                </div>
              </div>

              <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg mb-4">
                <div>
                  <p className="font-medium">
                    {locale === 'es' ? 'Modo de Mantenimiento' : 'Maintenance Mode'}
                  </p>
                  <p className="text-sm text-gray-500">
                    {settings.maintenanceMode 
                      ? (locale === 'es' ? 'El sitio está en mantenimiento' : 'The site is under maintenance')
                      : (locale === 'es' ? 'El sitio está activo' : 'The site is live')}
                  </p>
                </div>
                <button
                  onClick={() => updateSetting('maintenanceMode', !settings.maintenanceMode)}
                  className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                    settings.maintenanceMode ? 'bg-orange-500' : 'bg-gray-300'
                  }`}
                >
                  <span
                    className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                      settings.maintenanceMode ? 'translate-x-6' : 'translate-x-1'
                    }`}
                  />
                </button>
              </div>

              {settings.maintenanceMode && (
                <div className="bg-orange-50 border border-orange-200 rounded-lg p-4 mb-4">
                  <p className="text-orange-800 text-sm font-medium flex items-center gap-2">
                    <WrenchScrewdriverIcon className="w-4 h-4" />
                    {locale === 'es' 
                      ? '¡Advertencia! El modo de mantenimiento está activo.' 
                      : 'Warning! Maintenance mode is active.'}
                  </p>
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {locale === 'es' ? 'Mensaje de Mantenimiento (Inglés)' : 'Maintenance Message (English)'}
                  </label>
                  <textarea
                    value={settings.maintenanceMessage || ''}
                    onChange={(e) => updateSetting('maintenanceMessage', e.target.value || null)}
                    rows={3}
                    className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
                    placeholder="We are currently performing maintenance. Please check back soon."
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {locale === 'es' ? 'Mensaje de Mantenimiento (Español)' : 'Maintenance Message (Spanish)'}
                  </label>
                  <textarea
                    value={settings.maintenanceMessageEs || ''}
                    onChange={(e) => updateSetting('maintenanceMessageEs', e.target.value || null)}
                    rows={3}
                    className="w-full px-4 py-3 rounded-btn border border-secondary-light-gray focus:outline-none focus:ring-2 focus:ring-primary-yellow"
                    placeholder="Estamos realizando mantenimiento. Por favor vuelve pronto."
                  />
                </div>
              </div>
            </div>
          </Card>

          {/* Save Button at Bottom */}
          <div className="flex justify-end">
            <Button onClick={handleSave} isLoading={saving} size="lg">
              <CheckCircleIcon className="w-5 h-5 mr-2" />
              {locale === 'es' ? 'Guardar Todos los Cambios' : 'Save All Changes'}
            </Button>
          </div>
        </div>
      )}

      {/* Legal Settings Tab */}
      {activeTab === 'legal' && (
        <div className="space-y-6">
          {/* Info Banner */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <p className="text-blue-800 text-sm">
              <span className="font-medium">
                {locale === 'es' ? 'Nota:' : 'Note:'}
              </span>{' '}
              {locale === 'es'
                ? 'Estos valores se usan como marcadores de posición en las páginas legales. Los marcadores como {{COMPANY_NAME}} se reemplazan automáticamente con los valores configurados aquí.'
                : 'These values are used as placeholders in legal pages. Placeholders like {{COMPANY_NAME}} are automatically replaced with the values configured here.'}
            </p>
          </div>

          {/* Company Information */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-indigo-100 rounded-full flex items-center justify-center">
                  <ScaleIcon className="w-5 h-5 text-indigo-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Información de la Empresa' : 'Company Information'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es'
                      ? 'Datos legales de la empresa que aparecerán en las páginas legales'
                      : 'Legal company details that will appear in legal pages'}
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Input
                  label={locale === 'es' ? 'Nombre de la Empresa' : 'Company Name'}
                  value={legalSettings.companyName || ''}
                  onChange={(e) => updateLegalSetting('companyName', e.target.value || null)}
                  placeholder={locale === 'es' ? 'Ej: Spanglish S.A.' : 'e.g. Spanglish S.A.'}
                />
                <Input
                  label={locale === 'es' ? 'Nombre de la Entidad Legal' : 'Legal Entity Name'}
                  value={legalSettings.legalEntityName || ''}
                  onChange={(e) => updateLegalSetting('legalEntityName', e.target.value || null)}
                  placeholder={locale === 'es' ? 'Ej: Spanglish S.A.' : 'e.g. Spanglish S.A.'}
                />
                <Input
                  label={locale === 'es' ? 'Número de RUC' : 'RUC Number'}
                  value={legalSettings.rucNumber || ''}
                  onChange={(e) => updateLegalSetting('rucNumber', e.target.value || null)}
                  placeholder={locale === 'es' ? 'Ej: 80012345-6' : 'e.g. 80012345-6'}
                />
              </div>
            </div>
          </Card>

          {/* Address & Location */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-teal-100 rounded-full flex items-center justify-center">
                  <GlobeAltIcon className="w-5 h-5 text-teal-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Dirección y Ubicación' : 'Address & Location'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es'
                      ? 'Dirección física y jurisdicción legal'
                      : 'Physical address and legal jurisdiction'}
                  </p>
                </div>
              </div>

              <div className="space-y-4">
                <div className="max-w-lg">
                  <Input
                    label={locale === 'es' ? 'Dirección de la Empresa' : 'Company Address'}
                    value={legalSettings.companyAddress || ''}
                    onChange={(e) => updateLegalSetting('companyAddress', e.target.value || null)}
                    placeholder={locale === 'es' ? 'Ej: Av. Mariscal López 1234' : 'e.g. 1234 Main Street'}
                  />
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <Input
                    label={locale === 'es' ? 'Ciudad' : 'City'}
                    value={legalSettings.companyCity || ''}
                    onChange={(e) => updateLegalSetting('companyCity', e.target.value || null)}
                    placeholder={locale === 'es' ? 'Ej: Asunción' : 'e.g. Asunción'}
                  />
                  <Input
                    label={locale === 'es' ? 'País' : 'Country'}
                    value={legalSettings.companyCountry || ''}
                    onChange={(e) => updateLegalSetting('companyCountry', e.target.value || null)}
                    placeholder={locale === 'es' ? 'Ej: Paraguay' : 'e.g. Paraguay'}
                  />
                </div>
              </div>
            </div>
          </Card>

          {/* Contact Emails */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-rose-100 rounded-full flex items-center justify-center">
                  <EnvelopeIcon className="w-5 h-5 text-rose-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Emails Legales' : 'Legal Emails'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es'
                      ? 'Direcciones de email para asuntos legales y soporte'
                      : 'Email addresses for legal matters and support'}
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Input
                  label={locale === 'es' ? 'Email de Soporte' : 'Support Email'}
                  type="email"
                  value={legalSettings.supportEmail || ''}
                  onChange={(e) => updateLegalSetting('supportEmail', e.target.value || null)}
                  placeholder="support@example.com"
                  error={legalErrors.supportEmail}
                />
                <Input
                  label={locale === 'es' ? 'Email Legal' : 'Legal Email'}
                  type="email"
                  value={legalSettings.legalEmail || ''}
                  onChange={(e) => updateLegalSetting('legalEmail', e.target.value || null)}
                  placeholder="legal@example.com"
                  error={legalErrors.legalEmail}
                />
              </div>
            </div>
          </Card>

          {/* Legal Jurisdiction */}
          <Card>
            <div className="p-6">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center">
                  <ScaleIcon className="w-5 h-5 text-amber-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-lg">
                    {locale === 'es' ? 'Jurisdicción Legal' : 'Legal Jurisdiction'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {locale === 'es'
                      ? 'Ley aplicable y jurisdicción para las páginas legales'
                      : 'Governing law and jurisdiction for legal pages'}
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <Input
                  label={locale === 'es' ? 'Ley Aplicable' : 'Governing Law'}
                  value={legalSettings.governingLaw || ''}
                  onChange={(e) => updateLegalSetting('governingLaw', e.target.value || null)}
                  placeholder={locale === 'es' ? 'Ej: las leyes de la República del Paraguay' : 'e.g. the laws of the Republic of Paraguay'}
                />
                <Input
                  label={locale === 'es' ? 'Ciudad de Jurisdicción' : 'Jurisdiction City'}
                  value={legalSettings.jurisdictionCity || ''}
                  onChange={(e) => updateLegalSetting('jurisdictionCity', e.target.value || null)}
                  placeholder={locale === 'es' ? 'Ej: Asunción' : 'e.g. Asunción'}
                />
              </div>
            </div>
          </Card>

          {/* Save Button at Bottom */}
          <div className="flex justify-end">
            <Button onClick={handleSaveLegal} isLoading={savingLegal} size="lg">
              <CheckCircleIcon className="w-5 h-5 mr-2" />
              {locale === 'es' ? 'Guardar Configuración Legal' : 'Save Legal Settings'}
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
