import { create } from 'zustand';
import { cloneDefaultProps, cloneDefaultStyles, getSectionSchema } from '../schema/sectionSchema';

// Simple ID generator (replaces uuid)
const generateId = () => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 9)}`;

export interface SectionProp {
    type: 'static' | 'dynamic';
    value?: any;
    source?: string;
}

export interface SectionStyles {
    backgroundColor?: string;
    backgroundType?: 'solid' | 'gradient' | 'image';
    gradientFrom?: string;
    gradientTo?: string;
    gradientAngle?: number; // 0-360
    backgroundImage?: string;
    backgroundOverlay?: number; // 0-100 opacity
    paddingTop?: string;
    paddingBottom?: string;
    contentWidth?: 'full' | 'contained' | 'boxed';
    heightPreset?: string;
    dynamicBackground?: string; // e.g. 'post_featured_image'
}

export interface ElementStyle {
    color?: string;
    fontSize?: string;
    fontWeight?: string;
    fontFamily?: 'primary' | 'secondary';
    textAlign?: 'left' | 'center' | 'right';

    // Image specific
    objectFit?: 'cover' | 'contain' | 'fill';
    backgroundColor?: string; // Wrapper BG
    width?: string;
    height?: string;

    // Link specific
    textDecoration?: 'none' | 'underline';
    hoverColor?: string;

    // Button/Box specific
    borderColor?: string;
    borderWidth?: string;
    borderRadius?: string;
    padding?: string;
}

export interface Section {
    id: string;
    type: string;
    layoutVariant?: string;
    colorScheme?: string;
    styles?: SectionStyles;
    elementStyles?: Record<string, ElementStyle>;
    props: Record<string, SectionProp>;
}

export interface PageItem {
    id?: number;
    type: 'page' | 'template';
    cpt?: string;
    slug?: string;
    title: string;
    url?: string;
    icon?: string;
    has_template?: boolean;
    permalink_base?: string;
    isFrontPage?: boolean;
    isSpaLanding?: boolean;
    containerWidth?: 'boxed' | 'fullwidth' | 'default';
}

interface PageEditorState {
    // Current page/template being edited
    currentPage: PageItem | null;

    // Sections for the current page
    sections: Section[];

    // Selection & interaction
    selectedSectionId: string | null;
    hoveredSectionId: string | null;

    // UI state
    deviceMode: 'desktop' | 'mobile';
    inspectorCollapsed: boolean;
    hasUnsavedChanges: boolean;
    isLoading: boolean;

    // Available sources for dynamic fields (CPT templates)
    availableSources: { value: string; label: string }[];

    // Actions
    setCurrentPage: (page: PageItem | null) => void;
    setSections: (sections: Section[]) => void;
    setSelectedSection: (id: string | null) => void;
    setHoveredSection: (id: string | null) => void;
    setDeviceMode: (mode: 'desktop' | 'mobile') => void;
    setInspectorCollapsed: (collapsed: boolean) => void;
    setAvailableSources: (sources: { value: string; label: string }[]) => void;
    setIsLoading: (loading: boolean) => void;

    // Section actions
    addSection: (type: string, index?: number) => void;
    deleteSection: (id: string) => void;
    duplicateSection: (id: string) => void;
    moveSection: (id: string, direction: 'up' | 'down') => void;
    reorderSections: (sections: Section[]) => void;
    updateSectionProp: (sectionId: string, propName: string, value: SectionProp) => void;
    updateSectionLayout: (sectionId: string, layoutVariant: string) => void;
    updateSectionColorScheme: (sectionId: string, colorScheme: string) => void;
    updateSectionStyles: (sectionId: string, styles: Partial<SectionStyles>) => void;
    updateElementStyles: (sectionId: string, fieldName: string, styles: Partial<ElementStyle>) => void;

    // Page actions
    setAsSpaLanding: () => Promise<void>;
    unsetSpaLanding: () => Promise<void>;

    // Persistence
    markAsChanged: () => void;
    markAsSaved: () => void;
    reset: () => void;
    savePage: () => Promise<void>;
}

export const usePageEditorStore = create<PageEditorState>((set, get) => ({
    // Initial state
    currentPage: null,
    sections: [],
    selectedSectionId: null,
    hoveredSectionId: null,
    deviceMode: 'desktop',
    inspectorCollapsed: false,
    hasUnsavedChanges: false,
    isLoading: false,
    availableSources: [],

    // Setters
    setCurrentPage: (currentPage) => set({ currentPage }),
    setSections: (sections) => set({ sections, hasUnsavedChanges: true }),
    setSelectedSection: (selectedSectionId) => set({ selectedSectionId }),
    setHoveredSection: (hoveredSectionId) => set({ hoveredSectionId }),
    setDeviceMode: (deviceMode) => set({ deviceMode }),
    setInspectorCollapsed: (inspectorCollapsed) => set({ inspectorCollapsed }),
    setAvailableSources: (availableSources) => set({ availableSources }),
    setIsLoading: (isLoading) => set({ isLoading }),

    // Section actions
    addSection: (type, index) => {
        const { sections } = get();
        const sectionConfig = getSectionSchema(type);

        if (!sectionConfig) return;

        const newSection: Section = {
            id: generateId(),
            type,
            props: cloneDefaultProps(type) as Record<string, SectionProp>,
            styles: cloneDefaultStyles(type) as SectionStyles,
        };

        const newSections = [...sections];
        if (typeof index === 'number') {
            newSections.splice(index, 0, newSection);
        } else {
            newSections.push(newSection);
        }

        set({ sections: newSections, hasUnsavedChanges: true });

        // Select the new section
        set({ selectedSectionId: newSection.id });
    },

    deleteSection: (id) => {
        const { sections, selectedSectionId } = get();
        const newSections = sections.filter(s => s.id !== id);

        set({
            sections: newSections,
            hasUnsavedChanges: true,
            selectedSectionId: selectedSectionId === id ? null : selectedSectionId
        });
    },

    duplicateSection: (id) => {
        const { sections } = get();
        const index = sections.findIndex(s => s.id === id);
        if (index === -1) return;

        const section = sections[index];
        const newSection: Section = {
            ...JSON.parse(JSON.stringify(section)), // Deep clone
            id: generateId()
        };

        const newSections = [...sections];
        newSections.splice(index + 1, 0, newSection);

        set({ sections: newSections, hasUnsavedChanges: true });
    },

    moveSection: (id, direction) => {
        const { sections } = get();
        const index = sections.findIndex(s => s.id === id);
        if (index === -1) return;

        if (direction === 'up' && index > 0) {
            const newSections = [...sections];
            [newSections[index], newSections[index - 1]] = [newSections[index - 1], newSections[index]];
            set({ sections: newSections, hasUnsavedChanges: true });
        } else if (direction === 'down' && index < sections.length - 1) {
            const newSections = [...sections];
            [newSections[index], newSections[index + 1]] = [newSections[index + 1], newSections[index]];
            set({ sections: newSections, hasUnsavedChanges: true });
        }
    },

    reorderSections: (sections) => {
        set({ sections, hasUnsavedChanges: true });
    },

    updateSectionProp: (sectionId, propName, value) => {
        const { sections } = get();
        const newSections = sections.map(section => {
            if (section.id !== sectionId) return section;
            return {
                ...section,
                props: {
                    ...section.props,
                    [propName]: value
                }
            };
        });
        set({ sections: newSections, hasUnsavedChanges: true });
    },

    updateSectionLayout: (sectionId, layoutVariant) => {
        const { sections } = get();
        const newSections = sections.map(section => {
            if (section.id !== sectionId) return section;
            return {
                ...section,
                layoutVariant
            };
        });
        set({ sections: newSections, hasUnsavedChanges: true });
    },

    updateSectionColorScheme: (sectionId, colorScheme) => {
        const { sections } = get();
        const newSections = sections.map(section => {
            if (section.id !== sectionId) return section;
            return {
                ...section,
                colorScheme
            };
        });
        set({ sections: newSections, hasUnsavedChanges: true });
    },

    updateSectionStyles: (sectionId, styles) => {
        const { sections } = get();
        const newSections = sections.map(section => {
            if (section.id !== sectionId) return section;
            return {
                ...section,
                styles: {
                    ...section.styles,
                    ...styles
                }
            };
        });
        set({ sections: newSections, hasUnsavedChanges: true });
    },

    updateElementStyles: (sectionId, fieldName, styles) => {
        const { sections } = get();
        const newSections = sections.map(section => {
            if (section.id !== sectionId) return section;

            const newElementStyles = {
                ...section.elementStyles,
                [fieldName]: {
                    ...(section.elementStyles?.[fieldName] || {}),
                    ...styles
                }
            };

            return {
                ...section,
                elementStyles: newElementStyles
            };
        });
        set({ sections: newSections, hasUnsavedChanges: true });
    },

    // Page Actions
    setAsSpaLanding: async () => {
        const { currentPage } = get();
        if (!currentPage || !currentPage.id) return;

        try {
            set({ isLoading: true });

            // Call API to set page as SPA Landing
            await fetch(`${(window as any).WNW_API.root}/pages/${currentPage.id}/set-as-spa-landing`, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': (window as any).WNW_API.nonce,
                    'Content-Type': 'application/json'
                }
            });

            // Update local state - only update isSpaLanding, no other properties
            set({
                currentPage: {
                    ...currentPage,
                    isSpaLanding: true
                },
                isLoading: false
            });

        } catch (error) {
            console.error('Failed to set SPA landing page:', error);
            set({ isLoading: false });
        }
    },

    unsetSpaLanding: async () => {
        const { currentPage } = get();
        if (!currentPage) return;

        try {
            set({ isLoading: true });

            // Call API to unset SPA Landing
            await fetch(`${(window as any).WNW_API.root}/pages/unset-spa-landing`, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': (window as any).WNW_API.nonce,
                    'Content-Type': 'application/json'
                }
            });

            // Update local state
            set({
                currentPage: {
                    ...currentPage,
                    isSpaLanding: false
                },
                isLoading: false
            });

        } catch (error) {
            console.error('Failed to unset SPA landing page:', error);
            set({ isLoading: false });
        }
    },

    // Persistence
    markAsChanged: () => set({ hasUnsavedChanges: true }),
    markAsSaved: () => set({ hasUnsavedChanges: false }),

    savePage: async () => {
        const { currentPage, sections } = get();
        if (!currentPage) return;

        try {
            set({ isLoading: true });

            const endpoint = currentPage.type === 'page'
                ? `/pages/${currentPage.slug}`
                : `/templates/${currentPage.cpt}`;

            await fetch(`${(window as any).WNW_API.root}${endpoint}`, {
                method: 'POST',
                headers: {
                    'X-WP-Nonce': (window as any).WNW_API.nonce,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    sections,
                    container_width: currentPage.containerWidth
                })
            });

            set({
                hasUnsavedChanges: false,
                isLoading: false
            });
        } catch (error) {
            console.error('Failed to save page:', error);
            set({ isLoading: false });
        }
    },

    reset: () =>
        set({
            currentPage: null,
            sections: [],
            selectedSectionId: null,
            hoveredSectionId: null,
            hasUnsavedChanges: false,
        }),
}));
