import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import type { SiteContent, ServiceContent, ProjectContent, TestimonialContent, TeamMember, HeroContent, AboutContent, ContactContent, FooterContent } from '@/types';

const defaultContent: SiteContent = {
  hero: {
    title: "ZLO Technologies",
    subtitle: "Solutions Digitales Innovantes",
    description: "Nous transformons vos idées en solutions technologiques puissantes. Expertise en développement web, mobile et intelligence artificielle.",
    ctaPrimary: "Nos Services",
    ctaSecondary: "Nous Contacter",
    backgroundImage: "https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1920&q=80"
  },
  about: {
    title: "À Propos de ZLO Technologies",
    description: "ZLO Technologies est une entreprise innovante spécialisée dans le développement de solutions technologiques sur mesure. Notre mission est d'accompagner les entreprises dans leur transformation digitale.",
    mission: "Accompagner les entreprises dans leur transformation digitale en fournissant des solutions technologiques innovantes et adaptées à leurs besoins.",
    vision: "Devenir le partenaire technologique de référence en Afrique, reconnu pour l'excellence et l'innovation de nos solutions.",
    values: [
      {
        title: "Innovation",
        description: "Nous repoussons constamment les limites de la technologie",
        icon: "Lightbulb"
      },
      {
        title: "Excellence",
        description: "Nous visons la perfection dans chaque projet",
        icon: "Award"
      },
      {
        title: "Collaboration",
        description: "Nous travaillons en étroite partnership avec nos clients",
        icon: "Users"
      },
      {
        title: "Intégrité",
        description: "Nous agissons avec transparence et éthique",
        icon: "Shield"
      }
    ],
    stats: [
      { value: "150+", label: "Projets Réalisés" },
      { value: "50+", label: "Clients Satisfaits" },
      { value: "8+", label: "Années d'Expérience" },
      { value: "25+", label: "Experts" }
    ],
    image: "https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=800&q=80"
  },
  services: [
    {
      id: "1",
      title: "Développement Web",
      shortDescription: "Sites web et applications web performants",
      fullDescription: "Nous créons des sites web et applications web modernes, rapides et sécurisés. De la conception à la mise en ligne, nous vous accompagnons à chaque étape.",
      icon: "Globe",
      features: [
        "Sites vitrines et e-commerce",
        "Applications web progressives (PWA)",
        "Dashboards et outils de gestion",
        "Intégration API et web services"
      ],
      image: "https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=600&q=80"
    },
    {
      id: "2",
      title: "Applications Mobiles",
      shortDescription: "Apps iOS et Android natives et cross-platform",
      fullDescription: "Développement d'applications mobiles natives et cross-platform pour iOS et Android. Nous créons des expériences utilisateur fluides et engageantes.",
      icon: "Smartphone",
      features: [
        "Applications iOS (Swift/SwiftUI)",
        "Applications Android (Kotlin)",
        "Apps cross-platform (React Native/Flutter)",
        "Publication sur App Store et Play Store"
      ],
      image: "https://images.unsplash.com/photo-1512941937669-90a1b58e7e9c?w=600&q=80"
    },
    {
      id: "3",
      title: "Intelligence Artificielle",
      shortDescription: "Solutions IA et machine learning sur mesure",
      fullDescription: "Intégration de l'intelligence artificielle dans vos projets. Chatbots, analyse de données, reconnaissance d'images et plus encore.",
      icon: "Brain",
      features: [
        "Chatbots et assistants virtuels",
        "Analyse prédictive",
        "Traitement du langage naturel",
        "Vision par ordinateur"
      ],
      image: "https://images.unsplash.com/photo-1677442136019-21780ecad995?w=600&q=80"
    },
    {
      id: "4",
      title: "Cloud & DevOps",
      shortDescription: "Infrastructure cloud et automatisation",
      fullDescription: "Mise en place d'infrastructures cloud scalables et sécurisées. Automatisation des déploiements et monitoring en temps réel.",
      icon: "Cloud",
      features: [
        "Architecture cloud (AWS, Azure, GCP)",
        "CI/CD et automatisation",
        "Conteneurisation (Docker, Kubernetes)",
        "Monitoring et logging"
      ],
      image: "https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=600&q=80"
    },
    {
      id: "5",
      title: "Conseil IT",
      shortDescription: "Accompagnement stratégique digital",
      fullDescription: "Conseil et accompagnement dans votre transformation digitale. Audit, stratégie et feuille de route technologique.",
      icon: "Compass",
      features: [
        "Audit technologique",
        "Stratégie digitale",
        "Architecture des systèmes",
        "Formation et support"
      ],
      image: "https://images.unsplash.com/photo-1552664730-d307ca884978?w=600&q=80"
    },
    {
      id: "6",
      title: "Cybersécurité",
      shortDescription: "Protection et sécurisation de vos données",
      fullDescription: "Sécurisation de vos systèmes et données. Audit de sécurité, mise en place de protocoles et formation des équipes.",
      icon: "Lock",
      features: [
        "Audit de sécurité",
        "Tests d'intrusion",
        "Conformité RGPD",
        "Formation sécurité"
      ],
      image: "https://images.unsplash.com/photo-1563986768609-322da13575f3?w=600&q=80"
    }
  ],
  projects: [
    {
      id: "1",
      title: "Plateforme E-commerce",
      category: "Web",
      description: "Développement d'une plateforme e-commerce complète avec paiement mobile",
      image: "https://images.unsplash.com/photo-1563013544-824ae1b704d3?w=600&q=80",
      technologies: ["React", "Node.js", "MongoDB", "Stripe"]
    },
    {
      id: "2",
      title: "App de Livraison",
      category: "Mobile",
      description: "Application mobile de livraison de repas avec géolocalisation",
      image: "https://images.unsplash.com/photo-1526304640581-d334cdbbf45e?w=600&q=80",
      technologies: ["React Native", "Firebase", "Google Maps"]
    },
    {
      id: "3",
      title: "Dashboard Analytics",
      category: "Data",
      description: "Tableau de bord de visualisation de données en temps réel",
      image: "https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=600&q=80",
      technologies: ["Vue.js", "D3.js", "Python", "PostgreSQL"]
    },
    {
      id: "4",
      title: "Chatbot IA",
      category: "IA",
      description: "Assistant virtuel intelligent pour le service client",
      image: "https://images.unsplash.com/photo-1531746790731-6c087fecd65a?w=600&q=80",
      technologies: ["Python", "TensorFlow", "NLP", "FastAPI"]
    }
  ],
  testimonials: [
    {
      id: "1",
      name: "Amadou Diallo",
      role: "Directeur Général",
      company: "TechSénégal",
      content: "ZLO Technologies a transformé notre vision en réalité. Leur expertise et leur professionnalisme sont exceptionnels.",
      avatar: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200&q=80",
      rating: 5
    },
    {
      id: "2",
      name: "Fatou Ndiaye",
      role: "Fondatrice",
      company: "StartupAfrica",
      content: "Une équipe talentueuse qui livre des solutions de qualité. Je recommande vivement leurs services.",
      avatar: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=200&q=80",
      rating: 5
    },
    {
      id: "3",
      name: "Omar Sow",
      role: "CTO",
      company: "DigitalPlus",
      content: "Collaboration fluide et résultats au-delà de nos attentes. ZLO est un partenaire de confiance.",
      avatar: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200&q=80",
      rating: 5
    }
  ],
  team: [
    {
      id: "1",
      name: "Zakaria Lô",
      role: "Fondateur & CEO",
      bio: "Expert en stratégie digitale avec plus de 10 ans d'expérience dans la tech.",
      image: "https://images.unsplash.com/photo-1560250097-0b93528c311a?w=400&q=80",
      social: {
        linkedin: "#",
        twitter: "#",
        email: "zakaria@zlo-technologies.com"
      }
    },
    {
      id: "2",
      name: "Aminata Faye",
      role: "Directrice Technique",
      bio: "Ingénieure logicielle passionnée par l'innovation technologique.",
      image: "https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=400&q=80",
      social: {
        linkedin: "#",
        twitter: "#",
        email: "aminata@zlo-technologies.com"
      }
    },
    {
      id: "3",
      name: "Moussa Kane",
      role: "Lead Developer",
      bio: "Développeur full-stack spécialisé en React et Node.js.",
      image: "https://images.unsplash.com/photo-1519085360753-af0119f7cbe7?w=400&q=80",
      social: {
        linkedin: "#",
        github: "#",
        email: "moussa@zlo-technologies.com"
      }
    },
    {
      id: "4",
      name: "Sophie Diouf",
      role: "Designer UX/UI",
      bio: "Créatrice d'expériences utilisateur intuitives et esthétiques.",
      image: "https://images.unsplash.com/photo-1580489944761-15a19d654956?w=400&q=80",
      social: {
        linkedin: "#",
        dribbble: "#",
        email: "sophie@zlo-technologies.com"
      }
    }
  ],
  contact: {
    title: "Contactez-nous",
    subtitle: "Parlons de votre projet",
    description: "Vous avez un projet en tête ? N'hésitez pas à nous contacter. Notre équipe est là pour vous accompagner.",
    address: "Lomé, Togo — CEDEAO",
    phone: "+228 92 60 59 49",
    email: "contact@zlotech.net",
    hours: "Lun – Ven: 8h–18h (GMT)",
    mapEmbedUrl: "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3858.728574520978!2d1.225!3d6.131!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x0!2zNsKwMDcnNTEuNiJOIDHCsDEzJzMwLjAiRQ!5e0!3m2!1sfr!2stg!4v1234567890",
    socialLinks: {
      facebook: "#",
      twitter: "#",
      linkedin: "#",
      instagram: "#",
      youtube: "#"
    }
  },
  footer: {
    companyDescription: "ZLO Technologies - Votre partenaire digital de confiance. Solutions innovantes pour votre transformation digitale.",
    quickLinks: [
      { label: "Accueil", href: "#hero" },
      { label: "À Propos", href: "#about" },
      { label: "Services", href: "#services" },
      { label: "Projets", href: "#projects" },
      { label: "Contact", href: "#contact" }
    ],
    services: [
      { label: "Développement Web", href: "#" },
      { label: "Applications Mobiles", href: "#" },
      { label: "Intelligence Artificielle", href: "#" },
      { label: "Cloud & DevOps", href: "#" }
    ],
    newsletterTitle: "Newsletter",
    newsletterDescription: "Abonnez-vous pour recevoir nos actualités et offres.",
    copyright: "© 2024 ZLO Technologies. Tous droits réservés.",
    legalLinks: [
      { label: "Politique de confidentialité", href: "#" },
      { label: "Conditions d'utilisation", href: "#" },
      { label: "Mentions légales", href: "#" }
    ]
  }
};

