
import React, { createContext, useState, useContext, ReactNode, useEffect } from 'react';
import { HERO_IMAGES, CONTENT } from '../constants.ts';
import { Itinerary, CruiseShip, DiningSection, VideoSectionContent, ShipsPageImages } from '../types.ts';

interface ThemeContextType {
  customLogo: string | null;
  customFooterLogo: string | null;
  heroImages: string[];
  
  // New customizable sections
  itineraries: Itinerary[];
  ships: CruiseShip[];
  dining: DiningSection;
  videoSection: VideoSectionContent;
  
  // Ships Page Specific Images
  shipsPageImages: ShipsPageImages;

  // Setters
  setCustomLogo: (url: string | null) => void;
  setCustomFooterLogo: (url: string | null) => void;
  setHeroImages: (images: string[]) => void;
  setItineraries: (data: Itinerary[]) => void;
  setShips: (data: CruiseShip[]) => void;
  setDining: (data: DiningSection) => void;
  setVideoSection: (data: VideoSectionContent) => void;
  setShipsPageImages: (data: ShipsPageImages) => void;
  
  resetTheme: () => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// Initial default values from constants (ZH version as base)
const DEFAULT_ITINERARIES: Itinerary[] = [
  {
    ...CONTENT.zh.itineraries[0],
    video: "https://videos.pexels.com/video-files/3252327/3252327-uhd_2560_1440_25fps.mp4" 
  },
  {
    ...CONTENT.zh.itineraries[1],
    video: "https://videos.pexels.com/video-files/5049352/5049352-uhd_2560_1440_30fps.mp4"
  },
  {
    ...CONTENT.zh.itineraries[2],
    video: "https://videos.pexels.com/video-files/2927233/2927233-uhd_2560_1440_24fps.mp4"
  }
];

const DEFAULT_SHIPS = CONTENT.zh.ships;
const DEFAULT_DINING: DiningSection = {
  title: CONTENT.zh.home.dining_title,
  description: CONTENT.zh.home.dining_desc,
  buttonText: CONTENT.zh.home.dining_btn,
  image: "https://picsum.photos/1920/600?random=5"
};
const DEFAULT_VIDEO: VideoSectionContent = {
  title: CONTENT.zh.home.exp_title,
  titleItalic: CONTENT.zh.home.exp_title_italic,
  description: CONTENT.zh.home.exp_desc,
  thumbnail: "https://picsum.photos/800/450?random=20"
};

const DEFAULT_SHIPS_PAGE_IMAGES: ShipsPageImages = {
  lanyue: [
    "https://picsum.photos/600/400?random=100",
    "https://picsum.photos/600/400?random=101",
    "https://picsum.photos/600/400?random=102",
    "https://picsum.photos/600/400?random=103"
  ],
  aurora: "https://picsum.photos/1920/800?random=200"
};

export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // --- Logo & Hero ---
  const [customLogo, setCustomLogo] = useState<string | null>(() => {
    return localStorage.getItem('vista_custom_logo') || null;
  });

  const [customFooterLogo, setCustomFooterLogo] = useState<string | null>(() => {
    return localStorage.getItem('vista_custom_footer_logo') || null;
  });

  const [heroImages, setHeroImages] = useState<string[]>(HERO_IMAGES);

  // Fetch hero images from API on every page refresh
  useEffect(() => {
    const loadHeroImagesFromApi = async () => {
      try {
        // Import the functions dynamically to avoid circular dependencies
        const { fetchHotArticles, extractHeroImagesFromArticles } = 
            await import('../services/articleService.ts');

        // Fetch hot articles from the API
        const articlesData = await fetchHotArticles(1, 6);
        
        // Extract hero images from the articles' coverUrl field
        const apiHeroImages = extractHeroImagesFromArticles(articlesData);
        
        // If we got images from the API, use them
        if (apiHeroImages.length > 0) {
          setHeroImages(apiHeroImages);
        }
        // Otherwise, keep the default HERO_IMAGES
      } catch (error) {
        console.error('Failed to fetch hero images from API:', error);
        // Fallback to default HERO_IMAGES if API fails
        setHeroImages(HERO_IMAGES);
      }
    };

    loadHeroImagesFromApi();
  }, []); // Empty dependency array means this runs on every component mount (page refresh)

  // Fetch video content from API on every page refresh
  useEffect(() => {
    const loadVideoContentFromApi = async () => {
      try {
        // Import the functions dynamically to avoid circular dependencies
        const { fetchVideoContent, extractVideoContentFromArticles } = 
            await import('../services/articleService.ts');

        // Fetch video content from the API (lang=1 for Chinese)
        const videoData = await fetchVideoContent(1);
        
        // Extract video content from the articles data
        const videoContent = extractVideoContentFromArticles(videoData);
        
        // If we got video content from the API, use it
        if (videoContent) {
          setVideoSection(videoContent);
        }
        // Otherwise, keep the default video content
      } catch (error) {
        console.error('Failed to fetch video content from API:', error);
        // Fallback to default video content if API fails
        setVideoSection(DEFAULT_VIDEO);
      }
    };

    loadVideoContentFromApi();
  }, []); // Empty dependency array means this runs on every component mount (page refresh)

