'use client';

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { GeneralSettings, generalSettingsSchema } from '@/lib/validations/settings.validation';

// Import all tab components
import { GeneralTab } from './tabs/GeneralTab';
import { BrandingTab } from './tabs/BrandingTab';
import { ContactTab } from './tabs/ContactTab';
import { SocialTab } from './tabs/SocialTab';
import { OrderTab } from './tabs/OrderTab';
import { DeliveryTab } from './tabs/DeliveryTab';
import { ReferralTab } from './tabs/ReferralTab';
import { SEOTab } from './tabs/SEOTab';
import { AnalyticsTab } from './tabs/AnalyticsTab';
import { LegalTab } from './tabs/LegalTab';
import { SMTPTab } from './tabs/SMTPTab';
import { ReviewsTab } from './tabs/ReviewsTab';
import { SocialLoginTab } from './tabs/SocialLoginTab';
import { PaymentTab } from './tabs/PaymentTab';
import { getApiErrorMessage } from '@/lib/utils/apiError';

// ─── Icons ───────────────────────────────────────────────────────────────────

function SettingsIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
  </svg>;
}

function PaletteIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
  </svg>;
}

function PhoneIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
  </svg>;
}

function ShareIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
  </svg>;
}

function ShoppingCartIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
  </svg>;
}

function TruckIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
  </svg>;
}

function GiftIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5.5A2.5 2.5 0 109.5 8H12zm-7 4h14M5 12a2 2 0 110-4h14a2 2 0 110 4M5 12v7a2 2 0 002 2h10a2 2 0 002-2v-7" />
  </svg>;
}

function SearchIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
  </svg>;
}

function ChartIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
  </svg>;
}

function FileIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
  </svg>;
}

function MailIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
  </svg>;
}

function StarIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
  </svg>;
}

function UsersIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
  </svg>;
}

function CreditCardIcon() { 
  return <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
  </svg>;
}

// ─── Tab Configuration ──────────────────────────────────────────────────────

const TABS = [
  { id: 'general', label: 'General', icon: <SettingsIcon />, component: GeneralTab },
  { id: 'branding', label: 'Branding', icon: <PaletteIcon />, component: BrandingTab },
  { id: 'contact', label: 'Contact', icon: <PhoneIcon />, component: ContactTab },
  { id: 'social', label: 'Social Media', icon: <ShareIcon />, component: SocialTab },
  { id: 'order', label: 'Order & Pricing', icon: <ShoppingCartIcon />, component: OrderTab },
  { id: 'delivery', label: 'Delivery', icon: <TruckIcon />, component: DeliveryTab },
  { id: 'referral', label: 'Referral', icon: <GiftIcon />, component: ReferralTab },
  { id: 'seo', label: 'SEO', icon: <SearchIcon />, component: SEOTab },
  { id: 'analytics', label: 'Analytics', icon: <ChartIcon />, component: AnalyticsTab },
  { id: 'legal', label: 'Legal Pages', icon: <FileIcon />, component: LegalTab },
  { id: 'smtp', label: 'SMTP', icon: <MailIcon />, component: SMTPTab },
  { id: 'reviews', label: 'Reviews', icon: <StarIcon />, component: ReviewsTab },
  { id: 'social-login', label: 'Social Login', icon: <UsersIcon />, component: SocialLoginTab },
  { id: 'payment', label: 'Payment Gateways', icon: <CreditCardIcon />, component: PaymentTab },
];

// ─── Main Component ──────────────────────────────────────────────────────────

interface SettingsFormProps {
  initialData: GeneralSettings;
  canUpdate: boolean;
}

