import React, { useState, useEffect, useRef } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';

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

interface CreatePageModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    cptList?: PageItem[];
    onCreated: (page: PageItem) => void;
}

export function CreatePageModal({ open, onOpenChange, cptList = [], onCreated }: CreatePageModalProps) {
    const [mode, setMode] = useState<'page' | 'template'>('page');

    // Structural page state
    const [title, setTitle] = useState('');
    const [slug, setSlug] = useState('');
    const [selectedTemplateId, setSelectedTemplateId] = useState<string>('blank');

    // CPT template state
    const [selectedCpt, setSelectedCpt] = useState<string>('');
    const [selectedCptPreset, setSelectedCptPreset] = useState<string>('single-post');

    // Prevent double submission
    const isSubmittingRef = useRef(false);

    const siteUrl = window.WNW_CONFIG?.siteUrl?.replace(/\/$/, '') || window.location.origin;

    // Fetch template presets
    const { data: templates = [] } = useQuery({
        queryKey: ['templates-presets'],
        queryFn: async () => {
            const res = await api.get('/templates/presets');
            return res as { id: string; label: string; description: string; icon: string; sections?: any }[];
        }
    });

    // CPTs that don't have a template yet
    const availableCpts = cptList.filter(p => p.type === 'template' && !p.has_template);

    // Set default CPT when list loads
    useEffect(() => {
        if (availableCpts.length > 0 && !selectedCpt) {
            setSelectedCpt(availableCpts[0].cpt || '');
        }
    }, [availableCpts, selectedCpt]);

    // Create structural page mutation
    const createPageMutation = useMutation({
        mutationFn: async (data: { title: string; slug: string; templateId: string }) => {
            if (isSubmittingRef.current) throw new Error('Request already in progress');
            isSubmittingRef.current = true;
            try {
                const response = await api.post('/pages', {
                    title: data.title,
                    slug: data.slug,
                    templateId: data.templateId,
                });
                return { type: 'page' as const, data: response };
            } finally {
                setTimeout(() => { isSubmittingRef.current = false; }, 500);
            }
        },
        onSuccess: (result) => {
            if (result?.data?.page) {
                toast.success(__('Page created successfully'));
                onCreated({
                    id: result.data.page.id,
                    type: result.type,
                    slug: result.data.page.slug,
                    title: result.data.page.title,
                });
                onOpenChange(false);
            }
        },
        onError: (error: any) => {
            if (error?.message === 'Request already in progress') return;
            const message = error?.response?.data?.message || error?.message || __('Failed to create page');
            toast.error(message);
        },
    });

    // Create CPT template mutation
    const createTemplateMutation = useMutation({
        mutationFn: async (data: { cpt: string; presetId: string }) => {
            if (isSubmittingRef.current) throw new Error('Request already in progress');
            isSubmittingRef.current = true;
            try {
                // Get preset sections
                const presets = templates as any[];
                const preset = presets.find((t: any) => t.id === data.presetId);
                const sections = preset?.sections || [];

                const response = await api.post(`/templates/${data.cpt}`, { sections });
                return { cpt: data.cpt, data: response };
            } finally {
                setTimeout(() => { isSubmittingRef.current = false; }, 500);
            }
        },
        onSuccess: (result) => {
            toast.success(__('Template created successfully'));
            // Find the CPT item from the list to pass back
            const cptItem = cptList.find(p => p.cpt === result.cpt);
            onCreated({
                type: 'template',
                cpt: result.cpt,
                title: cptItem?.title || `${result.cpt} Template`,
                has_template: true,
            });
            onOpenChange(false);
        },
        onError: (error: any) => {
            if (error?.message === 'Request already in progress') return;
            const message = error?.response?.data?.message || error?.message || __('Failed to create template');
            toast.error(message);
        },
    });

    // Auto-generate slug from title
    const handleTitleChange = (value: string) => {
        setTitle(value);
        const autoSlug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
        if (!slug || slug === autoSlug) {
            setSlug(value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''));
        }
    };

    // Reset form when modal closes
    useEffect(() => {
        if (!open) {
            setMode('page');
            setTitle('');
            setSlug('');
            setSelectedTemplateId('blank');
            setSelectedCpt('');
            setSelectedCptPreset('single-post');
            isSubmittingRef.current = false;
        }
    }, [open]);

    const handleSubmit = () => {
        if (isSubmittingRef.current) return;

        if (mode === 'page') {
            if (title && slug) {
                createPageMutation.mutate({ title, slug, templateId: selectedTemplateId });
            }
        } else {
            if (selectedCpt) {
                createTemplateMutation.mutate({ cpt: selectedCpt, presetId: selectedCptPreset });
            }
        }
    };

    const isPending = createPageMutation.isPending || createTemplateMutation.isPending;
    const isPageDisabled = !title || !slug || isPending;
    const isTemplateDisabled = !selectedCpt || isPending;
    const isDisabled = mode === 'page' ? isPageDisabled : isTemplateDisabled;

    // Page layout presets (exclude single-post — it's for CPT)
    const pagePresets = templates.filter((tpl: any) => tpl.id !== 'single-post');
    // CPT presets (include ALL — user can pick any layout)
    const cptPresets = templates as any[];

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>{__('Create New Page')}</DialogTitle>
                    <DialogDescription>
                        {__('Choose what type of page you want to create.')}
                    </DialogDescription>
                </DialogHeader>

                <div className="px-6 py-4">
                    <Tabs value={mode} onValueChange={(v) => setMode(v as 'page' | 'template')}>
                        <TabsList className="w-full grid grid-cols-2 mb-6">
                            <TabsTrigger value="page">{__('Structural Page')}</TabsTrigger>
                            <TabsTrigger value="template">{__('CPT Template')}</TabsTrigger>
                        </TabsList>

                        {/* ── Structural Page Tab ── */}
                        <TabsContent value="page" className="space-y-6 mt-0">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="title">{__('Page Title')}</Label>
                                    <Input
                                        id="title"
                                        value={title}
                                        onChange={(e) => handleTitleChange(e.target.value)}
                                        placeholder={__('e.g., About Us')}
                                        disabled={isPending}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="slug">{__('URL Slug')}</Label>
                                    <Input
                                        id="slug"
                                        value={slug}
                                        onChange={(e) => setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
                                        placeholder={__('e.g., about-us')}
                                        disabled={isPending}
                                    />
                                    <p className="text-xs text-muted-foreground truncate">
                                        <span className="font-mono text-primary">{siteUrl}/{slug || 'page'}</span>
                                    </p>
                                </div>
                            </div>

                            <div className="space-y-3">
                                <Label>{__('Choose a Layout')}</Label>
                                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                                    {pagePresets.map((tpl: any) => (
                                        <div
                                            key={tpl.id}
                                            className={`
                                                relative p-3 border rounded-lg cursor-pointer transition-all hover:bg-accent
                                                ${selectedTemplateId === tpl.id ? 'border-primary ring-1 ring-primary bg-primary/5' : 'border-border'}
                                            `}
                                            onClick={() => setSelectedTemplateId(tpl.id)}
                                        >
                                            <div className="mb-2 font-medium text-sm">{tpl.label}</div>
                                            <p className="text-xs text-muted-foreground line-clamp-2">{tpl.description}</p>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </TabsContent>

                        {/* ── CPT Template Tab ── */}
                        <TabsContent value="template" className="space-y-6 mt-0">
                            {availableCpts.length === 0 ? (
                                <div className="text-center py-8 text-muted-foreground text-sm space-y-2">
                                    <p className="font-medium">{__('All post types already have a template.')}</p>
                                    <p className="text-xs">{__('Abort an existing template first to create a new one.')}</p>
                                </div>
                            ) : (
                                <>
                                    <div className="space-y-2">
                                        <Label>{__('Select Post Type')}</Label>
                                        <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                                            {availableCpts.map((cpt) => (
                                                <div
                                                    key={cpt.cpt}
                                                    className={`
                                                        p-3 border rounded-lg cursor-pointer transition-all hover:bg-accent
                                                        ${selectedCpt === cpt.cpt ? 'border-primary ring-1 ring-primary bg-primary/5' : 'border-border'}
                                                    `}
                                                    onClick={() => setSelectedCpt(cpt.cpt || '')}
                                                >
                                                    <div className="font-medium text-sm">{cpt.title}</div>
                                                    {cpt.cpt && (
                                                        <p className="text-xs text-muted-foreground mt-1 font-mono">/{cpt.cpt}/</p>
                                                    )}
                                                </div>
                                            ))}
                                        </div>
                                    </div>

                                    <div className="space-y-3">
                                        <Label>{__('Starting Layout')}</Label>
                                        <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                                            {cptPresets.map((tpl: any) => (
                                                <div
                                                    key={tpl.id}
                                                    className={`
                                                        p-3 border rounded-lg cursor-pointer transition-all hover:bg-accent
                                                        ${selectedCptPreset === tpl.id ? 'border-primary ring-1 ring-primary bg-primary/5' : 'border-border'}
                                                    `}
                                                    onClick={() => setSelectedCptPreset(tpl.id)}
                                                >
                                                    <div className="font-medium text-sm">{tpl.label}</div>
                                                    <p className="text-xs text-muted-foreground line-clamp-2 mt-1">{tpl.description}</p>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                </>
                            )}
                        </TabsContent>
                    </Tabs>
                </div>

                <DialogFooter>
                    <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isPending}>
                        {__('Cancel')}
                    </Button>
                    <Button onClick={handleSubmit} disabled={isDisabled}>
                        {isPending ? (
                            <>
                                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                                {__('Creating...')}
                            </>
                        ) : (
                            mode === 'page' ? __('Create Page') : __('Create Template')
                        )}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}
