import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import type { Product, FBOHeroContent, FBOContactContent, FBOTheme, CartItem, ProductCategory } from '@/types';

const defaultFBOTheme: FBOTheme = {
  primaryColor: '#2D5A27',
  secondaryColor: '#4A7C43',
  accentColor: '#8BC34A',
  backgroundColor: '#F5F9F4',
  textColor: '#1A1A1A',
  cardBackground: '#FFFFFF'
};

const defaultHeroContent: FBOHeroContent = {
  title: "Découvrez le Pouvoir de l'Aloe Vera",
  titleEn: "Discover the Power of Aloe Vera",
  subtitle: "Produits Naturels Forever Living",
  subtitleEn: "Natural Forever Living Products",
  description: "Des produits de bien-être naturels à base d'aloe vera pur pour une vie plus saine et équilibrée.",
  descriptionEn: "Natural wellness products made with pure aloe vera for a healthier, balanced life.",
  ctaPrimary: "Découvrir nos produits",
  ctaPrimaryEn: "Discover our products",
  ctaSecondary: "Devenir FBO",
  ctaSecondaryEn: "Become FBO",
  backgroundImage: "https://images.unsplash.com/photo-1596547609652-9cf5d8d76921?w=1920&q=80"
};

const defaultContactContent: FBOContactContent = {
  title: "Contactez-nous",
  titleEn: "Contact us",
  subtitle: "Commandez vos produits Forever Living",
  subtitleEn: "Order your Forever Living products",
  description: "Notre équipe FBO est à votre disposition pour vous conseiller et prendre vos commandes.",
  descriptionEn: "Our FBO team is available to advise you and take your orders.",
  phone: "+221 77 123 45 67",
  email: "fbo@zlo-technologies.com",
  whatsapp: "+221 77 123 45 67",
  address: "Sacré-Cœur 3, Villa 10818, Dakar, Sénégal",
  hours: "Lun - Sam: 8h00 - 20h00",
  hoursEn: "Mon - Sat: 8:00 AM - 8:00 PM"
};