interface ContentContextType {
  content: SiteContent;
  updateHero: (hero: Partial<HeroContent>) => void;
  updateAbout: (about: Partial<AboutContent>) => void;
  updateServices: (services: ServiceContent[]) => void;
  addService: (service: ServiceContent) => void;
  updateService: (id: string, service: Partial<ServiceContent>) => void;
  deleteService: (id: string) => void;
  updateProjects: (projects: ProjectContent[]) => void;
  addProject: (project: ProjectContent) => void;
  updateProject: (id: string, project: Partial<ProjectContent>) => void;
  deleteProject: (id: string) => void;
  updateTestimonials: (testimonials: TestimonialContent[]) => void;
  addTestimonial: (testimonial: TestimonialContent) => void;
  updateTestimonial: (id: string, testimonial: Partial<TestimonialContent>) => void;
  deleteTestimonial: (id: string) => void;
  updateTeam: (team: TeamMember[]) => void;
  addTeamMember: (member: TeamMember) => void;
  updateTeamMember: (id: string, member: Partial<TeamMember>) => void;
  deleteTeamMember: (id: string) => void;
  updateContact: (contact: Partial<ContactContent>) => void;
  updateFooter: (footer: Partial<FooterContent>) => void;
  resetContent: () => void;
  exportContent: () => string;
  importContent: (json: string) => void;
}

