import React, { useState, useEffect } 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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Plus, FileText, Layout, Trash2, Eye, Settings } from 'lucide-react';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { PageSidebar } from './components/PageSidebar';
import { SectionEditor } from './components/SectionEditor';
import { PageSettings } from './components/PageSettings';
import { CreatePageModal } from './components/CreatePageModal';

// Types
interface PageItem {
    id?: number;
    type: 'page' | 'template';
    cpt?: string;
    slug?: string;
    title: string;
    url?: string;
    icon?: string;
    has_template?: boolean;
    permalink_base?: string;
}

interface Section {
    id: string;
    type: string;
    layoutVariant?: string;
    colorScheme?: string;
    props: Record<string, any>;
}

interface PageStructure {
    type: 'page' | 'template';
    sections: Section[];
    updated_at?: string;
}

export default function AppearancePages() {
    const queryClient = useQueryClient();
    const [selectedPage, setSelectedPage] = useState<PageItem | null>(null);
    const [selectedSection, setSelectedSection] = useState<Section | null>(null);
    const [structure, setStructure] = useState<PageStructure | null>(null);
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

    // Fetch all pages and templates
    const { data: pages = [], isLoading: pagesLoading } = useQuery<PageItem[]>({
        queryKey: ['pages'],
        queryFn: async () => {
            const response = await api.get('/pages');
            return response.data;
        },
    });

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

    // Update local structure when page data loads
    useEffect(() => {
        if (pageData?.structure) {
            setStructure(pageData.structure);
            setHasUnsavedChanges(false);
        }
    }, [pageData]);

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

    // Handle section update
    const handleSectionUpdate = (updatedSection: Section) => {
        if (!structure) return;
        const newSections = structure.sections.map(s =>
            s.id === updatedSection.id ? updatedSection : s
        );
        setStructure({ ...structure, sections: newSections });
        setSelectedSection(updatedSection);
        setHasUnsavedChanges(true);
    };

    // Add new section
    const handleAddSection = (sectionType: string) => {
        if (!structure) {
            setStructure({
                type: selectedPage?.type || 'page',
                sections: [],
            });
        }
        const newSection: Section = {
            id: `section-${Date.now()}`,
            type: sectionType,
            layoutVariant: 'default',
            colorScheme: 'default',
            props: {},
        };
        setStructure(prev => ({
            ...prev!,
            sections: [...(prev?.sections || []), newSection],
        }));
        setSelectedSection(newSection);
        setHasUnsavedChanges(true);
    };

    // Delete section
    const handleDeleteSection = (sectionId: string) => {
        if (!structure) return;
        setStructure({
            ...structure,
            sections: structure.sections.filter(s => s.id !== sectionId),
        });
        if (selectedSection?.id === sectionId) {
            setSelectedSection(null);
        }
        setHasUnsavedChanges(true);
    };

    // Move section
    const handleMoveSection = (sectionId: string, direction: 'up' | 'down') => {
        if (!structure) return;
        const index = structure.sections.findIndex(s => s.id === sectionId);
        if (index === -1) return;

        const newIndex = direction === 'up' ? index - 1 : index + 1;
        if (newIndex < 0 || newIndex >= structure.sections.length) return;

        const newSections = [...structure.sections];
        [newSections[index], newSections[newIndex]] = [newSections[newIndex], newSections[index]];
        setStructure({ ...structure, sections: newSections });
        setHasUnsavedChanges(true);
    };

    return (
        <div className="h-[calc(100vh-64px)] flex flex-col">
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b bg-white">
                <div>
                    <h1 className="text-xl font-semibold">{__('Page Editor')}</h1>
                    <p className="text-sm text-muted-foreground">
                        {selectedPage ? selectedPage.title : __('Select a page to edit')}
                    </p>
                </div>
                <div className="flex items-center gap-3">
                    {hasUnsavedChanges && (
                        <span className="text-sm text-amber-600">{__('Unsaved changes')}</span>
                    )}
                    <Button
                        variant="outline"
                        onClick={() => setShowCreateModal(true)}
                    >
                        <Plus className="w-4 h-4 mr-2" />
                        {__('Create Page')}
                    </Button>
                    <Button
                        onClick={() => saveMutation.mutate()}
                        disabled={!hasUnsavedChanges || saveMutation.isPending}
                    >
                        {saveMutation.isPending ? __('Saving...') : __('Save Changes')}
                    </Button>
                </div>
            </div>

            {/* 3-Column Layout */}
            <div className="flex-1 flex overflow-hidden">
                {/* Left Column: Pages List */}
                <PageSidebar
                    pages={pages}
                    selectedPage={selectedPage}
                    onSelectPage={(page) => {
                        if (hasUnsavedChanges) {
                            if (!confirm(__('You have unsaved changes. Continue?'))) return;
                        }
                        setSelectedPage(page);
                        setSelectedSection(null);
                    }}
                    isLoading={pagesLoading}
                />

                {/* Center Column: Section Editor */}
                <div className="flex-1 bg-gray-50 overflow-y-auto p-6">
                    {selectedPage ? (
                        <SectionEditor
                            sections={structure?.sections || []}
                            selectedSection={selectedSection}
                            onSelectSection={setSelectedSection}
                            onAddSection={handleAddSection}
                            onDeleteSection={handleDeleteSection}
                            onMoveSection={handleMoveSection}
                            isTemplate={selectedPage.type === 'template'}
                            cpt={selectedPage.cpt}
                            isLoading={pageLoading}
                        />
                    ) : (
                        <div className="h-full flex items-center justify-center text-gray-400">
                            <div className="text-center">
                                <Layout className="w-12 h-12 mx-auto mb-4 opacity-50" />
                                <p>{__('Select a page from the sidebar to start editing')}</p>
                            </div>
                        </div>
                    )}
                </div>

                {/* Right Column: Settings & Preview */}
                <PageSettings
                    page={selectedPage}
                    section={selectedSection}
                    onSectionUpdate={handleSectionUpdate}
                    isTemplate={selectedPage?.type === 'template'}
                    availableSources={pageData?.available_sources || []}
                />
            </div>

            {/* Create Page Modal */}
            <CreatePageModal
                open={showCreateModal}
                onOpenChange={setShowCreateModal}
                onCreated={(newPage) => {
                    queryClient.invalidateQueries({ queryKey: ['pages'] });
                    setSelectedPage(newPage);
                }}
            />
        </div>
    );
}