const defaultProducts: Product[] = [
  {
    id: "1",
    reference: "715",
    name: "Aloe Vera Gel",
    nameEn: "Aloe Vera Gel",
    category: "aloe-vera",
    price: 15000,
    priceEUR: 23,
    priceUSD: 25,
    priceGBP: 19,
    image: "https://images.unsplash.com/photo-1615485290382-441e4d049cb5?w=600&q=80",
    images: [],
    description: "Notre produit phare à base d'aloe vera pur stabilisé. Boisson quotidienne pour le bien-être général.",
    descriptionEn: "Our flagship product made with pure stabilized aloe vera. Daily drink for general wellness.",
    composition: "99.7% de gel d'aloe vera stabilisé",
    compositionEn: "99.7% stabilized aloe vera gel",
    dosage: "60-120ml par jour",
    dosageEn: "60-120ml per day",
    benefits: [
      "Soutient la digestion",
      "Renforce le système immunitaire",
      "Hydratation naturelle",
      "Riche en vitamines et minéraux"
    ],
    benefitsEn: [
      "Supports digestion",
      "Boosts immune system",
      "Natural hydration",
      "Rich in vitamins and minerals"
    ],
    inStock: true,
    featured: true
  },
  {
    id: "2",
    reference: "734",
    name: "Forever Bright Toothgel",
    nameEn: "Forever Bright Toothgel",
    category: "personal-care",
    price: 8000,
    priceEUR: 12,
    priceUSD: 13,
    priceGBP: 10,
    image: "https://images.unsplash.com/photo-1559671088-795c6c6b3d83?w=600&q=80",
    images: [],
    description: "Dentifrice naturel à base d'aloe vera et de propolis sans fluor.",
    descriptionEn: "Natural toothpaste with aloe vera and propolis, fluoride-free.",
    composition: "Aloe vera, propolis, menthe",
    compositionEn: "Aloe vera, propolis, mint",
    dosage: "Utilisation quotidienne",
    dosageEn: "Daily use",
    benefits: [
      "Haleine fraîche",
      "Nettoie en douceur",
      "Sans fluor",
      "Naturel et sûr"
    ],
    benefitsEn: [
      "Fresh breath",
      "Gentle cleansing",
      "Fluoride-free",
      "Natural and safe"
    ],
    inStock: true,
    featured: false
  },
  {
    id: "3",
    reference: "638",
    name: "Aloe Propolis Creme",
    nameEn: "Aloe Propolis Creme",
    category: "beauty",
    price: 12000,
    priceEUR: 18,
    priceUSD: 20,
    priceGBP: 15,
    image: "https://images.unsplash.com/photo-1556228720-195a672e8a03?w=600&q=80",
    images: [],
    description: "Crème hydratante enrichie en aloe vera et propolis pour tous types de peau.",
    descriptionEn: "Moisturizing cream enriched with aloe vera and propolis for all skin types.",
    composition: "Aloe vera, propolis, vitamine E",
    compositionEn: "Aloe vera, propolis, vitamin E",
    dosage: "Appliquer matin et soir",
    dosageEn: "Apply morning and evening",
    benefits: [
      "Hydratation profonde",
      "Apaise la peau",
      "Protection naturelle",
      "Texture légère"
    ],
    benefitsEn: [
      "Deep hydration",
      "Soothes skin",
      "Natural protection",
      "Light texture"
    ],
    inStock: true,
    featured: true
  },
  {
    id: "4",
    reference: "289",
    name: "Forever Lite Ultra",
    nameEn: "Forever Lite Ultra",
    category: "nutrition",
    price: 18000,
    priceEUR: 27,
    priceUSD: 30,
    priceGBP: 23,
    image: "https://images.unsplash.com/photo-1579722821273-0f6c7d44362f?w=600&q=80",
    images: [],
    description: "Shake protéiné pour compléter votre alimentation quotidienne.",
    descriptionEn: "Protein shake to complement your daily diet.",
    composition: "Protéines de soja, vitamines, minéraux",
    compositionEn: "Soy protein, vitamins, minerals",
    dosage: "1-2 shakes par jour",
    dosageEn: "1-2 shakes per day",
    benefits: [
      "Riche en protéines",
      "Substitut de repas",
      "Contrôle du poids",
      "Énergie durable"
    ],
    benefitsEn: [
      "High in protein",
      "Meal replacement",
      "Weight management",
      "Sustained energy"
    ],
    inStock: true,
    featured: false
  },
  {
    id: "5",
    reference: "470",
    name: "Clean 9",
    nameEn: "Clean 9",
    category: "weight-management",
    price: 45000,
    priceEUR: 68,
    priceUSD: 74,
    priceGBP: 58,
    image: "https://images.unsplash.com/photo-1490645935967-10de6ba17061?w=600&q=80",
    images: [],
    description: "Programme de détoxification sur 9 jours pour un nouveau départ.",
    descriptionEn: "9-day detoxification program for a fresh start.",
    composition: "Aloe vera gel, Forever Lite Ultra, Garcinia Plus",
    compositionEn: "Aloe vera gel, Forever Lite Ultra, Garcinia Plus",
    dosage: "Programme de 9 jours complet",
    dosageEn: "Complete 9-day program",
    benefits: [
      "Détoxification",
      "Perte de poids",
      "Plus d'énergie",
      "Meilleure digestion"
    ],
    benefitsEn: [
      "Detoxification",
      "Weight loss",
      "More energy",
      "Better digestion"
    ],
    inStock: true,
    featured: true,
    isPack: true
  }
];

interface FBOAdminContextType {
  // Hero
  hero: FBOHeroContent;
  updateHero: (hero: Partial<FBOHeroContent>) => void;
  
  // Products
  products: Product[];
  addProduct: (product: Omit<Product, 'id'>) => string;
  updateProduct: (id: string, product: Partial<Product>) => void;
  deleteProduct: (id: string) => void;
  getProductById: (id: string) => Product | undefined;
  getProductsByCategory: (category: ProductCategory) => Product[];
  getFeaturedProducts: () => Product[];
  toggleProductStock: (id: string) => void;
  toggleProductFeatured: (id: string) => void;
  