  // Fetch cruise routes from API on every page refresh
  useEffect(() => {
    const loadCruiseRoutesFromApi = async () => {
      try {
        // Import the functions dynamically to avoid circular dependencies
        const { fetchCruiseRoutes, extractCruiseRoutesFromArticles } = 
            await import('../services/articleService.ts');

        // Fetch cruise routes from the API (lang=1 for Chinese)
        const cruiseRoutesData = await fetchCruiseRoutes(1);
        
        // Extract cruise routes from the articles data
        const cruiseRoutes = extractCruiseRoutesFromArticles(cruiseRoutesData);
        
        // If we got cruise routes from the API, use them
        if (cruiseRoutes.length > 0) {
          setItineraries(cruiseRoutes);
        }
        // Otherwise, keep the default itineraries
      } catch (error) {
        console.error('Failed to fetch cruise routes from API:', error);
        // Fallback to default itineraries if API fails
        setItineraries(DEFAULT_ITINERARIES);
      }
    };

    loadCruiseRoutesFromApi();
  }, []); // Empty dependency array means this runs on every component mount (page refresh)

  // --- Content Sections ---
  const [itineraries, setItineraries] = useState<Itinerary[]>(() => {
    const saved = localStorage.getItem('vista_itineraries');
    return saved ? JSON.parse(saved) : DEFAULT_ITINERARIES;
  });

  const [ships, setShips] = useState<CruiseShip[]>(() => {
    const saved = localStorage.getItem('vista_ships');
    return saved ? JSON.parse(saved) : DEFAULT_SHIPS;
  });

  const [dining, setDining] = useState<DiningSection>(() => {
    const saved = localStorage.getItem('vista_dining');
    return saved ? JSON.parse(saved) : DEFAULT_DINING;
  });

  const [videoSection, setVideoSection] = useState<VideoSectionContent>(DEFAULT_VIDEO);

  const [shipsPageImages, setShipsPageImages] = useState<ShipsPageImages>(() => {
    const saved = localStorage.getItem('vista_ships_page_images');
    return saved ? JSON.parse(saved) : DEFAULT_SHIPS_PAGE_IMAGES;
  });

  // --- Persistence Effects ---
  useEffect(() => {
    if (customLogo) localStorage.setItem('vista_custom_logo', customLogo);
    else localStorage.removeItem('vista_custom_logo');
  }, [customLogo]);

  useEffect(() => {
    if (customFooterLogo) localStorage.setItem('vista_custom_footer_logo', customFooterLogo);
    else localStorage.removeItem('vista_custom_footer_logo');
  }, [customFooterLogo]);



  useEffect(() => {
    localStorage.setItem('vista_itineraries', JSON.stringify(itineraries));
  }, [itineraries]);

  useEffect(() => {
    localStorage.setItem('vista_ships', JSON.stringify(ships));
  }, [ships]);

  useEffect(() => {
    localStorage.setItem('vista_dining', JSON.stringify(dining));
  }, [dining]);



  useEffect(() => {
    localStorage.setItem('vista_ships_page_images', JSON.stringify(shipsPageImages));
  }, [shipsPageImages]);


  const resetTheme = () => {
    setCustomLogo(null);
    setCustomFooterLogo(null);
    setHeroImages(HERO_IMAGES);
    setItineraries(DEFAULT_ITINERARIES);
    setShips(DEFAULT_SHIPS);
    setDining(DEFAULT_DINING);
    setVideoSection(DEFAULT_VIDEO);
    setShipsPageImages(DEFAULT_SHIPS_PAGE_IMAGES);

    localStorage.removeItem('vista_custom_logo');
    localStorage.removeItem('vista_custom_footer_logo');
    localStorage.removeItem('vista_hero_images');
    localStorage.removeItem('vista_itineraries');
    localStorage.removeItem('vista_ships');
    localStorage.removeItem('vista_dining');
    localStorage.removeItem('vista_video');
    localStorage.removeItem('vista_ships_page_images');
  };

  return (
    <ThemeContext.Provider value={{ 
      customLogo, customFooterLogo, heroImages, 
      setCustomLogo, setCustomFooterLogo, setHeroImages,
      itineraries, setItineraries,
      ships, setShips,
      dining, setDining,
      videoSection, setVideoSection,
      shipsPageImages, setShipsPageImages,
      resetTheme 
    }}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};