import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import type { Section, MenuItem } from '@/types';

const defaultSections: Section[] = [
  { 
    id: 'hero', 
    name: 'Hero', 
    label: 'Accueil', 
    labelEn: 'Home',
    description: 'Section d\'accueil avec bannière principale', 
    isVisible: true, 
    showInMenu: false, 
    order: 0,
    icon: 'Home'
  },
  { 
    id: 'about', 
    name: 'À propos', 
    label: 'À propos', 
    labelEn: 'About',
    description: 'Présentation de l\'entreprise', 
    isVisible: true, 
    showInMenu: true, 
    order: 1,
    icon: 'Info'
  },
  { 
    id: 'services', 
    name: 'Services', 
    label: 'Services', 
    labelEn: 'Services',
    description: 'Nos services et expertises', 
    isVisible: true, 
    showInMenu: true, 
    order: 2,
    icon: 'Briefcase'
  },
  { 
    id: 'projects', 
    name: 'Projets', 
    label: 'Projets', 
    labelEn: 'Projects',
    description: 'Nos réalisations', 
    isVisible: true, 
    showInMenu: true, 
    order: 3,
    icon: 'FolderOpen'
  },
  { 
    id: 'testimonials', 
    name: 'Témoignages', 
    label: 'Témoignages', 
    labelEn: 'Testimonials',
    description: 'Avis de nos clients', 
    isVisible: true, 
    showInMenu: false, 
    order: 4,
    icon: 'MessageSquare'
  },
  { 
    id: 'team', 
    name: 'Équipe', 
    label: 'Équipe', 
    labelEn: 'Team',
    description: 'Notre équipe', 
    isVisible: true, 
    showInMenu: false, 
    order: 5,
    icon: 'Users'
  },
  { 
    id: 'contact', 
    name: 'Contact', 
    label: 'Contact', 
    labelEn: 'Contact',
    description: 'Formulaire de contact', 
    isVisible: true, 
    showInMenu: true, 
    order: 6,
    icon: 'Mail'
  }
];

const defaultMenuItems: MenuItem[] = [
  { 
    id: 'home', 
    label: 'Accueil', 
    labelEn: 'Home',
    href: '#hero', 
    isVisible: true, 
    order: 0,
    icon: 'Home'
  },
  { 
    id: 'about-menu', 
    label: 'À propos', 
    labelEn: 'About',
    href: '#about', 
    isVisible: true, 
    order: 1,
    icon: 'Info'
  },
  { 
    id: 'services-menu', 
    label: 'Services', 
    labelEn: 'Services',
    href: '#services', 
    isVisible: true, 
    order: 2,
    icon: 'Briefcase'
  },
  { 
    id: 'projects-menu', 
    label: 'Projets', 
    labelEn: 'Projects',
    href: '#projects', 
    isVisible: true, 
    order: 3,
    icon: 'FolderOpen'
  },
  { 
    id: 'team-menu', 
    label: 'La Team', 
    labelEn: 'Team',
    href: '#team', 
    isVisible: true, 
    order: 4,
    icon: 'Users'
  },
  { 
    id: 'contact-menu', 
    label: 'Contact', 
    labelEn: 'Contact',
    href: '#contact', 
    isVisible: true, 
    order: 5,
    icon: 'Mail'
  }
];

interface SectionsContextType {
  sections: Section[];
  menuItems: MenuItem[];
  visibleSections: Section[];
  visibleMenuItems: MenuItem[];
  updateSection: (id: string, updates: Partial<Section>) => void;
  updateMenuItem: (id: string, updates: Partial<MenuItem>) => void;
  addSection: (section: Omit<Section, 'id'>) => string;
  addMenuItem: (item: Omit<MenuItem, 'id'>) => string;
  removeSection: (id: string) => void;
  removeMenuItem: (id: string) => void;
  reorderSections: (orderedIds: string[]) => void;
  reorderMenuItems: (orderedIds: string[]) => void;
  toggleSectionVisibility: (id: string) => void;
  toggleMenuItemVisibility: (id: string) => void;
  toggleSectionInMenu: (id: string) => void;
  resetToDefaults: () => void;
  exportConfig: () => string;
  importConfig: (json: string) => void;
}

const SectionsContext = createContext<SectionsContextType | undefined>(undefined);

const STORAGE_KEY = 'zlo_sections_config';

