import { useState } from "react";
import styles from "../../ChatbotSettings.module.css";
import { FiX, FiMail, FiMenu, FiTrash2, FiChevronRight } from "react-icons/fi";
import { 
    FaFacebookMessenger, 
    FaTelegram, 
    FaSkype, 
    FaLine, 
    FaTiktok, 
    FaWhatsapp,
    FaInstagram,
    FaPhone,
} from "react-icons/fa";
import { FiMessageSquare } from "react-icons/fi";

const CONTACT_OPTIONS = [
    { name: "Messenger", icon: FaFacebookMessenger, color: '#0084FF' },
    { name: "Phone call", icon: FaPhone, color: '#10b981' },
    { name: "Instagram", icon: FaInstagram, color: '#E1306C' },
    { name: "Telegram", icon: FaTelegram, color: '#0088cc' },
    { name: "Skype", icon: FaSkype, color: '#00AFF0' },
    { name: "Line", icon: FaLine, color: '#00C300' },
    { name: "WhatsApp", icon: FaWhatsapp, color: '#25D366' },
    { name: "SMS", icon: FiMessageSquare, color: '#3b82f6' },
    { name: "TikTok", icon: FaTiktok, color: '#000000' },
    { name: "Email", icon: FiMail, color: '#fbbf24' },
];

interface ContactModalProps {
    onClose: () => void;
    chatStatus: boolean;
    setChatStatus: (val: boolean) => void;
    onlineStatus: string;
    setOnlineStatus: (val: string) => void;
    offlineStatus: string;
    setOfflineStatus: (val: string) => void;
    showOnlineOutside: boolean;
    setShowOnlineOutside: (val: boolean) => void;
    showContactMethods: boolean;
    setShowContactMethods: (val: boolean) => void;
    contactMethods: any[];
    setContactMethods: (val: any[]) => void;
}

const getContactIcon = (type: string) => {
    const option = CONTACT_OPTIONS.find(o => o.name.toLowerCase() === type.toLowerCase());
    return option ? option.icon : FiMail;
};

const getIconColor = (type: string) => {
    const option = CONTACT_OPTIONS.find(o => o.name.toLowerCase() === type.toLowerCase());
    return option ? option.color : '#fbbf24';
};

