import React, { useState } from "react";
import { FiChevronDown, FiChevronRight, FiGrid, FiEdit2, FiTrash2, FiStar, FiSearch, FiFilter, FiDownload, FiUpload, FiPlus, FiX } from "react-icons/fi";
import styles from "../../chatbot/components/ChatbotSettings.module.css";

interface FAQ {
    faq_id: string;
    question: string;
    answer_html: string;
    status: string;
    is_featured: boolean;
    external_link?: string;
    created_at: string;
}

interface Category {
    category_id: string;
    category_name: string;
    icon_identifier: string;
    status: string;
    display_position: number;
    is_featured: boolean;
    faq_count: number;
    faqs: FAQ[];
}

interface ManageFAQsTabProps {
    categories: Category[];
    expandedRows: string[];
    toggleRow: (id: string) => void;
    setIsAddDropdownOpen: (open: boolean) => void;
    isAddDropdownOpen: boolean;
    setIsAddFaqOpen: (open: boolean) => void;
    setIsAddCategoryOpen: (open: boolean) => void;
    onUpdate: (newCategories: Category[]) => void;
    setEditingCategory: (cat: Category | null) => void;
    setEditingFaq: (faq: any | null) => void;
}

export function ManageFAQsTab({
    categories,
    expandedRows,
    toggleRow,
    setIsAddDropdownOpen,
    isAddDropdownOpen,
    setIsAddFaqOpen,
    setIsAddCategoryOpen,
    onUpdate,
    setEditingCategory,
    setEditingFaq
}: ManageFAQsTabProps) {
    const [draggedCatIndex, setDraggedCatIndex] = useState<number | null>(null);
    const [draggedFaqInfo, setDraggedFaqInfo] = useState<{ catId: string, faqIndex: number } | null>(null);
    const [searchQuery, setSearchQuery] = useState("");
    const [deleteModalInfo, setDeleteModalInfo] = useState<{ type: 'category' | 'faq', catId: string, faqId?: string } | null>(null);

    // Local copy for optimistic drag reordering — only pushes to API on drop
    const [localCategories, setLocalCategories] = useState<Category[]>(categories);

    // Sync local state when categories prop changes (after API refetch)
    React.useEffect(() => {
        setLocalCategories(categories);
    }, [categories]);

    const displayCategories = localCategories;

    const filteredCategories = displayCategories.map(cat => {
        const matchesCat = cat.category_name.toLowerCase().includes(searchQuery.toLowerCase());
        const filteredFaqs = cat.faqs.filter(faq =>
            faq.question.toLowerCase().includes(searchQuery.toLowerCase())
        );
        if (matchesCat || filteredFaqs.length > 0) {
            return { ...cat, faqs: matchesCat && searchQuery ? cat.faqs : (searchQuery ? filteredFaqs : cat.faqs) };
        }
        return null;
    }).filter(Boolean) as Category[];

    const handleFeatureCategory = (cat: Category) => {
        const newCats = localCategories.map(c =>
            c.category_id === cat.category_id ? { ...c, is_featured: !c.is_featured } : c
        );
        setLocalCategories(newCats);
        onUpdate(newCats);
    };

    const handleFeatureFaq = (catId: string, faqId: string) => {
        const newCats = localCategories.map(c => {
            if (c.category_id === catId) {
                return { ...c, faqs: c.faqs.map(f => f.faq_id === faqId ? { ...f, is_featured: !f.is_featured } : f) };
            }
            return c;
        });
        setLocalCategories(newCats);
        onUpdate(newCats);
    };

    const handleDeleteCategory = (catId: string) => {
        setDeleteModalInfo({ type: 'category', catId });
    };

    const handleDeleteFaq = (catId: string, faqId: string) => {
        setDeleteModalInfo({ type: 'faq', catId, faqId });
    };

    const confirmDelete = () => {
        if (!deleteModalInfo) return;

        if (deleteModalInfo.type === 'category') {
            const catId = deleteModalInfo.catId;
            const catToDelete = localCategories.find(c => c.category_id === catId);
            if (!catToDelete) return;
            
            let newCats = localCategories.filter(c => c.category_id !== catId);

            if (catToDelete.faqs.length > 0) {
                // Find "Uncategorized"
                let uncategorized = newCats.find(c => c.category_name === "Uncategorized");
                if (uncategorized) {
                   const updatedUncat = {
                       ...uncategorized,
                       faqs: [...uncategorized.faqs, ...catToDelete.faqs],
                       faq_count: uncategorized.faqs.length + catToDelete.faqs.length
                   };
                   newCats = newCats.map(c => c.category_name === "Uncategorized" ? updatedUncat : c);
                } else {
                   uncategorized = {
                       category_id: `cat_${Date.now()}_uncat`,
                       category_name: "Uncategorized",
                       icon_identifier: "other",
                       status: "published",
                       display_position: newCats.length + 1,
                       is_featured: false,
                       faq_count: catToDelete.faqs.length,
                       faqs: catToDelete.faqs
                   };
                   newCats.push(uncategorized);
                }
            }
            // Fix positions
            newCats.sort((a, b) => a.display_position - b.display_position);
            newCats = newCats.map((c, i) => ({ ...c, display_position: i + 1 }));

            setLocalCategories(newCats);
            onUpdate(newCats);
            setDeleteModalInfo(null);
            
        } else if (deleteModalInfo.type === 'faq') {
            const { catId, faqId } = deleteModalInfo;
            const newCats = localCategories.map(c => {
                if (c.category_id === catId) {
                    const newFaqs = c.faqs.filter(f => f.faq_id !== faqId);
                    return { ...c, faqs: newFaqs, faq_count: newFaqs.length };
                }
                return c;
            });
            setLocalCategories(newCats);
            onUpdate(newCats);
            setDeleteModalInfo(null);
        }
    };

    const handleStatusToggle = (catId: string, faqId?: string) => {
        const newCats = localCategories.map(c => {
            if (c.category_id === catId) {
                if (!faqId) return { ...c, status: c.status === 'published' ? 'draft' : 'published' };
                return { ...c, faqs: c.faqs.map(f => f.faq_id === faqId ? { ...f, status: f.status === 'published' ? 'draft' : 'published' } : f) };
            }
            return c;
        });
        setLocalCategories(newCats);
        onUpdate(newCats);
    };

    // Category Drag & Drop — reorder locally, persist only on drop
    const onCatDragStart = (idx: number) => setDraggedCatIndex(idx);
    const onCatDragOver = (e: React.DragEvent, idx: number) => {
        e.preventDefault();
        if (draggedCatIndex === null || draggedCatIndex === idx) return;
        const newCats = [...localCategories];
        const item = newCats.splice(draggedCatIndex, 1)[0];
        newCats.splice(idx, 0, item);
        const reordered = newCats.map((c, i) => ({ ...c, display_position: i + 1 }));
        setDraggedCatIndex(idx);
        setLocalCategories(reordered); // visual update only
    };
    const onCatDragEnd = () => {
        setDraggedCatIndex(null);
        onUpdate(localCategories); // persist once on drop
    };

    // FAQ Drag & Drop — reorder locally, persist only on drop
    const onFaqDragStart = (catId: string, idx: number) => setDraggedFaqInfo({ catId, faqIndex: idx });
    const onFaqDragOver = (e: React.DragEvent, catId: string, idx: number) => {
        e.preventDefault();
        if (!draggedFaqInfo || draggedFaqInfo.catId !== catId || draggedFaqInfo.faqIndex === idx) return;
        const newCats = localCategories.map(c => {
            if (c.category_id === catId) {
                const newFaqs = [...c.faqs];
                const item = newFaqs.splice(draggedFaqInfo.faqIndex, 1)[0];
                newFaqs.splice(idx, 0, item);
                return { ...c, faqs: newFaqs };
            }
            return c;
        });
        setDraggedFaqInfo({ catId, faqIndex: idx });
        setLocalCategories(newCats); // visual update only
    };
    const onFaqDragEnd = () => {
        setDraggedFaqInfo(null);
        onUpdate(localCategories); // persist once on drop
    };

    return (
        <div className={styles.manageDataCard} style={{ background: 'white', borderRadius: '16px', border: '1px solid #e5e7eb' }}>
            <div className={styles.manageHeader} style={{ padding: '24px' }}>
                <div className={styles.manageTitleGroup}>
                    <h3 className={styles.toggleTitle} style={{ fontSize: '18px' }}>Manage FAQs</h3>
                    <p className={styles.toggleDesc}>Create and publish FAQs to build your FAQs page or provide knowledge for training AI assistant</p>
                </div>
                <div className={styles.dropdownWrapper}>
                    <button
                        className={styles.syncBtn}
                        style={{ background: '#7c3aed', gap: '8px', display: 'flex', alignItems: 'center', position: 'relative' }}
                        onClick={() => setIsAddDropdownOpen(!isAddDropdownOpen)}
                    >
                        Add new <FiChevronDown />
                    </button>
                    {isAddDropdownOpen && (
                        <div className={styles.dropdownMenu} style={{ zIndex: 100 }}>
                            <div className={styles.dropdownItem} onClick={() => { setIsAddFaqOpen(true); setIsAddDropdownOpen(false); }}>
                                <FiPlus /> Add FAQ
                            </div>
                            <div className={styles.dropdownItem} onClick={() => { setIsAddCategoryOpen(true); setIsAddDropdownOpen(false); }}>
                                <FiPlus /> Add Category
                            </div>
                        </div>
                    )}
                </div>
            </div>

            <div className={styles.manageSubTabs} style={{ padding: '0 24px 20px', border: 'none' }}>
                <div className={styles.inputGroup} style={{ flex: 1, maxWidth: '600px', flexDirection: 'row' }}>
                    <div style={{ position: 'relative', flex: 1 }}>
                        <FiSearch style={{ position: 'absolute', left: '12px', top: '14px', color: '#9ca3af' }} />
                        <input
                            type="text"
                            className={styles.chatInput}
                            placeholder="Search faqs, categories..."
                            style={{ paddingLeft: '40px', textAlign: 'left', maxWidth: '100%' }}
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                        />
                    </div>
                </div>
                <div className={styles.manageActions} style={{ marginLeft: '12px' }}>
                    <div className={styles.actionIconBtn}><FiFilter /></div>
                    <div className={styles.actionIconBtn}><FiDownload /></div>
                    <div className={styles.actionIconBtn}><FiUpload /></div>
                </div>
            </div>

            <div className={styles.tableWrapper} style={{ padding: '0 24px' }}>
                <table className={styles.tableContainer} style={{ width: '100%', margin: '0 0 24px' }}>
                    <thead>
                        <tr style={{ background: '#f9fafb' }}>
                            <th style={{ width: '40px' }}></th>
                            <th style={{ width: '40px' }}></th>
                            <th>FAQs</th>
                            <th>Status</th>
                            <th>Featured</th>
                            <th style={{ textAlign: 'right', paddingRight: '20px' }}>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {filteredCategories.map((cat, catIdx) => (
                            <React.Fragment key={cat.category_id}>
                                <tr 
                                    style={{ 
                                        borderBottom: expandedRows.includes(cat.category_id) ? 'none' : '1px solid #f3f4f6',
                                        opacity: draggedCatIndex === catIdx ? 0.4 : 1
                                    }}
                                    draggable
                                    onDragStart={() => onCatDragStart(catIdx)}
                                    onDragOver={(e) => onCatDragOver(e, catIdx)}
                                    onDragEnd={onCatDragEnd}
                                >
                                    <td><div className={styles.dragHandle} style={{ cursor: 'grab' }}><FiGrid size={14} /></div></td>
                                    <td>
                                        <div style={{ cursor: 'pointer' }} onClick={() => toggleRow(cat.category_id)}>
                                            {expandedRows.includes(cat.category_id) ? <FiChevronDown color="#6b7280" /> : <FiChevronRight color="#6b7280" />}
                                        </div>
                                    </td>
                                    <td>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                            <span style={{ fontSize: '16px' }}>
                                                {cat.icon_identifier === 'shopping_cart' ? '🛒'
                                                : cat.icon_identifier === 'exchange' ? '🔄'
                                                : cat.icon_identifier === 'payment' ? '💳'
                                                : '📁'}
                                            </span>
                                            <span style={{ fontWeight: 500 }}>{cat.category_name} ({cat.faq_count} FAQs)</span>
                                        </div>
                                    </td>
                                    <td>
                                        <span 
                                            className={`${styles.statusBadge} ${cat.status === 'published' ? styles.statusActive : styles.statusDisabled}`}
                                            onClick={() => handleStatusToggle(cat.category_id)}
                                            style={{ cursor: 'pointer' }}
                                        >
                                            {cat.status === 'published' ? 'Published' : 'Draft'}
                                        </span>
                                    </td>
                                    <td>
                                        <FiStar 
                                            size={18} 
                                            className={cat.is_featured ? styles.starIconActive : styles.starIcon} 
                                            onClick={() => handleFeatureCategory(cat)}
                                            style={{ cursor: 'pointer', color: cat.is_featured ? '#eab308' : '#d1d5db' }}
                                        />
                                    </td>
                                    <td style={{ textAlign: 'right', paddingRight: '20px' }}>
                                        <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
                                            <FiEdit2 style={{ cursor: 'pointer', color: '#6b7280' }} onClick={() => setEditingCategory(cat)} />
                                            <FiTrash2 style={{ cursor: 'pointer', color: '#ef4444' }} onClick={() => handleDeleteCategory(cat.category_id)} />
                                        </div>
                                    </td>
                                </tr>
                                {expandedRows.includes(cat.category_id) && (
                                    <>
                                        {cat.faqs.map((faq, faqIdx) => (
                                            <tr 
                                                key={faq.faq_id} 
                                                className={styles.nestedRow} 
                                                style={{ 
                                                    borderBottom: '1px solid #f3f4f6',
                                                    opacity: (draggedFaqInfo?.catId === cat.category_id && draggedFaqInfo?.faqIndex === faqIdx) ? 0.4 : 1
                                                }}
                                                draggable
                                                onDragStart={() => onFaqDragStart(cat.category_id, faqIdx)}
                                                onDragOver={(e) => onFaqDragOver(e, cat.category_id, faqIdx)}
                                                onDragEnd={onFaqDragEnd}
                                            >
                                                <td colSpan={2}></td>
                                                <td className={styles.nestedCell}>
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                                        <div className={styles.dragHandle} style={{ cursor: 'grab' }}><FiGrid size={12} /></div>
                                                        <span style={{ color: '#4b5563' }}>{faq.question}</span>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span 
                                                        className={`${styles.statusBadge} ${faq.status === 'published' ? styles.statusActive : styles.statusDisabled}`}
                                                        onClick={() => handleStatusToggle(cat.category_id, faq.faq_id)}
                                                        style={{ cursor: 'pointer' }}
                                                    >
                                                        {faq.status === 'published' ? 'Published' : 'Draft'}
                                                    </span>
                                                </td>
                                                <td>
                                                    <FiStar 
                                                        size={18} 
                                                        className={faq.is_featured ? styles.starIconActive : styles.starIcon} 
                                                        onClick={() => handleFeatureFaq(cat.category_id, faq.faq_id)}
                                                        style={{ cursor: 'pointer', color: faq.is_featured ? '#eab308' : '#d1d5db' }}
                                                    />
                                                </td>
                                                <td style={{ textAlign: 'right', paddingRight: '20px' }}>
                                                    <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
                                                        <FiEdit2 style={{ cursor: 'pointer', color: '#6b7280' }} onClick={() => setEditingFaq({ ...faq, category_id: cat.category_id })} />
                                                        <FiTrash2 style={{ cursor: 'pointer', color: '#ef4444' }} onClick={() => handleDeleteFaq(cat.category_id, faq.faq_id)} />
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                        <tr>
                                            <td colSpan={2}></td>
                                            <td colSpan={4} style={{ padding: '8px 0' }}>
                                                <button className={styles.addFaqInnerBtn} onClick={() => { setEditingFaq({ category_id: cat.category_id }); setIsAddFaqOpen(true); }} style={{ margin: '8px 0 8px 40px', background: 'none', border: '1px dashed #7c3aed', color: '#7c3aed', padding: '6px 16px', borderRadius: '8px', display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer', fontWeight: 600 }}>
                                                    <FiPlus /> Add FAQ
                                                </button>
                                            </td>
                                        </tr>
                                    </>
                                )}
                            </React.Fragment>
                        ))}
                    </tbody>
                </table>
                {filteredCategories.length === 0 && (
                    <div style={{ textAlign: 'center', padding: '48px 24px', color: '#9ca3af' }}>
                        <div style={{ fontSize: '40px', marginBottom: '12px' }}>📋</div>
                        <p style={{ fontWeight: 600, color: '#6b7280', marginBottom: '4px' }}>
                            {searchQuery ? 'No results found' : 'No categories yet'}
                        </p>
                        <p style={{ fontSize: '13px' }}>
                            {searchQuery
                                ? `Try a different search term`
                                : 'Click "Add new" to create your first FAQ category'}
                        </p>
                    </div>
                )}
            </div>

            {/* Custom Delete Modal */}
            {deleteModalInfo && (
                <div className={styles.modalOverlay} onClick={() => setDeleteModalInfo(null)}>
                    <div 
                        className={styles.modalContent} 
                        style={{ width: '500px', borderRadius: '12px', padding: 0 }} 
                        onClick={e => e.stopPropagation()}
                    >
                        <div className={styles.modalHeader} style={{ padding: '20px 24px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#111827', margin: 0 }}>
                                {deleteModalInfo.type === 'category' ? 'Delete Category?' : 'Delete FAQ?'}
                            </h2>
                            <button className={styles.closeButton} onClick={() => setDeleteModalInfo(null)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, display: 'flex' }}>
                                <FiX size={20} color="#6b7280" />
                            </button>
                        </div>
                        
                        <div className={styles.modalBody} style={{ padding: '24px', fontSize: '14px', color: '#4b5563', lineHeight: '1.5' }}>
                            {deleteModalInfo.type === 'category' ? (() => {
                                const cat = localCategories.find(c => c.category_id === deleteModalInfo.catId);
                                return (
                                    <p style={{ margin: 0 }}>
                                        This will delete <strong>{cat?.category_name}</strong>. 
                                        {cat && cat.faqs.length > 0 && ` The ${cat.faqs.length} FAQs in this category will be moved to "Uncategorized".`}
                                    </p>
                                );
                            })() : (
                                <p style={{ margin: 0 }}>Are you sure you want to delete this FAQ?</p>
                            )}
                        </div>
                        
                        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', padding: '16px 24px', borderTop: '1px solid #e5e7eb', background: '#fff', borderBottomLeftRadius: '12px', borderBottomRightRadius: '12px' }}>
                            <button 
                                onClick={() => setDeleteModalInfo(null)} 
                                style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #d1d5db', background: 'white', color: '#374151', fontSize: '14px', fontWeight: 500, cursor: 'pointer' }}
                            >
                                Cancel
                            </button>
                            <button 
                                onClick={confirmDelete} 
                                style={{ padding: '8px 16px', borderRadius: '8px', border: 'none', background: '#dc2626', color: 'white', fontSize: '14px', fontWeight: 500, cursor: 'pointer' }}
                            >
                                Delete
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