const ContentContext = createContext<ContentContextType | undefined>(undefined);

const STORAGE_KEY = 'zlo_site_content';

export function ContentProvider({ children }: { children: React.ReactNode }) {
  const [content, setContent] = useState<SiteContent>(() => {
    if (typeof window !== 'undefined') {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (saved) {
        try {
          return { ...defaultContent, ...JSON.parse(saved) };
        } catch {
          return defaultContent;
        }
      }
    }
    return defaultContent;
  });

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(content));
  }, [content]);

  const updateHero = useCallback((hero: Partial<HeroContent>) => {
    setContent(prev => ({ ...prev, hero: { ...prev.hero, ...hero } }));
  }, []);

  const updateAbout = useCallback((about: Partial<AboutContent>) => {
    setContent(prev => ({ ...prev, about: { ...prev.about, ...about } }));
  }, []);

  const updateServices = useCallback((services: ServiceContent[]) => {
    setContent(prev => ({ ...prev, services }));
  }, []);

  const addService = useCallback((service: ServiceContent) => {
    setContent(prev => ({ ...prev, services: [...prev.services, service] }));
  }, []);

  const updateService = useCallback((id: string, service: Partial<ServiceContent>) => {
    setContent(prev => ({
      ...prev,
      services: prev.services.map(s => s.id === id ? { ...s, ...service } : s)
    }));
  }, []);

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

  const updateProjects = useCallback((projects: ProjectContent[]) => {
    setContent(prev => ({ ...prev, projects }));
  }, []);

  const addProject = useCallback((project: ProjectContent) => {
    setContent(prev => ({ ...prev, projects: [...prev.projects, project] }));
  }, []);

  const updateProject = useCallback((id: string, project: Partial<ProjectContent>) => {
    setContent(prev => ({
      ...prev,
      projects: prev.projects.map(p => p.id === id ? { ...p, ...project } : p)
    }));
  }, []);

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

  const updateTestimonials = useCallback((testimonials: TestimonialContent[]) => {
    setContent(prev => ({ ...prev, testimonials }));
  }, []);

  const addTestimonial = useCallback((testimonial: TestimonialContent) => {
    setContent(prev => ({ ...prev, testimonials: [...prev.testimonials, testimonial] }));
  }, []);

  const updateTestimonial = useCallback((id: string, testimonial: Partial<TestimonialContent>) => {
    setContent(prev => ({
      ...prev,
      testimonials: prev.testimonials.map(t => t.id === id ? { ...t, ...testimonial } : t)
    }));
  }, []);

  const deleteTestimonial = useCallback((id: string) => {
    setContent(prev => ({
      ...prev,
      testimonials: prev.testimonials.filter(t => t.id !== id)
    }));
  }, []);

  const updateTeam = useCallback((team: TeamMember[]) => {
    setContent(prev => ({ ...prev, team }));
  }, []);

  const addTeamMember = useCallback((member: TeamMember) => {
    setContent(prev => ({ ...prev, team: [...prev.team, member] }));
  }, []);

  const updateTeamMember = useCallback((id: string, member: Partial<TeamMember>) => {
    setContent(prev => ({
      ...prev,
      team: prev.team.map(m => m.id === id ? { ...m, ...member } : m)
    }));
  }, []);

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

  const updateContact = useCallback((contact: Partial<ContactContent>) => {
    setContent(prev => ({ ...prev, contact: { ...prev.contact, ...contact } }));
  }, []);

  const updateFooter = useCallback((footer: Partial<FooterContent>) => {
    setContent(prev => ({ ...prev, footer: { ...prev.footer, ...footer } }));
  }, []);

  const resetContent = useCallback(() => {
    setContent(defaultContent);
  }, []);

  const exportContent = useCallback(() => {
    return JSON.stringify(content, null, 2);
  }, [content]);

  const importContent = useCallback((json: string) => {
    try {
      const parsed = JSON.parse(json);
      setContent({ ...defaultContent, ...parsed });
    } catch (error) {
      console.error('Failed to import content:', error);
      throw new Error('Invalid JSON format');
    }
  }, []);

  return (
    <ContentContext.Provider value={{
      content,
      updateHero,
      updateAbout,
      updateServices,
      addService,
      updateService,
      deleteService,
      updateProjects,
      addProject,
      updateProject,
      deleteProject,
      updateTestimonials,
      addTestimonial,
      updateTestimonial,
      deleteTestimonial,
      updateTeam,
      addTeamMember,
      updateTeamMember,
      deleteTeamMember,
      updateContact,
      updateFooter,
      resetContent,
      exportContent,
      importContent
    }}>
      {children}
    </ContentContext.Provider>
  );
}

export function useContent() {
  const context = useContext(ContentContext);
  if (context === undefined) {
    throw new Error('useContent must be used within a ContentProvider');
  }
  return context;
}