export default function ContactModal({ 
    onClose,
    chatStatus,
    setChatStatus,
    onlineStatus,
    setOnlineStatus,
    offlineStatus,
    setOfflineStatus,
    showOnlineOutside,
    setShowOnlineOutside,
    showContactMethods,
    setShowContactMethods,
    contactMethods,
    setContactMethods
}: ContactModalProps) {
    const [showDropdown, setShowDropdown] = useState(false);
    const [draggedItemIndex, setDraggedItemIndex] = useState<number | null>(null);

    const addContactMethod = (type: string) => {
        const id = Date.now().toString();
        setContactMethods([...contactMethods, { id, type, value: '', icon: type.toLowerCase() }]);
        setShowDropdown(false);
    };

    const deleteMethod = (id: string) => {
        setContactMethods(contactMethods.filter(m => m.id !== id));
    };

    const updateMethodValue = (id: string, value: string) => {
        setContactMethods(contactMethods.map(m => m.id === id ? { ...m, value } : m));
    };

    const handleDragStart = (index: number) => {
        setDraggedItemIndex(index);
    };

    const handleDragOver = (e: React.DragEvent, index: number) => {
        e.preventDefault();
    };

    const handleDrop = (index: number) => {
        if (draggedItemIndex === null) return;
        const newMethods = [...contactMethods];
        const draggedItem = newMethods[draggedItemIndex];
        newMethods.splice(draggedItemIndex, 1);
        newMethods.splice(index, 0, draggedItem);
        setContactMethods(newMethods);
        setDraggedItemIndex(null);
    };

    return (
        <div className={styles.modalOverlay}>
            <div className={styles.modalContent}>
                <div className={styles.modalHeader}>
                    <h2 className={styles.modalTitle}>Contact configuration</h2>
                    <button onClick={onClose} className={styles.closeButton}>
                        <FiX />
                    </button>
                </div>

                <div className={styles.modalBody}>
                    <div className={styles.modalRow}>
                        <div className={styles.modalRowInfo}>
                            <div className={styles.modalRowTitle}>Chat status</div>
                            <div className={styles.modalRowDesc}>
                                Set up online/offline status in <span className={styles.purpleLink}>working hours settings.</span>
                            </div>
                        </div>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={chatStatus} 
                                onChange={(e) => setChatStatus(e.target.checked)} 
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>

                    <div className={styles.inputGroupConfiguration}>
                        <label className={styles.inputLabel}>Online status</label>
                        <input 
                            type="text" 
                            className={styles.inputField} 
                            value={onlineStatus} 
                            onChange={(e) => setOnlineStatus(e.target.value)}
                        />
                    </div>

                    <div className={styles.inputGroupConfiguration}>
                        <label className={styles.inputLabel}>Offline status</label>
                        <input 
                            type="text" 
                            className={styles.inputField} 
                            value={offlineStatus} 
                            onChange={(e) => setOfflineStatus(e.target.value)}
                        />
                    </div>

                    <div className={styles.modalRow}>
                        <div className={styles.modalRowInfo}>
                            <div className={styles.modalRowTitle}>Show online status outside working hours</div>
                            <div className={styles.modalRowDesc}>
                                Shows online if any agent is available, even outside working hours.
                            </div>
                        </div>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={showOnlineOutside} 
                                onChange={(e) => setShowOnlineOutside(e.target.checked)}
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>

                    <hr className={styles.modalDivider} />

                    <div className={styles.modalRow}>
                        <div className={styles.modalRowTitle}>Contact methods</div>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={showContactMethods} 
                                onChange={(e) => setShowContactMethods(e.target.checked)}
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>

                    <div style={{ display: 'flex', flexDirection: 'column', gap: '20px', marginTop: '16px' }}>
                        {contactMethods.map((method, index) => {
                            const Icon = getContactIcon(method.type);
                            const isPhoneOrWhatsapp = method.type.toLowerCase().includes('phone') || method.type.toLowerCase().includes('whatsapp');
                            
                            return (
                                <div 
                                    key={method.id} 
                                    className={styles.contactMethodCard}
                                    draggable
                                    onDragStart={() => handleDragStart(index)}
                                    onDragOver={(e) => handleDragOver(e, index)}
                                    onDrop={() => handleDrop(index)}
                                    style={{ opacity: draggedItemIndex === index ? 0.5 : 1 }}
                                >
                                    <div className={styles.methodLabel}>{method.type}</div>
                                    <div className={styles.methodInputWrapper}>
                                        <div className={styles.dragHandleSide}>
                                            <FiMenu />
                                        </div>
                                        <div className={styles.methodIconBox} style={{ background: getIconColor(method.type) }}>
                                            <Icon />
                                        </div>
                                        <div className={styles.methodInputContainer}>
                                            {isPhoneOrWhatsapp && (
                                                <div className={styles.countryFlag}>
                                                    🇺🇸 <FiChevronRight style={{ transform: 'rotate(90deg)', fontSize: '10px' }} />
                                                </div>
                                            )}
                                            <input 
                                                type="text" 
                                                className={styles.methodValueInputV2} 
                                                value={method.value} 
                                                onChange={(e) => updateMethodValue(method.id, e.target.value)}
                                                placeholder={isPhoneOrWhatsapp ? '+15475475757' : `Enter ${method.type} link/number`}
                                                onClick={(e) => e.stopPropagation()}
                                            />
                                        </div>
                                        <div className={styles.methodDeleteBtn} onClick={() => deleteMethod(method.id)}>
                                            <FiTrash2 />
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>

                    <div style={{ position: 'relative' }}>
                        <div 
                            className={styles.addMethodButton} 
                            onClick={() => setShowDropdown(!showDropdown)}
                            style={{ cursor: 'pointer' }}
                        >
                            Add contact method <FiChevronRight style={{ transform: showDropdown ? 'rotate(270deg)' : 'rotate(90deg)' }} />
                        </div>

                        {showDropdown && (
                            <div className={styles.contactDropdown}>
                                {CONTACT_OPTIONS.map((option) => {
                                    const Icon = option.icon;
                                    return (
                                        <div 
                                            key={option.name} 
                                            className={styles.dropdownItem}
                                            onClick={() => addContactMethod(option.name)}
                                        >
                                            <Icon style={{ color: option.color }} />
                                            <span>{option.name}</span>
                                        </div>
                                    );
                                })}
                            </div>
                        )}
                    </div>

                    <hr className={styles.modalDivider} />

                    <div className={styles.modalRow}>
                        <div className={styles.modalRowInfo}>
                            <div className={styles.modalRowTitle}>Contact button</div>
                            <div className={styles.modalRowDesc}>
                                Add contact button anywhere on your site to boost engagement. <span className={styles.purpleLink}>Read guide</span> for more details or <span className={styles.purpleLink}>go to theme</span> to set it up.
                            </div>
                        </div>
                        <label className={styles.switch}>
                            <input type="checkbox" defaultChecked />
                            <span className={styles.slider}></span>
                        </label>
                    </div>
                </div>
            </div>
        </div>
    );
}
