import React, { useState, useEffect, useRef } from 'react';
import { api } from '@/lib/api';
import { __ } from '@/lib/i18n';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Settings, Eye, Smartphone, Monitor, ExternalLink, RefreshCw, Loader2 } from 'lucide-react';

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

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

interface AvailableSource {
    value: string;
    label: string;
}

interface PageSettingsProps {
    page: PageItem | null;
    section: Section | null;
    sections: Section[]; // All sections for preview
    onSectionUpdate: (section: Section) => void;
    isTemplate?: boolean;
    availableSources?: AvailableSource[];
}

// Section field configs
const SECTION_FIELDS: Record<string, { name: string; type: 'text' | 'textarea' | 'url' | 'image'; dynamic?: boolean }[]> = {
    hero: [
        { name: 'title', type: 'text', dynamic: true },
        { name: 'subtitle', type: 'text', dynamic: true },
        { name: 'image', type: 'image', dynamic: true },
        { name: 'cta_text', type: 'text' },
        { name: 'cta_url', type: 'url' },
    ],
    content: [
        { name: 'content', type: 'textarea', dynamic: true },
    ],
    'image-text': [
        { name: 'title', type: 'text', dynamic: true },
        { name: 'text', type: 'textarea', dynamic: true },
        { name: 'image', type: 'image', dynamic: true },
    ],
    'feature-grid': [
        { name: 'heading', type: 'text' },
    ],
    'cta-banner': [
        { name: 'title', type: 'text' },
        { name: 'text', type: 'text' },
        { name: 'button_text', type: 'text' },
        { name: 'button_url', type: 'url' },
    ],
    'contact-form': [
        { name: 'title', type: 'text' },
        { name: 'webhook_url', type: 'url' },
        { name: 'redirect_url', type: 'url' },
    ],
};

const LAYOUT_OPTIONS: Record<string, { value: string; label: string }[]> = {
    hero: [
        { value: 'default', label: 'Centered' },
        { value: 'hero-left-image', label: 'Image Left' },
        { value: 'hero-right-image', label: 'Image Right' },
    ],
    'image-text': [
        { value: 'image-left', label: 'Image Left' },
        { value: 'image-right', label: 'Image Right' },
    ],
    'feature-grid': [
        { value: 'grid-2', label: '2 Columns' },
        { value: 'grid-3', label: '3 Columns' },
        { value: 'grid-4', label: '4 Columns' },
    ],
    content: [
        { value: 'default', label: 'Full Width' },
        { value: 'narrow', label: 'Narrow' },
        { value: 'medium', label: 'Medium' },
    ],
};

const COLOR_SCHEMES = [
    { value: 'default', label: 'Default' },
    { value: 'primary', label: 'Primary' },
    { value: 'secondary', label: 'Secondary' },
    { value: 'muted', label: 'Muted' },
    { value: 'gradient', label: 'Gradient' },
];

