import React, { useState, useEffect } from 'react';
import { FiSearch, FiPlus, FiTrash2, FiEdit3, FiChevronLeft, FiArrowLeft, FiSave, FiBold, FiItalic, FiUnderline } from 'react-icons/fi';
import styles from '../../chatbot/components/ChatbotSettings.module.css';
import { useGetInboxSettings, useUpdateInboxSettings } from 'app/utils/api';
import { useToast } from 'app/components/providers/use-toast';

interface SettingsInboxProps {
    onBack?: () => void;
}

export function SettingsInbox({ onBack }: SettingsInboxProps) {
    const { data: response, isLoading } = useGetInboxSettings();
    const updateMutation = useUpdateInboxSettings();
    const { showSuccess, showError } = useToast();

    const [view, setView] = useState<'main' | 'manage'>('main');
    const [formData, setFormData] = useState<any>(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [editingReply, setEditingReply] = useState<any>(null);
    const [showForm, setShowForm] = useState(false);

    const defaultData = {
        message_preference: { enter_key_action: 'send_message', options: ['send_message', 'start_new_line'] },
        quick_replies: { 
            activate_proactive_chat: true, 
            search_query: '', 
            replies_list: [],
            pagination: { items_per_page: 10, current_page: 1, total_pages: 1 }
        },
        create_quick_reply_form: {
            name: 'Qixs-Design',
            font: 'Inter',
            response_rich_text: '',
            formatting_options_enabled: ['bold', 'italic', 'underline']
        }
    };

    useEffect(() => {
        if (response?.data) {
            setFormData({ ...defaultData, ...response.data });
        } else if (!isLoading) {
            setFormData(defaultData);
        }
    }, [response, isLoading]);

    const handleSave = async (updatedData = formData) => {
        try {
            await updateMutation.mutateAsync(updatedData);
            showSuccess("Settings saved successfully");
        } catch (err) {
            showError("Failed to save settings");
        }
    };

    const deleteReply = (id: number) => {
        const newList = formData.quick_replies.replies_list.filter((r: any) => r.id !== id);
        const updated = {
            ...formData,
            quick_replies: { ...formData.quick_replies, replies_list: newList }
        };
        setFormData(updated);
        handleSave(updated);
    };

    const saveQuickReply = () => {
        let newList = [...formData.quick_replies.replies_list];
        if (editingReply.id) {
            newList = newList.map(r => r.id === editingReply.id ? editingReply : r);
        } else {
            newList.push({ ...editingReply, id: Date.now(), updated_at: new Date().toLocaleString() });
        }
        
        const updated = {
            ...formData,
            quick_replies: { ...formData.quick_replies, replies_list: newList }
        };
        setFormData(updated);
        handleSave(updated);
        setShowForm(false);
        setEditingReply(null);
    };

    if (isLoading || !formData) return <div style={{ padding: '24px', textAlign: 'center' }}>Loading inbox settings...</div>;

    if (view === 'manage') {
        return (
            <div className={styles.settingsLayout} style={{ gap: '20px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
                    <button 
                        onClick={() => setView('main')}
                        style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px', color: '#6b7280', fontSize: '14px', fontWeight: 500 }}
                    >
                        <FiArrowLeft /> Back to Inbox
                    </button>
                </div>

                <div className={styles.appearanceCard} style={{ padding: '24px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
                        <div>
                            <h3 style={{ fontSize: '18px', fontWeight: 600 }}>Quick Replies</h3>
                            <p style={{ fontSize: '14px', color: '#6b7280' }}>Create pre-written messages to reply faster</p>
                        </div>
                        <button 
                            className={styles.syncBtn} 
                            style={{ background: '#7c3aed', width: 'auto', padding: '10px 20px' }}
                            onClick={() => {
                                setEditingReply({ shortcut: '', category: 'General', response: '' });
                                setShowForm(true);
                            }}
                        >
                            <FiPlus /> Create quick reply
                        </button>
                    </div>

                    <div style={{ position: 'relative', marginBottom: '20px' }}>
                        <FiSearch style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)', color: '#9ca3af' }} />
                        <input 
                            type="text" 
                            className={styles.chatInput} 
                            placeholder="Search shortcuts..." 
                            style={{ width: '100%', paddingLeft: '36px', height: '44px', background: 'white', border: '1px solid #e5e7eb' }}
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                        />
                    </div>

                    <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                        {formData.quick_replies.replies_list.filter((r: any) => r.shortcut.toLowerCase().includes(searchQuery.toLowerCase())).map((reply: any) => (
                            <div key={reply.id} style={{ border: '1px solid #e5e7eb', borderRadius: '12px', padding: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', background: 'white' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                        <span style={{ fontSize: '15px', fontWeight: 700, color: '#7c3aed' }}>{reply.shortcut}</span>
                                        <span style={{ fontSize: '11px', background: '#f3f4f6', padding: '2px 8px', borderRadius: '4px', color: '#6b7280', fontWeight: 600 }}>{reply.category}</span>
                                    </div>
                                    <p style={{ fontSize: '13px', color: '#4b5563', marginTop: '4px' }}>{reply.response}</p>
                                    <span style={{ fontSize: '11px', color: '#9ca3af', marginTop: '8px' }}>Updated {reply.updated_at}</span>
                                </div>
                                <div style={{ display: 'flex', gap: '12px' }}>
                                    <button 
                                        style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#6b7280' }}
                                        onClick={() => { setEditingReply({ ...reply }); setShowForm(true); }}
                                    >
                                        <FiEdit3 size={18} />
                                    </button>
                                    <button 
                                        style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#ef4444' }}
                                        onClick={() => deleteReply(reply.id)}
                                    >
                                        <FiTrash2 size={18} />
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>

                {/* Create/Edit Form Overlay */}
                {showForm && (
                    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px' }}>
                        <div style={{ background: 'white', width: '100%', maxWidth: '500px', borderRadius: '16px', overflow: 'hidden', boxShadow: '0 25px 50px -12px rgba(0,0,0,0.25)' }}>
                            <div style={{ padding: '20px 24px', borderBottom: '1px solid #f3f4f6', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <h3 style={{ fontSize: '18px', fontWeight: 600 }}>{editingReply?.id ? 'Edit' : 'Create'} Quick Reply</h3>
                                <button onClick={() => setShowForm(false)} style={{ background: 'none', border: 'none', fontSize: '24px', cursor: 'pointer', color: '#9ca3af' }}>×</button>
                            </div>
                            <div style={{ padding: '24px', display: 'flex', flexDirection: 'column', gap: '20px' }}>
                                <div>
                                    <label style={{ fontSize: '13px', fontWeight: 600, color: '#374151', display: 'block', marginBottom: '8px' }}>Shortcut</label>
                                    <input 
                                        type="text" 
                                        className={styles.chatInput} 
                                        style={{ width: '100%', background: 'white', border: '1px solid #d1d5db' }} 
                                        placeholder="/Thanks" 
                                        value={editingReply.shortcut}
                                        onChange={(e) => setEditingReply({ ...editingReply, shortcut: e.target.value })}
                                    />
                                    <p style={{ fontSize: '11px', color: '#6b7280', marginTop: '6px' }}>Type this in the inbox to quickly insert the response.</p>
                                </div>
                                <div>
                                    <label style={{ fontSize: '13px', fontWeight: 600, color: '#374151', display: 'block', marginBottom: '8px' }}>Category</label>
                                    <select 
                                        className={styles.chatInput} 
                                        style={{ width: '100%', background: 'white', border: '1px solid #d1d5db' }}
                                        value={editingReply.category}
                                        onChange={(e) => setEditingReply({ ...editingReply, category: e.target.value })}
                                    >
                                        <option>General</option>
                                        <option>Closing message</option>
                                        <option>Greetings</option>
                                        <option>Troubleshooting</option>
                                    </select>
                                </div>
                                <div>
                                    <label style={{ fontSize: '13px', fontWeight: 600, color: '#374151', display: 'block', marginBottom: '8px' }}>Response</label>
                                    <div style={{ border: '1px solid #d1d5db', borderRadius: '8px', overflow: 'hidden' }}>
                                        <div style={{ background: '#f9fafb', padding: '8px 12px', borderBottom: '1px solid #d1d5db', display: 'flex', gap: '16px' }}>
                                            <FiBold style={{ cursor: 'pointer', color: '#6b7280' }} />
                                            <FiItalic style={{ cursor: 'pointer', color: '#6b7280' }} />
                                            <FiUnderline style={{ cursor: 'pointer', color: '#6b7280' }} />
                                        </div>
                                        <textarea 
                                            className={styles.chatInput} 
                                            style={{ width: '100%', height: '120px', border: 'none', borderRadius: 0, resize: 'none', padding: '12px' }} 
                                            placeholder="Enter the message response..."
                                            value={editingReply.response}
                                            onChange={(e) => setEditingReply({ ...editingReply, response: e.target.value })}
                                        />
                                    </div>
                                </div>
                                <div style={{ display: 'flex', gap: '12px', marginTop: '8px' }}>
                                    <button 
                                        onClick={() => setShowForm(false)}
                                        style={{ flex: 1, padding: '12px', background: 'white', border: '1px solid #d1d5db', borderRadius: '8px', fontWeight: 600, cursor: 'pointer' }}
                                    >
                                        Cancel
                                    </button>
                                    <button 
                                        onClick={saveQuickReply}
                                        style={{ flex: 1, padding: '12px', background: '#7c3aed', color: 'white', border: 'none', borderRadius: '8px', fontWeight: 600, cursor: 'pointer' }}
                                    >
                                        {editingReply?.id ? 'Update' : 'Create'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        );
    }

    return (
        <div className={styles.settingsLayout}>
            {/* Message Preference */}
            <div className={styles.appearanceCard}>
                <div className={styles.settingsGrid}>
                    <div>
                        <h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '8px' }}>Message preference</h3>
                        <p style={{ fontSize: '13px', color: '#6b7280' }}>Configure keyboard shortcuts for message composition</p>
                    </div>
                    <div>
                        <p style={{ fontSize: '14px', fontWeight: 600, marginBottom: '16px' }}>When writing a message in inbox, press ↵ Enter to</p>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div
                                className={styles.triggerOption}
                                style={{ marginBottom: 0, padding: '12px', borderColor: formData.message_preference.enter_key_action === 'send_message' ? '#7c3aed' : '#e5e7eb' }}
                                onClick={() => {
                                    const updated = { ...formData, message_preference: { ...formData.message_preference, enter_key_action: 'send_message' } };
                                    setFormData(updated);
                                    handleSave(updated);
                                }}
                            >
                                <div className={`${styles.radioCircle} ${formData.message_preference.enter_key_action === 'send_message' ? styles.radioCircleActive : ''}`}>
                                    {formData.message_preference.enter_key_action === 'send_message' && <div className={styles.radioInner} />}
                                </div>
                                <span style={{ fontSize: '14px' }}>Send the message</span>
                            </div>
                            <div
                                className={styles.triggerOption}
                                style={{ marginBottom: 0, padding: '12px', borderColor: formData.message_preference.enter_key_action === 'start_new_line' ? '#7c3aed' : '#e5e7eb' }}
                                onClick={() => {
                                    const updated = { ...formData, message_preference: { ...formData.message_preference, enter_key_action: 'start_new_line' } };
                                    setFormData(updated);
                                    handleSave(updated);
                                }}
                            >
                                <div className={`${styles.radioCircle} ${formData.message_preference.enter_key_action === 'start_new_line' ? styles.radioCircleActive : ''}`}>
                                    {formData.message_preference.enter_key_action === 'start_new_line' && <div className={styles.radioInner} />}
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '4px', flexWrap: 'wrap' }}>
                                    <span style={{ fontSize: '14px' }}>Start a new line</span>
                                    <span style={{ fontSize: '13px', color: '#9ca3af' }}>(to send message, use Ctrl + ↵ Enter)</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Quick Replies */}
            <div className={styles.appearanceCard} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '16px' }}>
                <div style={{ flex: 1, minWidth: '200px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600 }}>Quick replies</h3>
                        <label className={styles.switch}>
                            <input 
                                type="checkbox" 
                                checked={formData.quick_replies.activate_proactive_chat}
                                onChange={(e) => {
                                    const updated = { ...formData, quick_replies: { ...formData.quick_replies, activate_proactive_chat: e.target.checked } };
                                    setFormData(updated);
                                    handleSave(updated);
                                }}
                            />
                            <span className={styles.slider}></span>
                        </label>
                    </div>
                    <p style={{ fontSize: '13px', color: '#6b7280' }}>Create pre-written messages to make replying to customers fast and efficient.</p>
                </div>
                <button
                    className={styles.syncBtn}
                    style={{ background: '#7c3aed', width: 'auto', minWidth: '100px' }}
                    onClick={() => setView('manage')}
                >
                    Manage
                </button>
            </div>
        </div>
    );
}
