import { useState } from "react";
import { FiLink, FiImage } from "react-icons/fi";
import styles from "../../../chatbot/components/ChatbotSettings.module.css";
import { useUpdateFAQSystem } from "app/utils/api";
import { useToast } from "app/components/providers/use-toast";

interface AddFAQModalProps {
    onClose: () => void;
    faq?: any;
    categories: any[];
}

export function AddFAQModal({ onClose, faq, categories }: AddFAQModalProps) {
    const [question, setQuestion] = useState(faq?.question || "");
    const [answer, setAnswer] = useState(faq?.answer_html || "");
    const [status, setStatus] = useState(faq?.status || "published");
    const [categoryId, setCategoryId] = useState(faq?.category_id || (categories.length > 0 ? categories[0].category_id : ""));
    const [isFeatured, setIsFeatured] = useState(faq?.is_featured || false);
    
    const updateFaqMutation = useUpdateFAQSystem();
    const { showSuccess, showError } = useToast();

    const handleSave = async () => {
        if (!question.trim()) {
            showError("Question is required.");
            return;
        }

        try {
            const newCategories = categories.map(cat => {
                if (cat.category_id === categoryId) {
                    let newFaqs = [...cat.faqs];
                    const faqData: any = {
                        faq_id: faq?.faq_id || `faq_${Date.now()}`,
                        question,
                        answer_html: answer,
                        status: status.toLowerCase(),
                        is_featured: isFeatured,
                        created_at: faq?.created_at || new Date().toISOString()
                    };

                    if (faq?.faq_id) {
                        newFaqs = newFaqs.map((f: any) => f.faq_id === faq.faq_id ? faqData : f);
                    } else {
                        newFaqs.push(faqData);
                    }
                    return { ...cat, faqs: newFaqs, faq_count: newFaqs.length };
                }
                // If FAQ was moved from another category, remove it from old one
                if (faq?.category_id && faq.category_id !== categoryId && cat.category_id === faq.category_id) {
                    const filteredFaqs = cat.faqs.filter((f: any) => f.faq_id !== faq.faq_id);
                    return { ...cat, faqs: filteredFaqs, faq_count: filteredFaqs.length };
                }
                return cat;
            });

            await updateFaqMutation.mutateAsync({ categories: newCategories });
            showSuccess(faq?.faq_id ? "FAQ updated!" : "FAQ added!");
            onClose();
        } catch (err) {
            showError("Failed to save FAQ.");
        }
    };

    return (
        <div className={styles.modalOverlay} onClick={onClose}>
            <div className={styles.modalContent} style={{ width: '600px', borderRadius: '16px' }} onClick={e => e.stopPropagation()}>
                <div className={styles.modalHeader}>
                    <h2 className={styles.modalTitle} style={{ margin: 0 }}>{faq?.faq_id ? "Edit FAQ" : "Add FAQ"}</h2>
                    <button className={styles.closeButton} onClick={onClose}>&times;</button>
                </div>

                <div className={styles.modalBody} style={{ display: 'flex', flexDirection: 'column', gap: '20px', padding: '24px' }}>
                    <div>
                        <label className={styles.settingsInputLabel}>Question</label>
                        <input 
                            type="text" 
                            className={styles.chatInput} 
                            style={{ textAlign: 'left', width: '100%', maxWidth: '100%', marginTop: '8px' }} 
                            value={question}
                            onChange={e => setQuestion(e.target.value)}
                            placeholder="e.g. How do I track my order?"
                        />
                    </div>

                    <div>
                        <label className={styles.settingsInputLabel}>Answer</label>
                        <div style={{ marginTop: '8px' }}>
                            <div className={styles.richTextToolbar} style={{ border: '1px solid #e5e7eb', borderBottom: 'none', borderTopLeftRadius: '12px', borderTopRightRadius: '12px', background: '#f9fafb', padding: '8px 12px', display: 'flex', gap: '16px' }}>
                                {["B", "I", "U"].map(tag => (
                                    <div key={tag} className={styles.toolbarBtn} style={{ cursor: 'pointer', fontWeight: tag === 'B' ? 800 : 400, fontStyle: tag === 'I' ? 'italic' : 'normal', textDecoration: tag === 'U' ? 'underline' : 'none' }}>{tag}</div>
                                ))}
                                <div style={{ width: '1px', background: '#e5e7eb', height: '16px' }}></div>
                                <FiLink style={{ cursor: 'pointer', color: '#6b7280' }} />
                                <FiImage style={{ cursor: 'pointer', color: '#6b7280' }} />
                            </div>
                            <textarea 
                                className={styles.instructionTextArea} 
                                style={{ borderTopLeftRadius: 0, borderTopRightRadius: 0, width: '100%', minHeight: '120px', resize: 'vertical' }} 
                                value={answer}
                                onChange={e => setAnswer(e.target.value)}
                            />
                        </div>
                    </div>

                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                        <div>
                            <label className={styles.settingsInputLabel}>Status</label>
                            <select 
                                className={styles.chatInput} 
                                style={{ textAlign: 'left', width: '100%', maxWidth: '100%', marginTop: '8px' }}
                                value={status}
                                onChange={e => setStatus(e.target.value)}
                            >
                                <option value="published">Published</option>
                                <option value="draft">Draft</option>
                            </select>
                        </div>
                        <div>
                            <label className={styles.settingsInputLabel}>Category</label>
                            <select 
                                className={styles.chatInput} 
                                style={{ textAlign: 'left', width: '100%', maxWidth: '100%', marginTop: '8px' }}
                                value={categoryId}
                                onChange={e => setCategoryId(e.target.value)}
                            >
                                {categories.map(cat => (
                                    <option key={cat.category_id} value={cat.category_id}>{cat.category_name}</option>
                                ))}
                            </select>
                        </div>
                    </div>

                    <div className={styles.featuredToggleBox} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: '#f9fafb', padding: '16px', borderRadius: '12px' }}>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                            <span style={{ fontSize: '14px', fontWeight: 600 }}>Featured question</span>
                            <span style={{ fontSize: '12px', color: '#6b7280', maxWidth: '350px' }}>
                                Enable to show this question on the first page of chatbox.
                            </span>
                        </div>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={isFeatured}
                                onChange={e => setIsFeatured(e.target.checked)}
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>

                    <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', marginTop: '12px' }}>
                        <button className={styles.settingsBtn} style={{ background: 'white', color: '#111111', border: '1px solid #e5e7eb' }} onClick={onClose}>Cancel</button>
                        <button 
                            className={styles.syncBtn} 
                            style={{ background: '#7c3aed' }} 
                            onClick={handleSave}
                            disabled={updateFaqMutation.isPending}
                        >
                            {updateFaqMutation.isPending ? "Saving..." : (faq?.faq_id ? "Save changes" : "Add FAQ")}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}