export function SectionsProvider({ children }: { children: React.ReactNode }) {
  const [sections, setSections] = useState<Section[]>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem(STORAGE_KEY + '_sections');
      if (saved) {
        try {
          return JSON.parse(saved);
        } catch {
          return defaultSections;
        }
      }
    }
    return defaultSections;
  });

  const [menuItems, setMenuItems] = useState<MenuItem[]>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem(STORAGE_KEY + '_menu');
      if (saved) {
        try {
          return JSON.parse(saved);
        } catch {
          return defaultMenuItems;
        }
      }
    }
    return defaultMenuItems;
  });

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY + '_sections', JSON.stringify(sections));
  }, [sections]);

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY + '_menu', JSON.stringify(menuItems));
  }, [menuItems]);

  const visibleSections = sections.filter(s => s.isVisible).sort((a, b) => a.order - b.order);
  const visibleMenuItems = menuItems.filter(m => m.isVisible).sort((a, b) => a.order - b.order);

  const updateSection = useCallback((id: string, updates: Partial<Section>) => {
    setSections(prev => prev.map(s => s.id === id ? { ...s, ...updates } : s));
  }, []);

  const updateMenuItem = useCallback((id: string, updates: Partial<MenuItem>) => {
    setMenuItems(prev => prev.map(m => m.id === id ? { ...m, ...updates } : m));
  }, []);

  const addSection = useCallback((section: Omit<Section, 'id'>): string => {
    const id = `section_${Date.now()}`;
    const newSection: Section = { ...section, id };
    setSections(prev => [...prev, newSection]);
    return id;
  }, []);

  const addMenuItem = useCallback((item: Omit<MenuItem, 'id'>): string => {
    const id = `menu_${Date.now()}`;
    const newItem: MenuItem = { ...item, id };
    setMenuItems(prev => [...prev, newItem]);
    return id;
  }, []);

  const removeSection = useCallback((id: string) => {
    setSections(prev => prev.filter(s => s.id !== id));
  }, []);

  const removeMenuItem = useCallback((id: string) => {
    setMenuItems(prev => prev.filter(m => m.id !== id));
  }, []);

  const reorderSections = useCallback((orderedIds: string[]) => {
    setSections(prev => {
      const sectionMap = new Map(prev.map(s => [s.id, s]));
      return orderedIds.map((id, index) => ({
        ...sectionMap.get(id)!,
        order: index
      }));
    });
  }, []);

  const reorderMenuItems = useCallback((orderedIds: string[]) => {
    setMenuItems(prev => {
      const itemMap = new Map(prev.map(m => [m.id, m]));
      return orderedIds.map((id, index) => ({
        ...itemMap.get(id)!,
        order: index
      }));
    });
  }, []);

  const toggleSectionVisibility = useCallback((id: string) => {
    setSections(prev => prev.map(s => 
      s.id === id ? { ...s, isVisible: !s.isVisible } : s
    ));
  }, []);

  const toggleMenuItemVisibility = useCallback((id: string) => {
    setMenuItems(prev => prev.map(m => 
      m.id === id ? { ...m, isVisible: !m.isVisible } : m
    ));
  }, []);

  const toggleSectionInMenu = useCallback((id: string) => {
    setSections(prev => prev.map(s => 
      s.id === id ? { ...s, showInMenu: !s.showInMenu } : s
    ));
  }, []);

  const resetToDefaults = useCallback(() => {
    setSections(defaultSections);
    setMenuItems(defaultMenuItems);
  }, []);

  const exportConfig = useCallback(() => {
    return JSON.stringify({ sections, menuItems }, null, 2);
  }, [sections, menuItems]);

  const importConfig = useCallback((json: string) => {
    try {
      const parsed = JSON.parse(json);
      if (parsed.sections) setSections(parsed.sections);
      if (parsed.menuItems) setMenuItems(parsed.menuItems);
    } catch (error) {
      console.error('Failed to import config:', error);
      throw new Error('Invalid configuration format');
    }
  }, []);

  return (
    <SectionsContext.Provider value={{
      sections,
      menuItems,
      visibleSections,
      visibleMenuItems,
      updateSection,
      updateMenuItem,
      addSection,
      addMenuItem,
      removeSection,
      removeMenuItem,
      reorderSections,
      reorderMenuItems,
      toggleSectionVisibility,
      toggleMenuItemVisibility,
      toggleSectionInMenu,
      resetToDefaults,
      exportConfig,
      importConfig
    }}>
      {children}
    </SectionsContext.Provider>
  );
}

export function useSections() {
  const context = useContext(SectionsContext);
  if (context === undefined) {
    throw new Error('useSections must be used within a SectionsProvider');
  }
  return context;
}
