import React, { useState, useEffect } from "react";
import { FiMonitor, FiLink2, FiX, FiSearch } from "react-icons/fi";
import styles from "../../chatbot/components/ChatbotSettings.module.css";
import { useDebounce } from "use-debounce";

interface FAQsPageTabProps {
    layout: string;
    setLayout: (layout: string) => void;
    colorSubTab: string;
    setColorSubTab: (tab: string) => void;
    pageSettings: any;
    onUpdate: (settings: any) => void;
    categories: any[];
}

export function FAQsPageTab({
    layout,
    setLayout,
    colorSubTab,
    setColorSubTab,
    pageSettings,
    onUpdate,
    categories
}: FAQsPageTabProps) {
    const [desktopPreviewOpen, setDesktopPreviewOpen] = useState(false);

    // Initialize state from props safely
    const [settings, setSettings] = useState(() => ({
        is_enabled: pageSettings?.is_enabled ?? true,
        appearance: {
            layout: pageSettings?.appearance?.layout ?? "1 page",
            colors: {
                title: pageSettings?.appearance?.colors?.title ?? "#0E61BD",
                page_background: pageSettings?.appearance?.colors?.page_background ?? "#D5E9C1",
                question_text: pageSettings?.appearance?.colors?.question_text ?? "#232323",
                question_background: pageSettings?.appearance?.colors?.question_background ?? "#ECF2FA",
                answer_text: pageSettings?.appearance?.colors?.answer_text ?? "#616161",
                answer_background: pageSettings?.appearance?.colors?.answer_background ?? "#E3ACAC",
                button_label: pageSettings?.appearance?.colors?.button_label ?? "#6F1E1E",
                button_background: pageSettings?.appearance?.colors?.button_background ?? "#5B93D0",
                color_preset: pageSettings?.appearance?.colors?.color_preset ?? "Blue",
                is_custom: pageSettings?.appearance?.colors?.is_custom ?? false
            }
        },
        header: {
            logo: pageSettings?.header?.logo ?? "",
            heading: pageSettings?.header?.heading ?? "Frequently Asked Questions",
            description: pageSettings?.header?.description ?? "Got a question? We are here to answer!",
            banner_enabled: pageSettings?.header?.banner_enabled ?? true
        },
        contact_us: {
            is_display_enabled: pageSettings?.contact_us?.is_display_enabled ?? true
        }
    }));

    // Local override for app state (so pill tabs sync)
    useEffect(() => {
        if (settings.appearance.layout !== layout) setLayout(settings.appearance.layout);
        if (settings.appearance.colors.is_custom !== (colorSubTab === "Custom Color")) {
            setColorSubTab(settings.appearance.colors.is_custom ? "Custom Color" : "Preset");
        }
    }, [settings.appearance.layout, settings.appearance.colors.is_custom]);

    // Handle debounced auto-save
    const [debouncedSettings] = useDebounce(settings, 1000);
    const [initialLoad, setInitialLoad] = useState(true);

    useEffect(() => {
        if (initialLoad) {
            setInitialLoad(false);
            return;
        }
        onUpdate(debouncedSettings);
    }, [debouncedSettings]);

    const updateNested = (path: string[], value: any) => {
        setSettings(prev => {
            const next = JSON.parse(JSON.stringify(prev));
            let curr = next;
            for (let i = 0; i < path.length - 1; i++) {
                if (!curr[path[i]]) curr[path[i]] = {};
                curr = curr[path[i]];
            }
            curr[path[path.length - 1]] = value;
            return next;
        });
    };

    const handlePresetChange = (presetName: string, colors: any) => {
        updateNested(['appearance', 'colors', 'color_preset'], presetName);
        Object.keys(colors).forEach(k => {
            updateNested(['appearance', 'colors', k], colors[k]);
        });
        updateNested(['appearance', 'colors', 'is_custom'], false);
    };

    const renderPreviewList = () => {
        const c = settings.appearance.colors;
        
        return categories.map(cat => (
            <div key={cat.category_id} style={{ marginBottom: '16px' }}>
                <div style={{ fontSize: '12px', fontWeight: 700, color: c.title, marginBottom: '8px' }}>
                    {cat.category_name}
                </div>
                {cat.faqs.map((faq: any) => (
                    <div key={faq.faq_id} style={{ background: c.question_background, border: 'none', borderRadius: '8px', padding: '12px', marginBottom: '8px', display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: c.question_text }}>
                        <span>{faq.question}</span>
                        <span>▾</span>
                    </div>
                ))}
            </div>
        ));
    };

    const renderPreviewCards = () => {
        const c = settings.appearance.colors;
        
        return (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '16px' }}>
                {categories.map(cat => (
                    <div key={cat.category_id} style={{ border: 'none', borderRadius: '8px', padding: '16px 12px', textAlign: 'center', background: c.question_background }}>
                        <div style={{ 
                            width: '32px', height: '32px', borderRadius: '8px', 
                            background: `${c.title}15`, color: c.title, 
                            display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 8px', fontSize: '14px' 
                        }}>📁</div>
                        <div style={{ fontSize: '11px', fontWeight: 600, color: c.question_text, marginBottom: '4px' }}>{cat.category_name}</div>
                        <div style={{ fontSize: '9px', color: '#6b7280' }}>{cat.faq_count} Articles</div>
                    </div>
                ))}
            </div>
        );
    };

    return (
        <div className={styles.faqPageLayout}>
            <div className={styles.settingsPanel}>
                {/* Display FAQ Toggle */}
                <div className={styles.appearanceCard} style={{ padding: '16px 24px', marginBottom: '16px' }}>
                    <div className={styles.toggleRow}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                            <span style={{ fontSize: '14px', fontWeight: 600 }}>Display FAQs page</span>
                        </div>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={settings.is_enabled} 
                                onChange={(e) => updateNested(['is_enabled'], e.target.checked)} 
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>
                </div>

                {/* Appearance Section */}
                <div className={styles.appearanceCard}>
                    <h3 className={styles.cardSectionTitle}>Appearance</h3>

                    <div className={styles.labelGroup}>
                        <label className={styles.settingsInputLabel}>Layout</label>
                        <div className={styles.layoutSelectionGrid}>
                            <div
                                className={`${styles.layoutItem} ${settings.appearance.layout === '1 page' ? styles.layoutActive : ''}`}
                                onClick={() => updateNested(['appearance', 'layout'], '1 page')}
                            >
                                <div className={styles.layoutPreviewBox}>
                                    <div className={styles.layoutThumbnail}>
                                        <div className={styles.thumbLine}></div>
                                        <div className={styles.thumbLine} style={{ opacity: 0.8 }}></div>
                                        <div className={styles.thumbLine} style={{ opacity: 0.6 }}></div>
                                    </div>
                                </div>
                                <h4 className={styles.layoutInfoTitle}>1 page layout</h4>
                                <p className={styles.layoutInfoDesc}>Best for simple FAQs, showing all questions in one list</p>
                            </div>
                            <div
                                className={`${styles.layoutItem} ${settings.appearance.layout === 'card' ? styles.layoutActive : ''}`}
                                onClick={() => updateNested(['appearance', 'layout'], 'card')}
                            >
                                <div className={styles.layoutPreviewBox}>
                                    <div className={styles.cardGridThumb}>
                                        {[1, 2, 3, 4, 5, 6].map(i => <div key={i} className={styles.thumbSquare}></div>)}
                                    </div>
                                </div>
                                <h4 className={styles.layoutInfoTitle}>Card layout</h4>
                                <p className={styles.layoutInfoDesc}>Best for detailed help center, grouping questions into categories</p>
                            </div>
                        </div>
                    </div>

                    <div className={styles.colorSection}>
                        <label className={styles.settingsInputLabel}>Color</label>
                        <div className={styles.colorTabs}>
                            {["Preset", "Custom Color"].map(tab => {
                                const isActive = tab === "Preset" ? !settings.appearance.colors.is_custom : settings.appearance.colors.is_custom;
                                return (
                                    <div
                                        key={tab}
                                        className={`${styles.colorTab} ${isActive ? styles.colorTabActive : ""}`}
                                        onClick={() => updateNested(['appearance', 'colors', 'is_custom'], tab === "Custom Color")}
                                    >
                                        {tab}
                                    </div>
                                );
                            })}
                        </div>

                        {!settings.appearance.colors.is_custom ? (
                            <div className={styles.presetGrid}>
                                {[
                                    { name: "Light", p: { title: "#111827", page_background: "#f9fafb", question_text: "#111827", question_background: "#ffffff", answer_text: "#4b5563", answer_background: "#ffffff", button_label: "#ffffff", button_background: "#111827" } },
                                    { name: "Dark", p: { title: "#f9fafb", page_background: "#1f2937", question_text: "#f9fafb", question_background: "#374151", answer_text: "#d1d5db", answer_background: "#374151", button_label: "#1f2937", button_background: "#f9fafb" } },
                                    { name: "Blue", p: { title: "#2563eb", page_background: "#eff6ff", question_text: "#1e3a8a", question_background: "#ffffff", answer_text: "#3b82f6", answer_background: "#ffffff", button_label: "#ffffff", button_background: "#2563eb" } },
                                    { name: "Green", p: { title: "#059669", page_background: "#ecfdf5", question_text: "#064e3b", question_background: "#ffffff", answer_text: "#10b981", answer_background: "#ffffff", button_label: "#ffffff", button_background: "#059669" } }
                                ].map(preset => (
                                    <div 
                                        key={preset.name} 
                                        className={styles.presetItem}
                                        style={{ border: settings.appearance.colors.color_preset === preset.name ? '2px solid #7c3aed' : '' }}
                                        onClick={() => handlePresetChange(preset.name, preset.p)}
                                    >
                                        <div className={styles.presetCircle} style={{ background: preset.p.title }}></div>
                                        <span style={{ fontSize: '13px', fontWeight: 500 }}>{preset.name}</span>
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <div className={styles.customColorGrid} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginTop: '16px' }}>
                                {[
                                    { label: "Title", keyPath: ['appearance', 'colors', 'title'] },
                                    { label: "Page background", keyPath: ['appearance', 'colors', 'page_background'] },
                                    { label: "Question text", keyPath: ['appearance', 'colors', 'question_text'] },
                                    { label: "Question background", keyPath: ['appearance', 'colors', 'question_background'] },
                                    { label: "Answer text", keyPath: ['appearance', 'colors', 'answer_text'] },
                                    { label: "Answer background", keyPath: ['appearance', 'colors', 'answer_background'] },
                                    { label: "Button label", keyPath: ['appearance', 'colors', 'button_label'] },
                                    { label: "Button background", keyPath: ['appearance', 'colors', 'button_background'] },
                                ].map(c => {
                                    const val = c.keyPath.reduce((obj: any, key: any) => obj[key], settings) as string;
                                    return (
                                        <div 
                                            key={c.label} 
                                            className={styles.colorPickerItem}
                                            style={{ display: 'flex', alignItems: 'center', gap: '12px' }}
                                        >
                                            <input 
                                                type="color" 
                                                value={val} 
                                                onChange={(e) => updateNested(c.keyPath, e.target.value)}
                                                style={{ width: '32px', height: '32px', padding: 0, border: 'none', borderRadius: '4px', cursor: 'pointer', outline: 'none' }}
                                            />
                                            <div className={styles.pickerInfo} style={{ display: 'flex', flexDirection: 'column' }}>
                                                <span className={styles.pickerLabel} style={{ fontSize: '12px', color: '#4b5563' }}>{c.label}</span>
                                                <span className={styles.pickerHex} style={{ fontSize: '11px', color: '#9ca3af' }}>{val.toUpperCase()}</span>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>
                </div>

                {/* Header Section */}
                <div className={styles.headerCard}>
                    <h3 className={styles.cardSectionTitle}>Header</h3>
                    <div className={styles.labelGroup}>
                        <label className={styles.settingsInputLabel}>Heading</label>
                        <input
                            type="text"
                            className={styles.chatInput}
                            style={{ textAlign: 'left', width: '100%', maxWidth: '100%', marginTop: '8px' }}
                            value={settings.header.heading}
                            onChange={(e) => updateNested(['header', 'heading'], e.target.value)}
                        />
                    </div>
                    <div className={styles.labelGroup}>
                        <label className={styles.settingsInputLabel}>Description</label>
                        <textarea
                            className={styles.instructionTextArea}
                            style={{ marginTop: '8px', minHeight: '80px' }}
                            value={settings.header.description}
                            onChange={(e) => updateNested(['header', 'description'], e.target.value)}
                        />
                    </div>
                    <div className={styles.toggleRow}>
                        <span style={{ fontSize: '14px', fontWeight: 600 }}>Banner</span>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={settings.header.banner_enabled}
                                onChange={(e) => updateNested(['header', 'banner_enabled'], e.target.checked)} 
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>
                </div>

                {/* Contact Section */}
                <div className={styles.contactCard}>
                    <h3 className={styles.cardSectionTitle}>Contact us</h3>
                    <div className={styles.toggleRow} style={{ marginBottom: '8px' }}>
                        <span style={{ fontSize: '14px', fontWeight: 600 }}>Display contact us</span>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={settings.contact_us.is_display_enabled}
                                onChange={(e) => updateNested(['contact_us', 'is_display_enabled'], e.target.checked)}
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>
                    <p style={{ fontSize: '12px', color: '#6b7280' }}>Allow customers to contact you via chatbot or email.</p>
                </div>
            </div>

            {/* Preview Sidebar */}
            <div className={styles.previewSidebar}>
                <div className={styles.feedbackCard} style={{ padding: '24px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                        <h3 className={styles.cardSectionTitle} style={{ margin: 0 }}>Preview</h3>
                        <div className={styles.actionIconBtn} style={{ width: '100px', gap: '8px', fontSize: '13px', cursor: 'pointer' }} onClick={() => setDesktopPreviewOpen(true)}>
                            <FiMonitor /> Desktop
                        </div>
                    </div>
                    <div className={styles.phoneFrame} style={{ borderColor: '#e5e7eb', background: '#fafafa', borderRadius: '32px', overflow: 'hidden' }}>
                        <div className={styles.chatBody} style={{ padding: '20px 16px', background: settings.appearance.colors.page_background, minHeight: '100%' }}>
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', color: settings.appearance.colors.question_text }}>
                                <div style={{ fontWeight: 800, fontSize: '14px' }}>☰</div>
                                <div style={{ fontWeight: 800, fontSize: '12px' }}>YOUR STORE</div>
                                <div style={{ display: 'flex', gap: '12px' }}>
                                    <div style={{ fontSize: '12px' }}>🔍</div>
                                    <div style={{ fontSize: '12px' }}>🛒</div>
                                </div>
                            </div>

                            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
                                <h5 style={{ fontSize: '16px', fontWeight: 700, margin: '0 0 6px', color: settings.appearance.colors.title }}>{settings.header.heading}</h5>
                                <p style={{ fontSize: '11px', color: '#6b7280' }}>{settings.header.description}</p>
                            </div>

                            <div style={{ position: 'relative', marginBottom: '24px' }}>
                                <input type="text" style={{ width: '100%', fontSize: '12px', padding: '10px 14px', borderRadius: '8px', border: '1px solid #d1d5db', background: '#fff' }} placeholder="Type keyword to find your answer" />
                            </div>

                            {settings.appearance.layout === 'card' && renderPreviewCards()}
                            
                            {settings.appearance.layout === '1 page' ? renderPreviewList() : (
                                <div style={{ marginTop: '16px' }}>
                                    <div style={{ display: 'flex', gap: '12px', marginBottom: '16px', overflowX: 'auto', paddingBottom: '4px' }}>
                                        <span style={{ fontWeight: 600, fontSize: '11px', color: settings.appearance.colors.answer_text, borderBottom: `2px solid ${settings.appearance.colors.answer_text}`, paddingBottom: '4px' }}>All</span>
                                        {categories.map((c, i) => (
                                            <span key={i} style={{ color: settings.appearance.colors.title, fontSize: '11px', whiteSpace: 'nowrap', fontWeight: 600 }}>{c.category_name}</span>
                                        ))}
                                    </div>
                                    {renderPreviewList()}
                                </div>
                            )}

                            {settings.contact_us.is_display_enabled && (
                                <div style={{ marginTop: '24px', textAlign: 'center', padding: '16px', background: '#fff', borderRadius: '8px', border: '1px solid #e5e7eb' }}>
                                    <h4 style={{ fontSize: '13px', fontWeight: 600, color: settings.appearance.colors.title, marginBottom: '8px', margin: 0 }}>Any other questions?</h4>
                                    <p style={{ fontSize: '11px', color: '#6b7280', marginBottom: '12px', marginTop: '8px' }}>We're here to help. You can contact us: Weekdays: 8am to 6pm.</p>
                                    <button style={{ background: settings.appearance.colors.button_background, color: settings.appearance.colors.button_label, border: 'none', borderRadius: '6px', padding: '8px 16px', fontSize: '12px', fontWeight: 600, cursor: 'pointer', width: '100%' }}>Contact us</button>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>

            {/* Desktop Preview Modal */}
            {desktopPreviewOpen && (
                <div className={styles.modalOverlay} onClick={() => setDesktopPreviewOpen(false)} style={{ zIndex: 100 }}>
                    <div className={styles.modalContent} style={{ width: '800px', height: '600px', borderRadius: '16px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }} onClick={e => e.stopPropagation()}>
                        <div className={styles.modalHeader} style={{ padding: '16px 24px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#111827', margin: 0 }}>Desktop preview</h2>
                            <button className={styles.closeButton} onClick={() => setDesktopPreviewOpen(false)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0 }}>
                                <FiX size={20} color="#6b7280" />
                            </button>
                        </div>
                        <div style={{ flex: 1, padding: '40px 60px', overflowY: 'auto', background: settings.appearance.colors.page_background }}>
                            <div style={{ textAlign: 'center', marginBottom: '40px' }}>
                                <h1 style={{ fontSize: '28px', fontWeight: 700, margin: '0 0 12px', color: settings.appearance.colors.title }}>{settings.header.heading}</h1>
                                <p style={{ fontSize: '14px', color: '#6b7280' }}>{settings.header.description}</p>
                            </div>

                            <div style={{ maxWidth: '600px', margin: '0 auto' }}>
                                <div style={{ position: 'relative', marginBottom: '40px' }}>
                                    <input type="text" style={{ width: '100%', fontSize: '14px', padding: '14px 20px', borderRadius: '12px', border: '1px solid #d1d5db' }} placeholder="Type keyword to find your answer" />
                                </div>

                                {settings.appearance.layout === 'card' && (
                                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', marginBottom: '40px' }}>
                                        {categories.map(cat => (
                                            <div key={cat.category_id} style={{ border: 'none', borderRadius: '12px', padding: '24px', textAlign: 'center', background: settings.appearance.colors.question_background, cursor: 'pointer' }}>
                                                <div style={{ 
                                                    width: '48px', height: '48px', borderRadius: '12px', 
                                                    background: `${settings.appearance.colors.title}15`, color: settings.appearance.colors.title, 
                                                    display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', fontSize: '20px' 
                                                }}>📁</div>
                                                <div style={{ fontSize: '15px', fontWeight: 600, color: settings.appearance.colors.question_text, marginBottom: '8px' }}>{cat.category_name}</div>
                                                <div style={{ fontSize: '13px', color: '#6b7280' }}>{cat.faq_count} Articles</div>
                                            </div>
                                        ))}
                                    </div>
                                )}

                                <div>
                                    {settings.appearance.layout === '1 page' ? renderPreviewList() : (
                                        <div style={{ display: 'flex', gap: '32px' }}>
                                            <div style={{ width: '200px' }}>
                                                <div style={{ marginBottom: '16px', padding: '8px 12px', background: 'transparent', borderRadius: '8px', fontSize: '14px', fontWeight: 500, color: settings.appearance.colors.question_text }}>All</div>
                                                {categories.map(cat => (
                                                    <div key={cat.category_id} style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', padding: '4px 12px', fontSize: '14px', color: settings.appearance.colors.title, fontWeight: 600, cursor: 'pointer' }}>
                                                        <span>📁</span> {cat.category_name}
                                                    </div>
                                                ))}
                                            </div>
                                            <div style={{ flex: 1 }}>
                                                {renderPreviewList()}
                                            </div>
                                        </div>
                                    )}
                                </div>

                                {settings.contact_us.is_display_enabled && (
                                    <div style={{ marginTop: '40px', textAlign: 'center', padding: '32px', background: '#fff', borderRadius: '12px', border: '1px solid #e5e7eb' }}>
                                        <h4 style={{ fontSize: '18px', fontWeight: 600, color: settings.appearance.colors.title, marginBottom: '12px', margin: 0 }}>Any other questions?</h4>
                                        <p style={{ fontSize: '14px', color: '#6b7280', marginBottom: '20px', marginTop: '12px' }}>We're here to help. You can contact us: Weekdays: 8am to 6pm.</p>
                                        <button style={{ background: settings.appearance.colors.button_background, color: settings.appearance.colors.button_label, border: 'none', borderRadius: '8px', padding: '12px 24px', fontSize: '14px', fontWeight: 600, cursor: 'pointer' }}>Contact us</button>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