export default function SettingsForm({ initialData, canUpdate }: SettingsFormProps) {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState('general');
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState<GeneralSettings>(initialData);
  const [errors, setErrors] = useState<Record<string, string>>({});

  // ─── Handlers ─────────────────────────────────────────────────────────────

  const handleChange = useCallback((field: keyof GeneralSettings, value: unknown) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    
    // Clear error for this field
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  }, [errors]);

  const handleToggle = useCallback((field: keyof GeneralSettings) => {
    setFormData(prev => {
      const currentValue = prev[field];
      // Handle boolean toggle properly
      if (typeof currentValue === 'boolean') {
        return { ...prev, [field]: !currentValue };
      }
      // If it's undefined or null, default to true
      return { ...prev, [field]: true };
    });
  }, []);

  const handleArrayToggle = useCallback((field: keyof GeneralSettings, value: string) => {
    setFormData(prev => {
      const current = (prev[field] as string[]) || [];
      const newArray = current.includes(value)
        ? current.filter(item => item !== value)
        : [...current, value];
      return { ...prev, [field]: newArray };
    });
  }, []);

  // ─── Submit Handler ──────────────────────────────────────────────────────

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!canUpdate) {
      toast.error('You do not have permission to update settings');
      return;
    }

    setLoading(true);
    setErrors({});

    try {
      // z.coerce automatically handles type conversion
      const validated = generalSettingsSchema.parse(formData);

      const res = await fetch('/api/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(validated),
      });

      const data = await res.json();

      if (!res.ok || !data.success) {
        if (data.errors) {
          const errorMap: Record<string, string> = {};
          if (Array.isArray(data.errors)) {
            data.errors.forEach((err: { path: string[]; message: string }) => {
              if (err.path) {
                errorMap[err.path.join('.')] = err.message;
              }
            });
          }
          setErrors(errorMap);
          toast.error('Please fix the validation errors');
        } else {
          toast.error(getApiErrorMessage(data, 'Failed to update settings'));
        }
        return;
      }

      toast.success('Settings updated successfully!');
      router.refresh();
    } catch (err: any) {
      console.error('[SettingsForm]', err);
      
      // Handle Zod errors
      if (err.name === 'ZodError') {
        const errorMap: Record<string, string> = {};
        err.errors.forEach((e: any) => {
          if (e.path) {
            errorMap[e.path.join('.')] = e.message;
          }
        });
        setErrors(errorMap);
        toast.error('Please fix the validation errors');
      } else {
        toast.error('Network error — please try again');
      }
    } finally {
      setLoading(false);
    }
  };

  // ─── Render ──────────────────────────────────────────────────────────────

  const CurrentTabComponent = TABS.find(t => t.id === activeTab)?.component || GeneralTab;

  return (
    <div className="flex flex-col lg:flex-row gap-6">
      {/* Left Sidebar - Tabs */}
      <div className="lg:w-64 shrink-0">
        <div className="sticky top-6 space-y-1">
          {TABS.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`w-full flex items-center gap-2 px-3 py-2.5 rounded-lg text-sm font-medium transition-all ${
                activeTab === tab.id
                  ? 'bg-cta text-white'
                  : 'hover:bg-surface-alt text-text-secondary hover:text-text'
              }`}
              style={{
                background: activeTab === tab.id ? 'var(--color-cta)' : 'transparent',
                color: activeTab === tab.id ? 'white' : 'var(--color-text-secondary)',
              }}
            >
              <span className="shrink-0">{tab.icon}</span>
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      {/* Right Content - Form */}
      <div className="flex-1">
        <form onSubmit={handleSubmit}>
          <div
            className="p-6 rounded-lg"
            style={{
              background: 'var(--color-surface)',
              border: '1px solid var(--color-border)',
              borderRadius: 'var(--radius-card)',
            }}
          >
            <h2 className="text-lg font-semibold mb-6" style={{ color: 'var(--color-text)' }}>
              {TABS.find(t => t.id === activeTab)?.label}
            </h2>

            <CurrentTabComponent
              data={formData}
              onChange={handleChange}
              onToggle={handleToggle}
              onArrayToggle={handleArrayToggle}
              errors={errors}
              canUpdate={canUpdate}
            />

            {canUpdate && (
              <div className="mt-8 pt-6 border-t flex justify-end" style={{ borderColor: 'var(--color-border)' }}>
                <button
                  type="submit"
                  disabled={loading}
                  className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all disabled:opacity-50 hover:opacity-90"
                  style={{ background: 'var(--color-cta)', color: 'white' }}
                >
                  {loading ? (
                    <span className="flex items-center gap-2">
                      <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                      </svg>
                      Saving...
                    </span>
                  ) : (
                    'Save Changes'
                  )}
                </button>
              </div>
            )}

            {!canUpdate && (
              <div className="mt-8 pt-6 border-t" style={{ borderColor: 'var(--color-border)' }}>
                <p className="text-sm text-center" style={{ color: 'var(--color-text-tertiary)' }}>
                  You have read-only access. Contact admin for changes.
                </p>
              </div>
            )}
          </div>
        </form>
      </div>
    </div>
  );
}