export function PageSettings({
    page,
    section,
    sections,
    onSectionUpdate,
    isTemplate = false,
    availableSources = [],
}: PageSettingsProps) {
    const [previewMode, setPreviewMode] = useState<'desktop' | 'mobile'>('desktop');
    const [previewHtml, setPreviewHtml] = useState<string | null>(null);
    const [previewLoading, setPreviewLoading] = useState(false);
    const [showPreview, setShowPreview] = useState(false);
    const iframeRef = useRef<HTMLIFrameElement>(null);
    const previewTimeoutRef = useRef<NodeJS.Timeout | null>(null);

    // Debounced preview fetch
    useEffect(() => {
        if (!page || !showPreview) return;

        // Clear existing timeout
        if (previewTimeoutRef.current) {
            clearTimeout(previewTimeoutRef.current);
        }

        // Debounce preview updates
        previewTimeoutRef.current = setTimeout(async () => {
            setPreviewLoading(true);
            try {
                const endpoint = page.type === 'page'
                    ? `/preview/page/${page.slug}`
                    : `/preview/template/${page.cpt}`;

                const response = await api.post(endpoint, { sections });
                if (response?.html) {
                    setPreviewHtml(response.html);
                }
            } catch (error) {
                console.error('Preview error:', error);
            } finally {
                setPreviewLoading(false);
            }
        }, 500);

        return () => {
            if (previewTimeoutRef.current) {
                clearTimeout(previewTimeoutRef.current);
            }
        };
    }, [page, sections, showPreview]);

    // Update iframe when HTML changes
    useEffect(() => {
        if (iframeRef.current && previewHtml) {
            const doc = iframeRef.current.contentDocument;
            if (doc) {
                doc.open();
                doc.write(previewHtml);
                doc.close();
            }
        }
    }, [previewHtml]);

    // Manual refresh
    const handleRefreshPreview = async () => {
        if (!page) return;
        setPreviewLoading(true);
        try {
            const endpoint = page.type === 'page'
                ? `/preview/page/${page.slug}`
                : `/preview/template/${page.cpt}`;

            const response = await api.post(endpoint, { sections });
            if (response?.html) {
                setPreviewHtml(response.html);
            }
        } catch (error) {
            console.error('Preview error:', error);
        } finally {
            setPreviewLoading(false);
        }
    };

    // Update section prop
    const updateProp = (name: string, value: any, isDynamic?: boolean) => {
        if (!section) return;

        const newProps = { ...section.props };
        if (isDynamic) {
            newProps[name] = { type: 'dynamic', source: value };
        } else {
            newProps[name] = { type: 'static', value };
        }

        onSectionUpdate({ ...section, props: newProps });
    };

    // Get prop value
    const getPropValue = (name: string): string => {
        const prop = section?.props[name];
        if (!prop) return '';
        if (typeof prop === 'object') {
            return prop.type === 'dynamic' ? prop.source : prop.value || '';
        }
        return String(prop);
    };

    // Check if prop is dynamic
    const isPropDynamic = (name: string): boolean => {
        const prop = section?.props[name];
        return typeof prop === 'object' && prop?.type === 'dynamic';
    };

    // Render field based on type
    const renderField = (field: { name: string; type: string; dynamic?: boolean }) => {
        const value = getPropValue(field.name);
        const isDynamic = isPropDynamic(field.name);
        const fieldLabel = field.name.charAt(0).toUpperCase() + field.name.slice(1).replace('_', ' ');

        return (
            <div key={field.name} className="space-y-2">
                <div className="flex items-center justify-between">
                    <Label>{fieldLabel}</Label>
                    {field.dynamic && isTemplate && (
                        <div className="flex items-center gap-2">
                            <span className="text-xs text-gray-500">
                                {isDynamic ? '◆ Dynamic' : 'Static'}
                            </span>
                            <Switch
                                checked={isDynamic}
                                onCheckedChange={(checked) => {
                                    if (checked) {
                                        updateProp(field.name, 'post_title', true);
                                    } else {
                                        updateProp(field.name, '', false);
                                    }
                                }}
                            />
                        </div>
                    )}
                </div>

                {isDynamic && isTemplate ? (
                    <Select
                        value={value}
                        onValueChange={(v) => updateProp(field.name, v, true)}
                    >
                        <SelectTrigger>
                            <SelectValue placeholder={__('Select source')} />
                        </SelectTrigger>
                        <SelectContent>
                            {availableSources.map(source => (
                                <SelectItem key={source.value} value={source.value}>
                                    {source.label}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                ) : field.type === 'textarea' ? (
                    <Textarea
                        value={value}
                        onChange={(e) => updateProp(field.name, e.target.value)}
                        rows={4}
                    />
                ) : (
                    <Input
                        type={field.type === 'url' ? 'url' : 'text'}
                        value={value}
                        onChange={(e) => updateProp(field.name, e.target.value)}
                    />
                )}
            </div>
        );
    };

    return (
        <div className="w-80 border-l bg-white flex flex-col">
            <div className="flex-1 overflow-y-auto">
                <div className="p-4 space-y-6">
                    {/* Page Info */}
                    {page && !section && (
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-sm flex items-center gap-2">
                                    <Settings className="w-4 h-4" />
                                    {isTemplate ? __('Template Settings') : __('Page Settings')}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3">
                                <div>
                                    <Label>{__('Type')}</Label>
                                    <p className="text-sm text-gray-600">
                                        {isTemplate ? __('Template (Dynamic)') : __('Page (Structural)')}
                                    </p>
                                </div>
                                {page.url && (
                                    <div>
                                        <Label>{__('URL')}</Label>
                                        <a
                                            href={page.url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="text-sm text-primary hover:underline flex items-center gap-1"
                                        >
                                            {page.url}
                                            <ExternalLink className="w-3 h-3" />
                                        </a>
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    )}

                    {/* Section Settings */}
                    {section && (
                        <>
                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm">{__('Section Settings')}</CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    {/* Layout Variant */}
                                    {LAYOUT_OPTIONS[section.type] && (
                                        <div className="space-y-2">
                                            <Label>{__('Layout')}</Label>
                                            <Select
                                                value={section.layoutVariant || 'default'}
                                                onValueChange={(v) => onSectionUpdate({ ...section, layoutVariant: v })}
                                            >
                                                <SelectTrigger>
                                                    <SelectValue />
                                                </SelectTrigger>
                                                <SelectContent>
                                                    {LAYOUT_OPTIONS[section.type].map(opt => (
                                                        <SelectItem key={opt.value} value={opt.value}>
                                                            {opt.label}
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                        </div>
                                    )}

                                    {/* Color Scheme */}
                                    <div className="space-y-2">
                                        <Label>{__('Color Scheme')}</Label>
                                        <Select
                                            value={section.colorScheme || 'default'}
                                            onValueChange={(v) => onSectionUpdate({ ...section, colorScheme: v })}
                                        >
                                            <SelectTrigger>
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                {COLOR_SCHEMES.map(opt => (
                                                    <SelectItem key={opt.value} value={opt.value}>
                                                        {opt.label}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                    </div>
                                </CardContent>
                            </Card>

                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-sm">{__('Content')}</CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-4">
                                    {SECTION_FIELDS[section.type]?.map(renderField)}
                                </CardContent>
                            </Card>
                        </>
                    )}

                    {/* Preview Panel */}
                    <Card>
                        <CardHeader className="pb-3">
                            <CardTitle className="text-sm flex items-center justify-between">
                                <span className="flex items-center gap-2">
                                    <Eye className="w-4 h-4" />
                                    {__('Preview')}
                                </span>
                                {showPreview && (
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-6 w-6"
                                        onClick={handleRefreshPreview}
                                        disabled={previewLoading}
                                    >
                                        <RefreshCw className={`w-3 h-3 ${previewLoading ? 'animate-spin' : ''}`} />
                                    </Button>
                                )}
                            </CardTitle>
                        </CardHeader>
                        <CardContent>
                            {/* Preview Mode Toggle */}
                            <div className="flex gap-2 mb-3">
                                <Button
                                    variant={previewMode === 'desktop' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setPreviewMode('desktop')}
                                >
                                    <Monitor className="w-4 h-4 mr-1" />
                                    {__('Desktop')}
                                </Button>
                                <Button
                                    variant={previewMode === 'mobile' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setPreviewMode('mobile')}
                                >
                                    <Smartphone className="w-4 h-4 mr-1" />
                                    {__('Mobile')}
                                </Button>
                            </div>

                            {/* Preview Toggle */}
                            {!showPreview ? (
                                <Button
                                    variant="outline"
                                    className="w-full"
                                    onClick={() => setShowPreview(true)}
                                    disabled={!page}
                                >
                                    <Eye className="w-4 h-4 mr-2" />
                                    {__('Show Preview')}
                                </Button>
                            ) : (
                                <div className="space-y-2">
                                    {/* Preview Iframe Container */}
                                    <div
                                        className="relative bg-gray-100 rounded-lg overflow-hidden border"
                                        style={{
                                            height: '300px',
                                            width: previewMode === 'mobile' ? '200px' : '100%',
                                            margin: previewMode === 'mobile' ? '0 auto' : undefined,
                                        }}
                                    >
                                        {previewLoading && (
                                            <div className="absolute inset-0 bg-white/80 flex items-center justify-center z-10">
                                                <Loader2 className="w-6 h-6 animate-spin text-primary" />
                                            </div>
                                        )}
                                        <iframe
                                            ref={iframeRef}
                                            className="w-full h-full border-0"
                                            title="Page Preview"
                                            sandbox="allow-same-origin"
                                            style={{
                                                transform: previewMode === 'mobile' ? 'scale(0.5)' : 'scale(0.4)',
                                                transformOrigin: 'top left',
                                                width: previewMode === 'mobile' ? '400px' : '250%',
                                                height: previewMode === 'mobile' ? '600px' : '750px',
                                            }}
                                        />
                                    </div>
                                    <Button
                                        variant="ghost"
                                        size="sm"
                                        className="w-full text-xs"
                                        onClick={() => setShowPreview(false)}
                                    >
                                        {__('Hide Preview')}
                                    </Button>
                                </div>
                            )}
                        </CardContent>
                    </Card>
                </div>
            </div>
        </div>
    );
}
