import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button';
import { Plus, Layout, Undo2, Save, Maximize2, Minimize2 } from 'lucide-react';
import { toast } from 'sonner';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { cn } from '@/lib/utils';
import { PageSidebar } from './components/PageSidebar';
import { CanvasRenderer } from './components/CanvasRenderer';
import { InspectorPanel } from './components/InspectorPanel';
import { CreatePageModal } from './components/CreatePageModal';
import { usePageEditorStore, Section, PageItem } from './store/usePageEditorStore';
import { useUnsavedChanges } from '@/hooks/useUnsavedChanges';

export default function AppearancePages() {
    const queryClient = useQueryClient();
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [isFullscreen, setIsFullscreen] = useState(false);
    const [showDeleteDialog, setShowDeleteDialog] = useState(false);
    const [showResetDialog, setShowResetDialog] = useState(false);
    const [showUnsavedDialog, setShowUnsavedDialog] = useState(false);
    const [pendingPage, setPendingPage] = useState<PageItem | null>(null);
    const [previewPostId, setPreviewPostId] = useState<number | null>(null);

    // Zustand store
    const {
        currentPage,
        sections,
        selectedSectionId,
        deviceMode,
        inspectorCollapsed,
        hasUnsavedChanges,
        isLoading,
        availableSources,
        setCurrentPage,
        setSections,
        setSelectedSection,
        setDeviceMode,
        setInspectorCollapsed,
        setAvailableSources,
        setIsLoading,
        addSection,
        deleteSection,
        duplicateSection,
        moveSection,
        reorderSections,
        updateSectionProp,
        updateSectionLayout,
        updateSectionColorScheme,
        updateSectionStyles,
        updateElementStyles,
        markAsSaved,
        setAsSpaLanding,
        unsetSpaLanding,
    } = usePageEditorStore();

    const { showPrompt, confirmNavigation, cancelNavigation } = useUnsavedChanges(hasUnsavedChanges);

    // Get selected section object
    const selectedSection = sections.find(s => s.id === selectedSectionId) || null;
    const isTemplate = currentPage?.type === 'template';

    // Fetch all pages and templates
    const { data: pages = [], isLoading: pagesLoading } = useQuery<PageItem[]>({
        queryKey: ['pages'],
        queryFn: async () => {
            const response = await api.get('/pages');
            // Map API snake_case to frontend camelCase
            return response.map((p: any) => ({
                ...p,
                isSpaLanding: !!p.is_spa_frontpage
            }));
        },
    });

    // Fetch selected page/template structure
    const { data: pageData, isLoading: pageLoading } = useQuery({
        queryKey: ['page-structure', currentPage?.type, currentPage?.slug || currentPage?.cpt],
        queryFn: async () => {
            if (!currentPage) return null;
            const endpoint = currentPage.type === 'page'
                ? `/pages/${currentPage.slug}`
                : `/templates/${currentPage.cpt}`;
            const response = await api.get(endpoint);
            return response;
        },
        enabled: !!currentPage,
    });

    // Fetch global settings for defaults
    const { data: globalSettings } = useQuery({
        queryKey: ['appearance-settings'],
        queryFn: async () => api.get('/appearance/settings'),
    });

    const { data: previewSamples } = useQuery({
        queryKey: ['template-preview-samples', currentPage?.cpt],
        queryFn: async () => {
            if (!currentPage?.cpt) return { items: [] };
            return api.get(`/preview/samples/${currentPage.cpt}`);
        },
        enabled: isTemplate && !!currentPage?.cpt,
    });

    // Resolve dynamic template props for canvas preview without mutating saved section JSON.
    const { data: templatePreviewData } = useQuery({
        queryKey: ['template-preview-resolved', currentPage?.cpt, previewPostId, sections],
        queryFn: async () => {
            if (!currentPage?.cpt) return null;
            return api.post(`/preview/resolve/${currentPage.cpt}`, { sections, sample_post_id: previewPostId });
        },
        enabled: isTemplate && !!currentPage?.cpt && sections.length > 0,
        staleTime: 10 * 1000,
    });

    const previewSections = isTemplate && templatePreviewData?.resolved
        ? templatePreviewData.sections as Section[]
        : undefined;

    // Update store when page data loads
    useEffect(() => {
        if (pageData?.structure?.sections) {
            setSections(pageData.structure.sections);
            markAsSaved();
        }
        if (pageData?.available_sources) {
            setAvailableSources(pageData.available_sources);
        }
        // Sync isFrontPage if returned from single page API (optional, but good practice)
        if (pageData?.is_front_page !== undefined && currentPage) {
            setCurrentPage({ ...currentPage, isFrontPage: !!pageData.is_front_page });
        }
        // Sync containerWidth
        if (pageData?.container_width && currentPage) {
            setCurrentPage({ ...currentPage, containerWidth: pageData.container_width });
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pageData, setSections, markAsSaved, setAvailableSources]); // Removed currentPage from dependency to avoid loop

    // Update loading state
    useEffect(() => {
        setIsLoading(pageLoading);
    }, [pageLoading, setIsLoading]);

    // Save mutation
    const saveMutation = useMutation({
        mutationFn: async () => {
            if (!currentPage) return;
            const endpoint = currentPage.type === 'page'
                ? `/pages/${currentPage.slug}`
                : `/templates/${currentPage.cpt}`;
            return api.post(endpoint, { sections });
        },
        onSuccess: () => {
            toast.success(__('Page saved successfully'));
            markAsSaved();
            queryClient.invalidateQueries({ queryKey: ['page-structure'] });
        },
        onError: () => {
            toast.error(__('Failed to save page'));
        },
    });

    // Keyboard shortcut listener
    useEffect(() => {
        const handleSaveShortcut = () => {
            if (hasUnsavedChanges && !saveMutation.isPending) {
                saveMutation.mutate();
            }
        };
        window.addEventListener('woonoow:shortcut:save', handleSaveShortcut);
        return () => window.removeEventListener('woonoow:shortcut:save', handleSaveShortcut);
    }, [hasUnsavedChanges, saveMutation]);

    // Delete mutation
    const deleteMutation = useMutation({
        mutationFn: async (id: number) => {
            return api.del(`/pages/${id}`);
        },
        onSuccess: () => {
            toast.success(__('Page deleted successfully'));
            markAsSaved(); // Clear unsaved flag
            setCurrentPage(null);
            queryClient.invalidateQueries({ queryKey: ['pages'] });
        },
        onError: () => {
            toast.error(__('Failed to delete page'));
        },
    });

    // Delete template mutation (abort SPA for this CPT)
    const deleteTemplateMutation = useMutation({
        mutationFn: async (cpt: string) => {
            return api.del(`/templates/${cpt}`);
        },
        onSuccess: () => {
            toast.success(__('CPT template deleted. WordPress will handle this post type natively.'));
            markAsSaved();
            setCurrentPage(null);
            queryClient.invalidateQueries({ queryKey: ['pages'] });
        },
        onError: () => {
            toast.error(__('Failed to delete template'));
        },
    });

    // Set as SPA Landing mutation
    const setSpaLandingMutation = useMutation({
        mutationFn: async (id: number) => {
            return api.post(`/pages/${id}/set-as-spa-landing`);
        },
        onSuccess: () => {
            toast.success(__('Set as SPA Landing Page'));
            queryClient.invalidateQueries({ queryKey: ['pages'] });
            // Update local state is handled by re-fetching pages or we can optimistic update
            if (currentPage) {
                setCurrentPage({ ...currentPage, isSpaLanding: true });
            }
        },
        onError: () => {
            toast.error(__('Failed to set SPA Landing Page'));
        },
    });

    // Unset SPA Landing mutation
    const unsetSpaLandingMutation = useMutation({
        mutationFn: async () => {
            return api.post(`/pages/unset-spa-landing`);
        },
        onSuccess: () => {
            toast.success(__('Unset SPA Landing Page'));
            queryClient.invalidateQueries({ queryKey: ['pages'] });
            if (currentPage) {
                setCurrentPage({ ...currentPage, isSpaLanding: false });
            }
        },
        onError: () => {
            toast.error(__('Failed to unset SPA Landing Page'));
        },
    });

    // Handle page selection
    const handleSelectPage = (page: PageItem) => {
        if (hasUnsavedChanges) {
            setPendingPage(page);
            setShowUnsavedDialog(true);
            return;
        }
        processPageSelection(page);
    };

    const processPageSelection = (page: PageItem) => {
        if (page.type === 'page') {
            setCurrentPage({
                ...page,
                isSpaLanding: !!(page as any).isSpaLanding
            });
        } else {
            setCurrentPage(page);
        };
        setPreviewPostId(null);
        setSelectedSection(null);
    };

    const handleDiscard = () => {
        if (pageData?.structure?.sections) {
            setSections(pageData.structure.sections);
            markAsSaved();
            toast.success(__('Changes discarded'));
        }
    };

    const handleDeletePage = () => {
        if (!currentPage || !currentPage.id) return;
        setShowDeleteDialog(true);
    };

    const handleDeleteTemplate = () => {
        if (!currentPage || currentPage.type !== 'template' || !currentPage.cpt) return;
        setShowResetDialog(true);
    };

    return (
        <div className={
            cn(
                "flex flex-col bg-background transition-all duration-300",
                isFullscreen ? "fixed inset-0 z-[100] h-screen" : "h-[calc(100vh-64px)]"
            )
        } >
            {/* Header */}
            < div className="flex items-center justify-between px-6 py-3 border-b bg-background" >
                <div>
                    <h1 className="text-xl font-semibold">{__('Page Editor')}</h1>
                    <p className="text-sm text-muted-foreground">
                        {currentPage ? currentPage.title : __('Select a page to edit')}
                    </p>
                </div>
                <div className="flex items-center gap-3">
                    {isTemplate && (previewSamples?.items || []).length > 0 && (
                        <select
                            className="h-9 rounded-md border border-input bg-background px-3 text-sm"
                            value={previewPostId ?? ''}
                            onChange={(event) => setPreviewPostId(event.target.value ? Number(event.target.value) : null)}
                            title={__('Preview content')}
                        >
                            <option value="">{__('Auto preview content')}</option>
                            {previewSamples.items.map((item: any) => (
                                <option key={item.id} value={item.id}>
                                    {item.title}
                                </option>
                            ))}
                        </select>
                    )}
                    <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => setIsFullscreen(!isFullscreen)}
                        title={isFullscreen ? __('Exit Fullscreen') : __('Enter Fullscreen')}
                        className="mr-2"
                    >
                        {isFullscreen ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
                    </Button>
                    {hasUnsavedChanges && (
                        <>
                            <span className="text-sm text-amber-600">{__('Unsaved changes')}</span>
                            <Button
                                variant="ghost"
                                size="sm"
                                onClick={handleDiscard}
                            >
                                <Undo2 className="w-4 h-4 mr-2" />
                                {__('Discard')}
                            </Button>
                        </>
                    )}
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setShowCreateModal(true)}
                    >
                        <Plus className="w-4 h-4 mr-2" />
                        {__('Create Page')}
                    </Button>
                    <Button
                        size="sm"
                        onClick={() => saveMutation.mutate()}
                        disabled={!hasUnsavedChanges || saveMutation.isPending}
                    >
                        <Save className="w-4 h-4 mr-2" />
                        {saveMutation.isPending ? __('Saving...') : __('Save')}
                    </Button>
                </div>
            </div >

            {/* 3-Column Layout: Sidebar | Canvas | Inspector */}
            < div className="flex-1 flex overflow-hidden" >
                {/* Left Column: Pages List */}
                < PageSidebar
                    pages={pages}
                    selectedPage={currentPage}
                    onSelectPage={handleSelectPage}
                    isLoading={pagesLoading}
                />

                {/* Center Column: Canvas Renderer */}
                {
                    currentPage ? (
                        <CanvasRenderer
                            sections={sections}
                            previewSections={previewSections}
                            selectedSectionId={selectedSectionId}
                            deviceMode={deviceMode}
                            onSelectSection={setSelectedSection}
                            onAddSection={addSection}
                            onDeleteSection={deleteSection}
                            onDuplicateSection={duplicateSection}
                            onMoveSection={moveSection}
                            onReorderSections={reorderSections}

                            onDeviceModeChange={setDeviceMode}
                            containerWidth={
                                currentPage?.containerWidth && currentPage.containerWidth !== 'default'
                                    ? currentPage.containerWidth
                                    : ((globalSettings as any)?.data?.general?.container_width || 'boxed')
                            }
                        />
                    ) : (
                        <div className="flex-1 bg-muted/30 flex items-center justify-center text-muted-foreground">
                            <div className="text-center">
                                <Layout className="w-16 h-16 mx-auto mb-4 opacity-50" />
                                <p className="text-lg">{__('Select a page from the sidebar')}</p>
                                <p className="text-sm mt-2">{__('Edit pages and templates visually')}</p>
                            </div>
                        </div>
                    )
                }

                {/* Right Column: Inspector Panel */}
                {
                    currentPage && (
                        <InspectorPanel
                            page={currentPage}
                            selectedSection={selectedSection}
                            isCollapsed={inspectorCollapsed}
                            isTemplate={currentPage.type === 'template'}
                            availableSources={availableSources}
                            onToggleCollapse={() => setInspectorCollapsed(!inspectorCollapsed)}
                            onSectionPropChange={(propName, value) => {
                                if (selectedSectionId) {
                                    updateSectionProp(selectedSectionId, propName, value);
                                }
                            }}
                            onLayoutChange={(layout) => {
                                if (selectedSectionId) {
                                    updateSectionLayout(selectedSectionId, layout);
                                }
                            }}
                            onColorSchemeChange={(scheme) => {
                                if (selectedSectionId) {
                                    updateSectionColorScheme(selectedSectionId, scheme);
                                }
                            }}
                            onSectionStylesChange={(styles) => {
                                if (selectedSectionId) {
                                    updateSectionStyles(selectedSectionId, styles);
                                }
                            }}
                            onElementStylesChange={(fieldName, styles) => {
                                if (selectedSectionId) {
                                    updateElementStyles(selectedSectionId, fieldName, styles);
                                }
                            }}
                            onDeleteSection={() => {
                                if (selectedSectionId) {
                                    deleteSection(selectedSectionId);
                                }
                            }}
                            onSetAsSpaLanding={() => {
                                if (currentPage?.id) {
                                    setSpaLandingMutation.mutate(currentPage.id);
                                }
                            }}
                            onUnsetSpaLanding={() => unsetSpaLandingMutation.mutate()}
                            onDeletePage={handleDeletePage}
                            onDeleteTemplate={handleDeleteTemplate}
                            onContainerWidthChange={(width) => {
                                if (currentPage) {
                                    setCurrentPage({ ...currentPage, containerWidth: width });
                                    markAsSaved(); // Mark as changed so save button enables
                                }
                            }}
                        />
                    )
                }
            </div >

            {/* Unsaved Changes Dialog (Route Navigation) */}
            <AlertDialog open={showPrompt} onOpenChange={cancelNavigation}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{__('Unsaved Changes')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {__('You have unsaved changes. Are you sure you want to leave this page?')}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel onClick={cancelNavigation}>{__('Cancel')}</AlertDialogCancel>
                        <AlertDialogAction onClick={confirmNavigation} className="bg-destructive hover:bg-destructive/90">
                            {__('Leave Page')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Unsaved Changes Dialog (Page Switch) */}
            <AlertDialog open={showUnsavedDialog} onOpenChange={setShowUnsavedDialog}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{__('Unsaved Changes')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {__('You have unsaved changes. Are you sure you want to discard them and continue?')}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel onClick={() => {
                            setShowUnsavedDialog(false);
                            setPendingPage(null);
                        }}>
                            {__('Cancel')}
                        </AlertDialogCancel>
                        <AlertDialogAction onClick={() => {
                            setShowUnsavedDialog(false);
                            if (pendingPage) processPageSelection(pendingPage);
                            setPendingPage(null);
                        }} className="bg-destructive hover:bg-destructive/90">
                            {__('Discard Changes')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Delete Dialog */}
            <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{__('Delete Page')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {__('Are you sure you want to delete this page? This action cannot be undone.')}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel onClick={() => setShowDeleteDialog(false)}>
                            {__('Cancel')}
                        </AlertDialogCancel>
                        <AlertDialogAction onClick={() => {
                            if (currentPage?.id) deleteMutation.mutate(currentPage.id);
                            setShowDeleteDialog(false);
                        }} className="bg-destructive hover:bg-destructive/90">
                            {__('Delete')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Reset Dialog */}
            <AlertDialog open={showResetDialog} onOpenChange={setShowResetDialog}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{__('Reset to WordPress Default')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {__('Are you sure? This will delete the SPA template and WordPress will handle this post type natively. This cannot be undone.')}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel onClick={() => setShowResetDialog(false)}>
                            {__('Cancel')}
                        </AlertDialogCancel>
                        <AlertDialogAction onClick={() => {
                            if (currentPage?.cpt) deleteTemplateMutation.mutate(currentPage.cpt);
                            setShowResetDialog(false);
                        }} className="bg-destructive hover:bg-destructive/90">
                            {__('Reset')}
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>

            {/* Create Page Modal */}
            < CreatePageModal
                open={showCreateModal}
                onOpenChange={setShowCreateModal}
                cptList={pages.filter((p: PageItem) => p.type === 'template')}
                onCreated={(newPage) => {
                    queryClient.invalidateQueries({ queryKey: ['pages'] });
                    setCurrentPage(newPage);
                }
                }
            />
        </div >
    );
}