  // Contact
  contact: FBOContactContent;
  updateContact: (contact: Partial<FBOContactContent>) => void;
  
  // Theme
  theme: FBOTheme;
  updateTheme: (theme: Partial<FBOTheme>) => void;
  resetTheme: () => void;
  
  // Settings
  showFBOButton: boolean;
  showFBOMenu: boolean;
  setShowFBOButton: (show: boolean) => void;
  setShowFBOMenu: (show: boolean) => void;
  
  // Cart
  cart: CartItem[];
  addToCart: (product: Product, quantity?: number) => void;
  removeFromCart: (productId: string) => void;
  updateCartQuantity: (productId: string, quantity: number) => void;
  clearCart: () => void;
  getCartTotal: () => number;
  getCartItemCount: () => number;
  
  // Import/Export
  exportFBOData: () => string;
  importFBOData: (json: string) => void;
  resetAll: () => void;
}

const FBOAdminContext = createContext<FBOAdminContextType | undefined>(undefined);

const STORAGE_KEY = 'zlo_fbo_data';

export function FBOAdminProvider({ children }: { children: React.ReactNode }) {
  const [hero, setHero] = useState<FBOHeroContent>(defaultHeroContent);
  const [products, setProducts] = useState<Product[]>(defaultProducts);
  const [contact, setContact] = useState<FBOContactContent>(defaultContactContent);
  const [theme, setTheme] = useState<FBOTheme>(defaultFBOTheme);
  const [showFBOButton, setShowFBOButton] = useState(true);
  const [showFBOMenu, setShowFBOMenu] = useState(true);
  const [cart, setCart] = useState<CartItem[]>([]);

  // Load from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) {
      try {
        const parsed = JSON.parse(saved);
        if (parsed.hero) setHero(parsed.hero);
        if (parsed.products) setProducts(parsed.products);
        if (parsed.contact) setContact(parsed.contact);
        if (parsed.theme) setTheme(parsed.theme);
        if (parsed.showFBOButton !== undefined) setShowFBOButton(parsed.showFBOButton);
        if (parsed.showFBOMenu !== undefined) setShowFBOMenu(parsed.showFBOMenu);
      } catch {
        console.error('Failed to load FBO data');
      }
    }
  }, []);

  // Save to localStorage on change
  useEffect(() => {
    const data = {
      hero,
      products,
      contact,
      theme,
      showFBOButton,
      showFBOMenu
    };
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
  }, [hero, products, contact, theme, showFBOButton, showFBOMenu]);

  // Hero
  const updateHero = useCallback((updates: Partial<FBOHeroContent>) => {
    setHero(prev => ({ ...prev, ...updates }));
  }, []);

  // Products
  const addProduct = useCallback((product: Omit<Product, 'id'>): string => {
    const id = `prod_${Date.now()}`;
    const newProduct: Product = { ...product, id };
    setProducts(prev => [...prev, newProduct]);
    return id;
  }, []);

  const updateProduct = useCallback((id: string, updates: Partial<Product>) => {
    setProducts(prev => prev.map(p => p.id === id ? { ...p, ...updates } : p));
  }, []);

  const deleteProduct = useCallback((id: string) => {
    setProducts(prev => prev.filter(p => p.id !== id));
  }, []);

  const getProductById = useCallback((id: string) => {
    return products.find(p => p.id === id);
  }, [products]);

  const getProductsByCategory = useCallback((category: ProductCategory) => {
    return products.filter(p => p.category === category);
  }, [products]);

  const getFeaturedProducts = useCallback(() => {
    return products.filter(p => p.featured);
  }, [products]);

  const toggleProductStock = useCallback((id: string) => {
    setProducts(prev => prev.map(p => 
      p.id === id ? { ...p, inStock: !p.inStock } : p
    ));
  }, []);

  const toggleProductFeatured = useCallback((id: string) => {
    setProducts(prev => prev.map(p => 
      p.id === id ? { ...p, featured: !p.featured } : p
    ));
  }, []);

  // Contact
  const updateContact = useCallback((updates: Partial<FBOContactContent>) => {
    setContact(prev => ({ ...prev, ...updates }));
  }, []);

  // Theme
  const updateTheme = useCallback((updates: Partial<FBOTheme>) => {
    setTheme(prev => ({ ...prev, ...updates }));
  }, []);

  const resetTheme = useCallback(() => {
    setTheme(defaultFBOTheme);
  }, []);

  // Cart
  const addToCart = useCallback((product: Product, quantity: number = 1) => {
    setCart(prev => {
      const existing = prev.find(item => item.product.id === product.id);
      if (existing) {
        return prev.map(item => 
          item.product.id === product.id 
            ? { ...item, quantity: item.quantity + quantity }
            : item
        );
      }
      return [...prev, { product, quantity }];
    });
  }, []);

  const removeFromCart = useCallback((productId: string) => {
    setCart(prev => prev.filter(item => item.product.id !== productId));
  }, []);

  const updateCartQuantity = useCallback((productId: string, quantity: number) => {
    if (quantity <= 0) {
      removeFromCart(productId);
      return;
    }
    setCart(prev => prev.map(item => 
      item.product.id === productId 
        ? { ...item, quantity }
        : item
    ));
  }, [removeFromCart]);

  const clearCart = useCallback(() => {
    setCart([]);
  }, []);

  const getCartTotal = useCallback(() => {
    return cart.reduce((total, item) => total + (item.product.price * item.quantity), 0);
  }, [cart]);

  const getCartItemCount = useCallback(() => {
    return cart.reduce((count, item) => count + item.quantity, 0);
  }, [cart]);

  // Import/Export
  const exportFBOData = useCallback(() => {
    return JSON.stringify({
      hero,
      products,
      contact,
      theme,
      showFBOButton,
      showFBOMenu
    }, null, 2);
  }, [hero, products, contact, theme, showFBOButton, showFBOMenu]);

  const importFBOData = useCallback((json: string) => {
    try {
      const parsed = JSON.parse(json);
      if (parsed.hero) setHero(parsed.hero);
      if (parsed.products) setProducts(parsed.products);
      if (parsed.contact) setContact(parsed.contact);
      if (parsed.theme) setTheme(parsed.theme);
      if (parsed.showFBOButton !== undefined) setShowFBOButton(parsed.showFBOButton);
      if (parsed.showFBOMenu !== undefined) setShowFBOMenu(parsed.showFBOMenu);
    } catch (error) {
      console.error('Failed to import FBO data:', error);
      throw new Error('Invalid FBO data format');
    }
  }, []);

  const resetAll = useCallback(() => {
    setHero(defaultHeroContent);
    setProducts(defaultProducts);
    setContact(defaultContactContent);
    setTheme(defaultFBOTheme);
    setShowFBOButton(true);
    setShowFBOMenu(true);
    setCart([]);
  }, []);

  return (
    <FBOAdminContext.Provider value={{
      hero,
      updateHero,
      products,
      addProduct,
      updateProduct,
      deleteProduct,
      getProductById,
      getProductsByCategory,
      getFeaturedProducts,
      toggleProductStock,
      toggleProductFeatured,
      contact,
      updateContact,
      theme,
      updateTheme,
      resetTheme,
      showFBOButton,
      showFBOMenu,
      setShowFBOButton,
      setShowFBOMenu,
      cart,
      addToCart,
      removeFromCart,
      updateCartQuantity,
      clearCart,
      getCartTotal,
      getCartItemCount,
      exportFBOData,
      importFBOData,
      resetAll
    }}>
      {children}
    </FBOAdminContext.Provider>
  );
}

export function useFBOAdmin() {
  const context = useContext(FBOAdminContext);
  if (context === undefined) {
    throw new Error('useFBOAdmin must be used within a FBOAdminProvider');
  }
  return context;
}
