import React, { useState, useEffect } from 'react';
import { FiChevronDown, FiPlus, FiX, FiArrowLeft, FiMonitor, FiSmartphone, FiStar, FiSmile, FiFrown, FiMeh } from 'react-icons/fi';
import styles from '../../chatbot/components/ChatbotSettings.module.css';
import { useGetAutomationSettings, useUpdateAutomationSettings } from 'app/utils/api';
import { useToast } from 'app/components/providers/use-toast';

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

export function SettingsAutomation({ onBack }: SettingsAutomationProps) {
    const { data: response, isLoading } = useGetAutomationSettings();
    const updateMutation = useUpdateAutomationSettings();
    const { showSuccess, showError } = useToast();

    const [view, setView] = useState<'main' | 'survey'>('main');
    const [formData, setFormData] = useState<any>(null);
    const [desktopPreviewOpen, setDesktopPreviewOpen] = useState(false);
    const [keywordInput, setKeywordInput] = useState('');

    const defaultData = {
        assignment: {
            method: 'manual_assignment',
            method_options: ['manual_assignment', 'automatic_assignment_in_order'],
            reassign_on_reply: 'stay_with_assigned',
            reassign_options: ['stay_with_assigned', 'assign_to_replier']
        },
        automatic_resolution: {
            enabled: true,
            auto_resolve_after: 60,
            unit: 'minutes',
            notice_message: "This chat was closed due to inactivity. Feel free to send a message to reopen it - we're here to help!"
        },
        smart_spam_protection: { enabled: false, requires_upgrade: true },
        satisfaction_survey: {
            enabled: false,
            survey_format: 'star_rating',
            format_options: ['star_rating', 'emoji_scale'],
            survey_content: {
                intro_text: "How was your experience?",
                thank_you_message: "Thank you for your feedback!"
            },
            trigger_time: {
                on_conversation_resolved: true,
                on_specific_keywords: {
                    enabled: false,
                    keywords: ['Thank you', 'Thanks']
                }
            }
        }
    };

    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("Automation settings saved");
        } catch (err) {
            showError("Failed to save settings");
        }
    };

    const updateNested = (path: string[], value: any) => {
        const newData = { ...formData };
        let current = newData;
        for (let i = 0; i < path.length - 1; i++) {
            current[path[i]] = { ...current[path[i]] };
            current = current[path[i]];
        }
        current[path[path.length - 1]] = value;
        setFormData(newData);
        handleSave(newData);
    };

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

    const renderSurveyIcons = (format: string, size = 24, active = false) => {
        if (format === 'star_rating') {
            return (
                <div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
                    {[1, 2, 3, 4, 5].map(i => <FiStar key={i} size={size} color={active ? '#fbbf24' : '#d1d5db'} fill={active ? '#fbbf24' : 'none'} />)}
                </div>
            );
        }
        return (
            <div style={{ display: 'flex', gap: '12px', justifyContent: 'center' }}>
                <FiFrown size={size} color={active ? '#f59e0b' : '#d1d5db'} />
                <FiMeh size={size} color={active ? '#f59e0b' : '#d1d5db'} />
                <FiSmile size={size} color={active ? '#f59e0b' : '#d1d5db'} />
                <FiSmile size={size} color={active ? '#f59e0b' : '#d1d5db'} />
                <FiSmile size={size} color={active ? '#ef4444' : '#d1d5db'} />
            </div>
        );
    };

    const previewComponent = (id: string) => (
        <div id={id} style={{ 
            background: 'white', borderRadius: '12px', padding: '16px', 
            boxShadow: '0 4px 12px rgba(0,0,0,0.05)', border: '1px solid #f3f4f6',
            maxWidth: '100%'
        }}>
            <p style={{ fontSize: '14px', fontWeight: 600, color: '#111827', textAlign: 'center', marginBottom: '16px' }}>
                {formData.satisfaction_survey.survey_content.intro_text}
            </p>
            {renderSurveyIcons(formData.satisfaction_survey.survey_format, 20, false)}
        </div>
    );

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

                    {/* Format */}
                    <div className={styles.appearanceCard}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                            <h3 style={{ fontSize: '15px', fontWeight: 600 }}>Display satisfaction survey</h3>
                            <label className={styles.switch}>
                                <input 
                                    type="checkbox" 
                                    checked={formData.satisfaction_survey.enabled}
                                    onChange={(e) => updateNested(['satisfaction_survey', 'enabled'], e.target.checked)}
                                />
                                <span className={styles.slider}></span>
                            </label>
                        </div>

                        <div style={{ display: 'flex', gap: '16px' }}>
                            {['star_rating', 'emoji_scale'].map(fmt => (
                                <div 
                                    key={fmt}
                                    onClick={() => updateNested(['satisfaction_survey', 'survey_format'], fmt)}
                                    style={{ 
                                        flex: 1, border: '1px solid', borderColor: formData.satisfaction_survey.survey_format === fmt ? '#7c3aed' : '#e5e7eb',
                                        borderRadius: '12px', padding: '24px 16px', textAlign: 'center', cursor: 'pointer', background: 'white'
                                    }}
                                >
                                    {renderSurveyIcons(fmt, 20, true)}
                                    <div style={{ fontSize: '13px', fontWeight: 600, color: '#374151', marginTop: '30px' }}>
                                        {fmt === 'star_rating' ? 'Star rating' : 'Emoji scale'}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Content */}
                    <div className={styles.appearanceCard}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '20px' }}>Survey content</h3>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div>
                                <label style={{ fontSize: '13px', color: '#6b7280', display: 'block', marginBottom: '8px' }}>Intro</label>
                                <input 
                                    className={styles.chatInput} 
                                    value={formData.satisfaction_survey.survey_content.intro_text}
                                    onChange={(e) => updateNested(['satisfaction_survey', 'survey_content', 'intro_text'], e.target.value)}
                                    style={{ width: '100%', background: 'white', border: '1px solid #d1d5db' }}
                                />
                            </div>
                            <div>
                                <label style={{ fontSize: '13px', color: '#6b7280', display: 'block', marginBottom: '8px' }}>Thank you message</label>
                                <input 
                                    className={styles.chatInput} 
                                    value={formData.satisfaction_survey.survey_content.thank_you_message}
                                    onChange={(e) => updateNested(['satisfaction_survey', 'survey_content', 'thank_you_message'], e.target.value)}
                                    style={{ width: '100%', background: 'white', border: '1px solid #d1d5db' }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Trigger */}
                    <div className={styles.appearanceCard}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '20px' }}>Trigger time</h3>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                <input 
                                    type="checkbox" 
                                    checked={formData.satisfaction_survey.trigger_time.on_conversation_resolved}
                                    onChange={(e) => updateNested(['satisfaction_survey', 'trigger_time', 'on_conversation_resolved'], e.target.checked)}
                                />
                                <span style={{ fontSize: '14px', color: '#374151' }}>Conversation is resolved</span>
                            </div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                <input 
                                    type="checkbox" 
                                    checked={formData.satisfaction_survey.trigger_time.on_specific_keywords.enabled}
                                    onChange={(e) => updateNested(['satisfaction_survey', 'trigger_time', 'on_specific_keywords', 'enabled'], e.target.checked)}
                                />
                                <span style={{ fontSize: '14px', color: '#374151' }}>When specific keywords appear in conversation</span>
                            </div>
                            {formData.satisfaction_survey.trigger_time.on_specific_keywords.enabled && (
                                <div style={{ marginLeft: '28px' }}>
                                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', border: '1px solid #d1d5db', borderRadius: '8px', padding: '8px', background: 'white' }}>
                                        {formData.satisfaction_survey.trigger_time.on_specific_keywords.keywords.map((kw: string) => (
                                            <div key={kw} style={{ background: '#f3f4f6', color: '#374151', padding: '4px 8px', borderRadius: '4px', fontSize: '12px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                {kw} <FiX style={{ cursor: 'pointer' }} onClick={() => {
                                                    const newKws = formData.satisfaction_survey.trigger_time.on_specific_keywords.keywords.filter((k: string) => k !== kw);
                                                    updateNested(['satisfaction_survey', 'trigger_time', 'on_specific_keywords', 'keywords'], newKws);
                                                }} />
                                            </div>
                                        ))}
                                        <input 
                                            placeholder="Enter keyword to add" 
                                            value={keywordInput}
                                            onChange={(e) => setKeywordInput(e.target.value)}
                                            onKeyDown={(e) => {
                                                if (e.key === 'Enter' && keywordInput.trim()) {
                                                    const newKws = [...formData.satisfaction_survey.trigger_time.on_specific_keywords.keywords, keywordInput.trim()];
                                                    updateNested(['satisfaction_survey', 'trigger_time', 'on_specific_keywords', 'keywords'], newKws);
                                                    setKeywordInput('');
                                                }
                                            }}
                                            style={{ border: 'none', outline: 'none', fontSize: '13px', flex: 1, minWidth: '100px' }}
                                        />
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* Preview Sidebar */}
                <div style={{ width: '320px', display: 'flex', flexDirection: 'column', gap: '20px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span style={{ fontSize: '13px', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '8px' }}>
                            Preview
                        </span>
                        <button 
                            onClick={() => setDesktopPreviewOpen(true)}
                            style={{ background: 'white', border: '1px solid #e5e7eb', borderRadius: '6px', padding: '4px 12px', fontSize: '12px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px' }}
                        >
                            <FiMonitor size={14} /> Desktop
                        </button>
                    </div>

                    <div style={{ background: '#f3f4f6', borderRadius: '32px', padding: '12px', width: '280px', height: '560px', border: '8px solid #1f2937', position: 'relative', margin: '0 auto' }}>
                        <div style={{ background: 'white', width: '100%', height: '100%', borderRadius: '20px', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
                            <div style={{ background: '#f9fafb', height: '60px', borderBottom: '1px solid #e5e7eb', padding: '26px 16px 10px', display: 'flex', alignItems: 'center', gap: '10px' }}>
                                <div style={{ width: '24px', height: '24px', borderRadius: '50%', background: '#10b981' }} />
                                <div>
                                    <div style={{ fontSize: '11px', fontWeight: 700 }}>pritam-dev</div>
                                    <div style={{ fontSize: '9px', color: '#10b981' }}>● We are online</div>
                                </div>
                            </div>
                            <div style={{ flex: 1, padding: '16px', background: 'white', display: 'flex', flexDirection: 'column', gap: '16px' }}>
                                <div style={{ fontSize: '10px', color: '#9ca3af', textAlign: 'center' }}>Today</div>
                                {previewComponent('mobile-preview')}
                            </div>
                            <div style={{ padding: '12px', borderTop: '1px solid #f3f4f6', display: 'flex', gap: '8px', alignItems: 'center' }}>
                                <div style={{ flex: 1, height: '32px', background: '#f3f4f6', borderRadius: '16px' }} />
                                <div style={{ width: '24px', height: '24px', borderRadius: '50%', background: '#f3f4f6' }} />
                            </div>
                        </div>
                    </div>

                    {/* Desktop Preview Modal */}
                    {desktopPreviewOpen && (
                        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                            <div style={{ background: 'white', width: '900px', height: '700px', borderRadius: '16px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                                <div style={{ padding: '16px 24px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <h2 style={{ fontSize: '16px', fontWeight: 600 }}>Desktop preview</h2>
                                    <FiX style={{ cursor: 'pointer' }} onClick={() => setDesktopPreviewOpen(false)} />
                                </div>
                                <div style={{ flex: 1, background: '#f9fafb', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                    <div style={{ width: '380px', height: '500px', background: 'white', borderRadius: '12px', boxShadow: '0 10px 30px rgba(0,0,0,0.1)', display: 'flex', flexDirection: 'column' }}>
                                        <div style={{ height: '60px', background: '#e5e7eb', padding: '12px 20px', display: 'flex', alignItems: 'center', gap: '12px', borderTopLeftRadius: '12px', borderTopRightRadius: '12px' }}>
                                            <FiArrowLeft /> pritam-dev
                                        </div>
                                        <div style={{ flex: 1, padding: '40px 24px', display: 'flex', flexDirection: 'column', gap: '24px' }}>
                                             {previewComponent('desktop-preview')}
                                        </div>
                                        <div style={{ height: '60px', borderTop: '1px solid #f3f4f6', padding: '12px 20px', display: 'flex', alignItems: 'center' }}>
                                            <div style={{ flex: 1, height: '36px', background: '#f3f4f6', borderRadius: '4px' }} />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        );
    }

    return (
        <div className={styles.settingsLayout}>
            {/* Assignment */}
            <div className={styles.appearanceCard}>
                <div className={styles.settingsGrid}>
                    <div>
                        <h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '8px' }}>Assignment</h3>
                        <p style={{ fontSize: '13px', color: '#6b7280' }}>How to assign conversations to your team</p>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                        <div>
                            <p style={{ fontSize: '13px', fontWeight: 600, color: '#374151', marginBottom: '16px' }}>Assignment method</p>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                                {formData.assignment.method_options.map((m: string) => (
                                    <div key={m} style={{ display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer' }} onClick={() => updateNested(['assignment', 'method'], m)}>
                                        <div className={`${styles.radioCircle} ${formData.assignment.method === m ? styles.radioCircleActive : ''}`}>
                                            {formData.assignment.method === m && <div className={styles.radioInner} />}
                                        </div>
                                        <span style={{ fontSize: '14px', color: '#374151', textTransform: 'capitalize' }}>
                                            {m.split('_').join(' ')}
                                        </span>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div>
                            <p style={{ fontSize: '13px', fontWeight: 600, color: '#374151', marginBottom: '16px' }}>Reassign conversations based on replies</p>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                                {formData.assignment.reassign_options.map((o: string) => (
                                    <div key={o} style={{ display: 'flex', alignItems: 'center', gap: '12px', cursor: 'pointer' }} onClick={() => updateNested(['assignment', 'reassign_on_reply'], o)}>
                                        <div className={`${styles.radioCircle} ${formData.assignment.reassign_on_reply === o ? styles.radioCircleActive : ''}`}>
                                            {formData.assignment.reassign_on_reply === o && <div className={styles.radioInner} />}
                                        </div>
                                        <span style={{ fontSize: '14px', color: '#374151' }}>
                                            {o === 'stay_with_assigned' ? 'Conversations stay with assigned member (or stay unassigned)' : 'Conversations will be assigned to whoever replies'}
                                        </span>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Automatic Resolution */}
            <div className={styles.appearanceCard} style={{ padding: '24px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px', flexWrap: 'wrap', gap: '12px' }}>
                    <h3 style={{ fontSize: '15px', fontWeight: 600 }}>Automatic resolution</h3>
                    <label className={styles.switch}>
                        <input 
                            type="checkbox" 
                            checked={formData.automatic_resolution.enabled}
                            onChange={(e) => updateNested(['automatic_resolution', 'enabled'], e.target.checked)}
                        />
                        <span className={styles.slider}></span>
                    </label>
                </div>
                <p style={{ fontSize: '13px', color: '#6b7280', marginBottom: '24px' }}>Auto resolve conversations since last message was sent by team</p>

                <div className={styles.settingsGrid}>
                    <div>
                        <label style={{ fontSize: '13px', color: '#374151', display: 'block', marginBottom: '8px' }}>Auto resolve after</label>
                        <div style={{ display: 'flex', gap: '12px' }}>
                            <input 
                                type="number"
                                className={styles.chatInput}
                                value={formData.automatic_resolution.auto_resolve_after}
                                onChange={(e) => updateNested(['automatic_resolution', 'auto_resolve_after'], parseInt(e.target.value))}
                                style={{ width: '80px', background: '#f9fafb' }}
                            />
                            <div style={{ position: 'relative', flex: 1 }}>
                                <select 
                                    className={styles.chatInput} 
                                    style={{ width: '100%', background: '#f9fafb', appearance: 'none', paddingRight: '40px' }}
                                    value={formData.automatic_resolution.unit}
                                    onChange={(e) => updateNested(['automatic_resolution', 'unit'], e.target.value)}
                                >
                                    <option value="minutes">Minute</option>
                                    <option value="hours">Hour</option>
                                    <option value="days">Day</option>
                                </select>
                                <FiChevronDown style={{ position: 'absolute', right: '16px', top: '14px', color: '#6b7280', pointerEvents: 'none' }} />
                            </div>
                        </div>
                    </div>
                    <div>
                        <label style={{ fontSize: '13px', color: '#374151', display: 'block', marginBottom: '8px' }}>Notice (this will be shown at the end of the conversation)</label>
                        <textarea
                            className={styles.chatInput}
                            style={{ width: '100%', height: '100px', background: '#f9fafb', resize: 'none', fontSize: '13px', textAlign: 'left', lineHeight: '1.5', padding: '12px' }}
                            value={formData.automatic_resolution.notice_message}
                            onChange={(e) => updateNested(['automatic_resolution', 'notice_message'], e.target.value)}
                        />
                    </div>
                </div>
            </div>

            {/* Satisfaction survey */}
            <div className={styles.appearanceCard} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '16px' }}>
                <div style={{ flex: 1, minWidth: '200px' }}>
                    <h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '4px' }}>Satisfaction survey</h3>
                    <p style={{ fontSize: '13px', color: '#6b7280' }}>Collect feedback from customers in their chat.</p>
                </div>
                <button
                    className={styles.syncBtn}
                    style={{ background: '#7c3aed', width: 'auto', minWidth: '100px' }}
                    onClick={() => setView('survey')}
                >
                    Manage
                </button>
            </div>

            {/* Smart spam protection */}
            <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: '4px' }}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600 }}>Smart spam protection</h3>
                        <span style={{ background: '#dbeafe', color: '#2563eb', padding: '2px 8px', borderRadius: '4px', fontSize: '11px', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '4px' }}>
                            <span style={{ fontSize: '12px' }}>👑</span> Upgrade
                        </span>
                    </div>
                    <p style={{ fontSize: '13px', color: '#6b7280' }}>Automatically classify and block spam, sexual, hateful, or violent messages in your inbox.</p>
                </div>
                <label className={styles.switch} style={{ opacity: 0.5, cursor: 'not-allowed' }}>
                    <input type="checkbox" disabled />
                    <span className={styles.slider} style={{ background: '#e5e7eb' }}></span>
                </label>
            </div>
        </div>
    );
}
