import styles from "../../ChatbotSettings.module.css";
import { FiMenu, FiX, FiTrash2, FiUsers, FiLink, FiChevronRight, FiEdit2, FiPlus, FiArrowUp, FiArrowDown } from "react-icons/fi";
import { useState } from "react";

interface ChatPageTabProps {
    handover: string;
    setHandover: (val: string) => void;
    conversationStarter: boolean;
    setConversationStarter: (val: boolean) => void;
    questions: any[];
    setQuestions: (val: any[]) => void;
    setShowQuestionModal: (val: boolean) => void;
    setSelectedQuestion: (val: any) => void;
    chatAvatar: string;
    setChatAvatar: (val: string) => void;
    preChatForm: string;
    setPreChatForm: (val: string) => void;
    preChatDescription: string;
    setPreChatDescription: (val: string) => void;
    messagesAfter: number;
    setMessagesAfter: (val: number) => void;
    marketingOptIn: boolean;
    setMarketingOptIn: (val: boolean) => void;
    disclaimerConsent: boolean;
    setDisclaimerConsent: (val: boolean) => void;
    disclaimerText: string;
    setDisclaimerText: (val: string) => void;
    aiName: string;
    setAiName: (val: string) => void;
    welcomeMessage: string;
    setWelcomeMessage: (val: string) => void;
    contactFields: any[];
    setContactFields: (val: any[]) => void;
}

