import React, { useState, useEffect, useRef } from 'react';
import { useMutation } 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 { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { toast } from 'sonner';
import { FileText, Layout, Loader2 } from 'lucide-react';

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

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

export function CreatePageModal({ open, onOpenChange, onCreated }: CreatePageModalProps) {
    const [pageType, setPageType] = useState<'page' | 'template'>('page');
    const [title, setTitle] = useState('');
    const [slug, setSlug] = useState('');

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

    // Get site URL from WordPress config
    const siteUrl = window.WNW_CONFIG?.siteUrl?.replace(/\/$/, '') || window.location.origin;

    // Create page mutation
    const createMutation = useMutation({
        mutationFn: async (data: { title: string; slug: string }) => {
            // Guard against double submission
            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 });
                return response.data;
            } finally {
                // Reset after a delay to prevent race conditions
                setTimeout(() => {
                    isSubmittingRef.current = false;
                }, 500);
            }
        },
        onSuccess: (data) => {
            if (data?.page) {
                toast.success(__('Page created successfully'));
                onCreated({
                    id: data.page.id,
                    type: 'page',
                    slug: data.page.slug,
                    title: data.page.title,
                });
                onOpenChange(false);
                setTitle('');
                setSlug('');
            }
        },
        onError: (error: any) => {
            // Don't show error for duplicate prevention
            if (error?.message === 'Request already in progress') {
                return;
            }
            // Extract error message from the response
            const message = error?.response?.data?.message ||
                error?.message ||
                __('Failed to create page');
            toast.error(message);
        },
    });

    // Auto-generate slug from title
    const handleTitleChange = (value: string) => {
        setTitle(value);
        // Auto-generate slug only if slug matches the previously auto-generated 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, ''));
        }
    };

    // Handle form submission
    const handleSubmit = () => {
        if (createMutation.isPending || isSubmittingRef.current) {
            return;
        }
        if (pageType === 'page' && title && slug) {
            createMutation.mutate({ title, slug });
        }
    };

    // Reset form when modal closes
    useEffect(() => {
        if (!open) {
            setTitle('');
            setSlug('');
            setPageType('page');
            isSubmittingRef.current = false;
        }
    }, [open]);

    const isDisabled = pageType === 'page' && (!title || !slug) || createMutation.isPending || isSubmittingRef.current;

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

                <div className="space-y-6 py-4 px-1">
                    {/* Page Type Selection */}
                    <RadioGroup value={pageType} onValueChange={(v) => setPageType(v as 'page' | 'template')}>
                        <div className="flex items-start space-x-3 p-4 border rounded-lg cursor-pointer hover:bg-accent/50 transition-colors">
                            <RadioGroupItem value="page" id="page" className="mt-1" />
                            <div className="flex-1">
                                <Label htmlFor="page" className="flex items-center gap-2 cursor-pointer font-medium">
                                    <FileText className="w-4 h-4" />
                                    {__('Structural Page')}
                                </Label>
                                <p className="text-sm text-muted-foreground mt-1">
                                    {__('Static content like About, Contact, Terms')}
                                </p>
                            </div>
                        </div>

                        <div className="flex items-start space-x-3 p-4 border rounded-lg cursor-pointer opacity-50">
                            <RadioGroupItem value="template" id="template" className="mt-1" disabled />
                            <div className="flex-1">
                                <Label htmlFor="template" className="flex items-center gap-2 cursor-pointer font-medium">
                                    <Layout className="w-4 h-4" />
                                    {__('CPT Template')}
                                </Label>
                                <p className="text-sm text-muted-foreground mt-1">
                                    {__('Templates are auto-created for each post type')}
                                </p>
                            </div>
                        </div>
                    </RadioGroup>

                    {/* Page Details */}
                    {pageType === 'page' && (
                        <div className="space-y-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={createMutation.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={createMutation.isPending}
                                />
                                <p className="text-xs text-muted-foreground">
                                    {__('URL will be: ')}<span className="font-mono text-primary">{siteUrl}/{slug || 'page-slug'}</span>
                                </p>
                            </div>
                        </div>
                    )}
                </div>

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