export default function ChatPageTab({
    handover, setHandover,
    conversationStarter, setConversationStarter,
    questions, setQuestions,
    setShowQuestionModal,
    setSelectedQuestion,
    chatAvatar, setChatAvatar,
    preChatForm, setPreChatForm,
    preChatDescription, setPreChatDescription,
    messagesAfter, setMessagesAfter,
    marketingOptIn, setMarketingOptIn,
    disclaimerConsent, setDisclaimerConsent,
    disclaimerText, setDisclaimerText,
    aiName, setAiName,
    welcomeMessage, setWelcomeMessage,
    contactFields, setContactFields
}: ChatPageTabProps) {

    const [draggedIndex, setDraggedIndex] = useState<number | null>(null);
    const [showFieldDropdown, setShowFieldDropdown] = useState(false);

    const handleDeleteQuestion = (id: number) => {
        setQuestions(questions.filter(q => q.id !== id));
    };

    const handleEditQuestion = (q: any) => {
        setSelectedQuestion(q);
        setShowQuestionModal(true);
    };

    const onDragStart = (idx: number) => {
        setDraggedIndex(idx);
    };

    const onDragOver = (e: React.DragEvent, idx: number) => {
        e.preventDefault();
        if (draggedIndex === null || draggedIndex === idx) return;

        const newQuestions = [...questions];
        const draggedItem = newQuestions[draggedIndex];
        newQuestions.splice(draggedIndex, 1);
        newQuestions.splice(idx, 0, draggedItem);
        
        setDraggedIndex(idx);
        setQuestions(newQuestions);
    };

    const onDragEnd = () => {
        setDraggedIndex(null);
    };

    const insertName = () => {
        setWelcomeMessage(welcomeMessage + " {{customer_name}}");
    };

    const addContactField = (label: string) => {
        if (contactFields.some(f => f.label === label)) {
            setShowFieldDropdown(false);
            return;
        }
        setContactFields([...contactFields, { label, required: true }]);
        setShowFieldDropdown(false);
    };

    const removeContactField = (label: string) => {
        setContactFields(contactFields.filter(f => f.label !== label));
    };

    const toggleRequired = (label: string) => {
        setContactFields(contactFields.map(f => f.label === label ? { ...f, required: !f.required } : f));
    };

    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
            {/* Welcome message section */}
            <div className={styles.card}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                    <h2 className={styles.sectionTitle} style={{ margin: 0 }}>Welcome message</h2>
                </div>
                <p className={styles.subtitle} style={{ marginBottom: "16px" }}>
                    Send the welcome message when visitors initiate the chat
                </p>
                <div className={styles.inputGroup}>
                    <div className={styles.labelRow}>
                        <label className={styles.inputLabel}>Message</label>
                        <span className={styles.blueLink} style={{ cursor: 'pointer' }} onClick={insertName}>Insert customer name</span>
                    </div>
                    <div className={styles.richEditor} style={{ minHeight: '100px', display: 'flex', flexDirection: 'column' }}>
                        <textarea
                            className={styles.editorContent}
                            style={{ 
                                flex: 1,
                                width: '100%', 
                                border: 'none', 
                                resize: 'none', 
                                outline: 'none', 
                                background: 'transparent',
                                minHeight: '80px',
                                padding: '12px'
                            }}
                            value={welcomeMessage}
                            onChange={(e) => setWelcomeMessage(e.target.value)}
                        />
                        <div style={{ padding: '8px 12px', display: 'flex', justifyContent: 'flex-end' }}>
                            <span style={{ cursor: 'pointer', fontSize: '18px' }}>😊</span>
                        </div>
                    </div>
                </div>
                <label className={styles.checkboxOption} style={{ marginTop: '16px' }}>
                    <input type="checkbox" />
                    <span>Use different offline message</span>
                </label>
            </div>

            {/* Conversation starter section */}
            <div className={styles.card}>
                <div className={styles.toggleRow} style={{ marginBottom: '8px' }}>
                    <h2 className={styles.sectionTitle} style={{ margin: 0 }}>Conversation starter</h2>
                    <label className={styles.switch}>
                        <input
                            type="checkbox"
                            checked={conversationStarter}
                            onChange={(e) => setConversationStarter(e.target.checked)}
                        />
                        <span className={styles.slider}></span>
                    </label>
                </div>
                <p className={styles.subtitle} style={{ marginBottom: "20px" }}>
                    Provide instant answers to customer's questions based on your FAQs
                </p>

                {conversationStarter && (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                        {questions.map((q, idx) => (
                            <div 
                                key={q.id} 
                                className={styles.questionItem} 
                                style={{ 
                                    border: '1px solid #f1f5f9', 
                                    borderRadius: '12px', 
                                    padding: '12px 16px',
                                    opacity: draggedIndex === idx ? 0.5 : 1,
                                    cursor: 'grab'
                                }}
                                draggable
                                onDragStart={() => onDragStart(idx)}
                                onDragOver={(e) => onDragOver(e, idx)}
                                onDragEnd={onDragEnd}
                            >
                                <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                                    <FiMenu color="#9ca3af" />
                                    <div className={styles.questionContent} style={{ flex: 1, marginLeft: '12px' }}>
                                        <span className={styles.questionText} style={{ display: 'block', fontWeight: 600, fontSize: '14px', marginBottom: '2px' }}>{q.icon} {q.text}</span>
                                        <span className={styles.answerText} style={{ display: 'block', fontSize: '12px', color: '#6b7280', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{q.desc}</span>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                                    <FiTrash2 
                                        className={styles.actionIcon} 
                                        style={{ cursor: 'pointer', color: '#9ca3af' }} 
                                        onClick={() => handleDeleteQuestion(q.id)}
                                    />
                                    <FiEdit2 
                                        className={styles.actionIcon} 
                                        style={{ cursor: 'pointer', color: '#9ca3af' }} 
                                        onClick={() => handleEditQuestion(q)}
                                    />
                                </div>
                            </div>
                        ))}
                        <div
                            className={styles.addQuestionLink}
                            style={{ display: 'flex', alignItems: 'center', gap: '6px', color: '#7c3aed', fontWeight: 600, cursor: 'pointer', marginTop: '4px' }}
                            onClick={() => {
                                setSelectedQuestion(null);
                                setShowQuestionModal(true);
                            }}
                        >
                            <FiPlus /> Add question
                        </div>
                    </div>
                )}
            </div>

            {/* Chat avatar section */}
            <div className={styles.card}>
                <h2 className={styles.sectionTitle} style={{ marginBottom: '20px' }}>Chat avatar</h2>
                <div className={styles.radioGrid}>
                    <div
                        className={`${styles.radioCard} ${chatAvatar === "Store branding" ? styles.radioCardActive : ""}`}
                        onClick={() => setChatAvatar("Store branding")}
                    >
                        <div className={`${styles.radioDot} ${chatAvatar === "Store branding" ? styles.radioDotActive : ""}`}>
                            {chatAvatar === "Store branding" && <div className={styles.radioDotInner}></div>}
                        </div>
                        <div className={styles.choiceRow}>
                            <span className={styles.choiceTitle}>Store branding</span>
                            <span className={styles.choiceDesc}>
                                Show store logo and name in customer chats. <span className={styles.blueLink}>Edit store logo.</span>
                            </span>
                        </div>
                    </div>
                    <div
                        className={`${styles.radioCard} ${chatAvatar === "Team member profile" ? styles.radioCardActive : ""}`}
                        onClick={() => setChatAvatar("Team member profile")}
                    >
                        <div className={`${styles.radioDot} ${chatAvatar === "Team member profile" ? styles.radioDotActive : ""}`}>
                            {chatAvatar === "Team member profile" && <div className={styles.radioDotInner}></div>}
                        </div>
                        <div className={styles.choiceRow}>
                            <span className={styles.choiceTitle}>Team member profile</span>
                            <span className={styles.choiceDesc}>
                                Show individual team member names and avatars in customer chats. <span className={styles.blueLink}>Go to team member.</span>
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            {/* Pre-chat form section */}
            <div className={styles.card}>
                <h2 className={styles.sectionTitle}>Pre-chat form</h2>
                <p className={styles.subtitle} style={{ marginBottom: "20px" }}>Collect leads from customers</p>
                
                <div style={{ marginBottom: '24px' }}>
                    <p className={styles.inputLabel} style={{ marginBottom: '12px' }}>How customers start a chat</p>
                    <div className={styles.radioGrid} style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                        {[
                            { id: "Chat as guest", label: "Chat as guest", desc: "Require information before chat" },
                            { id: "Chat as anonymous", label: "Chat as anonymous", desc: "No information required" },
                            { id: "Show both options", label: "Show both options", desc: "Let customers choose to provide information or not" }
                        ].map((opt) => (
                            <div
                                key={opt.id}
                                className={`${styles.radioCard} ${preChatForm === opt.id ? styles.radioCardActive : ""}`}
                                onClick={() => setPreChatForm(opt.id)}
                                style={{ padding: '12px 16px' }}
                            >
                                <div className={`${styles.radioDot} ${preChatForm === opt.id ? styles.radioDotActive : ""}`}>
                                    {preChatForm === opt.id && <div className={styles.radioDotInner}></div>}
                                </div>
                                <div className={styles.choiceRow}>
                                    <span className={styles.choiceTitle}>{opt.label}</span>
                                    <span className={styles.choiceDesc}>{opt.desc}</span>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {preChatForm !== "Chat as anonymous" && (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                        {preChatForm === "Show both options" && (
                            <div className={styles.inputGroup}>
                                <label className={styles.inputLabel}>Show form after X messages from visitors</label>
                                <input 
                                    type="number" 
                                    className={styles.inputField} 
                                    value={messagesAfter}
                                    onChange={(e) => setMessagesAfter(parseInt(e.target.value))}
                                />
                            </div>
                        )}

                        <div className={styles.inputGroup}>
                            <label className={styles.inputLabel}>Description</label>
                            <input 
                                type="text"
                                className={styles.inputField}
                                value={preChatDescription}
                                onChange={(e) => setPreChatDescription(e.target.value)}
                            />
                            <p style={{ marginTop: '6px', fontSize: '11px', color: '#9ca3af' }}>Description helps to convey the purpose of collecting user information</p>
                        </div>

                        <div className={styles.inputGroup}>
                            <div className={styles.labelRow} style={{ position: 'relative' }}>
                                <label className={styles.inputLabel}>Information to be collected</label>
                                <div 
                                    className={styles.blueLink} 
                                    style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '13px', cursor: 'pointer' }}
                                    onClick={() => setShowFieldDropdown(!showFieldDropdown)}
                                >
                                    Add contact field <FiChevronRight style={{ transform: showFieldDropdown ? 'rotate(270deg)' : 'rotate(90deg)', transition: '0.2s' }} />
                                </div>
                                {showFieldDropdown && (
                                    <div style={{ 
                                        position: 'absolute', 
                                        right: 0, 
                                        top: '24px', 
                                        background: 'white', 
                                        boxShadow: '0 4px 12px rgba(0,0,0,0.1)', 
                                        borderRadius: '8px', 
                                        padding: '4px', 
                                        zIndex: 10,
                                        width: '150px',
                                        border: '1px solid #f1f5f9'
                                    }}>
                                        {["Name", "Phone number"].filter(f => !contactFields.some(cf => cf.label === f)).map(f => (
                                            <div 
                                                key={f}
                                                style={{ padding: '8px 12px', fontSize: '13px', cursor: 'pointer', borderRadius: '4px' }}
                                                className={styles.dropdownItem}
                                                onClick={() => addContactField(f)}
                                            >
                                                {f}
                                            </div>
                                        ))}
                                        {["Name", "Phone number"].filter(f => !contactFields.some(cf => cf.label === f)).length === 0 && (
                                            <div style={{ padding: '8px 12px', fontSize: '12px', color: '#94a3b8', textAlign: 'center' }}>No more fields</div>
                                        )}
                                    </div>
                                )}
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '8px' }}>
                                {contactFields.map((field) => (
                                    <div key={field.label} style={{ background: '#f8fafc', borderRadius: '12px', padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', border: '1px solid #f1f5f9' }}>
                                        <span style={{ fontSize: '14px', fontWeight: 500 }}>{field.label}</span>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                            <div style={{ position: 'relative' }}>
                                                <div 
                                                    style={{ 
                                                        background: field.required ? '#ecfdf5' : '#f1f5f9', 
                                                        color: field.required ? '#10b981' : '#64748b', 
                                                        fontSize: '11px', 
                                                        padding: '4px 12px', 
                                                        borderRadius: '12px', 
                                                        fontWeight: 600, 
                                                        display: 'flex', 
                                                        alignItems: 'center', 
                                                        gap: '4px', 
                                                        cursor: 'pointer' 
                                                    }}
                                                    onClick={() => {
                                                        const active = (window as any).activeFieldDropdown === field.label;
                                                        (window as any).activeFieldDropdown = active ? null : field.label;
                                                        setContactFields([...contactFields]); // trigger re-render
                                                    }}
                                                >
                                                    {field.required ? 'Required' : 'Optional'} <FiChevronRight style={{ transform: 'rotate(90deg)' }} />
                                                </div>
                                                {(window as any).activeFieldDropdown === field.label && (
                                                    <div style={{ 
                                                        position: 'absolute', 
                                                        right: 0, 
                                                        top: '28px', 
                                                        background: 'white', 
                                                        boxShadow: '0 4px 12px rgba(0,0,0,0.1)', 
                                                        borderRadius: '8px', 
                                                        padding: '4px', 
                                                        zIndex: 20,
                                                        width: '100px',
                                                        border: '1px solid #f1f5f9'
                                                    }}>
                                                        {[true, false].map(req => (
                                                            <div 
                                                                key={req ? 'req' : 'opt'}
                                                                style={{ padding: '6px 12px', fontSize: '12px', cursor: 'pointer', borderRadius: '4px', background: field.required === req ? '#f8fafc' : 'transparent' }}
                                                                onClick={() => {
                                                                    setContactFields(contactFields.map(f => f.label === field.label ? { ...f, required: req } : f));
                                                                    (window as any).activeFieldDropdown = null;
                                                                }}
                                                            >
                                                                {req ? 'Required' : 'Optional'}
                                                            </div>
                                                        ))}
                                                    </div>
                                                )}
                                            </div>
                                            {field.label !== "Email address" && (
                                                <FiTrash2 
                                                    color="#f43f5e" 
                                                    style={{ cursor: 'pointer' }} 
                                                    onClick={() => removeContactField(field.label)}
                                                />
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div className={styles.toggleRow}>
                            <div className={styles.choiceRow}>
                                <span className={styles.choiceTitle}>Show marketing opt-in to customers</span>
                                <span className={styles.choiceDesc}>Visitor subscribe will be convert to customers</span>
                            </div>
                            <label className={styles.switch}>
                                <input 
                                    type="checkbox" 
                                    checked={marketingOptIn}
                                    onChange={(e) => setMarketingOptIn(e.target.checked)}
                                />
                                <span className={styles.slider}></span>
                            </label>
                        </div>

                        <div className={styles.toggleRow}>
                            <div className={styles.choiceRow}>
                                <span className={styles.choiceTitle}>Disclaimer consent</span>
                                <span className={styles.choiceDesc}>Inform customers how their data is used before they start a conversation or subscribe</span>
                            </div>
                            <label className={styles.switch}>
                                <input 
                                    type="checkbox" 
                                    checked={disclaimerConsent}
                                    onChange={(e) => setDisclaimerConsent(e.target.checked)}
                                />
                                <span className={styles.slider}></span>
                            </label>
                        </div>

                        <div className={styles.richEditor} style={{ borderRadius: '12px', background: 'white' }}>
                            <div className={styles.editorToolbar} style={{ borderBottom: '1px solid #f1f5f9', padding: '8px 12px', display: 'flex', gap: '16px' }}>
                                <span style={{ fontWeight: 800, cursor: 'pointer' }}>B</span>
                                <span style={{ fontStyle: 'italic', cursor: 'pointer' }}>I</span>
                                <FiLink style={{ cursor: 'pointer' }} />
                                <span style={{ textDecoration: 'underline', cursor: 'pointer' }}>U</span>
                            </div>
                            <textarea
                                className={styles.editorContent}
                                style={{ width: '100%', minHeight: '80px', padding: '12px', border: 'none', resize: 'none', background: 'transparent', outline: 'none' }}
                                value={disclaimerText}
                                onChange={(e) => setDisclaimerText(e.target.value)}
                            />
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
