import React, { useState, useEffect, useRef } from "react";
import { FiArrowLeft, FiMonitor, FiTrash2, FiPlus, FiClock, FiSave, FiCalendar, FiChevronLeft, FiChevronRight, FiCheck } from 'react-icons/fi';
import styles from '../../chatbot/components/ChatbotSettings.module.css';
import { useGetChatAvailability, useUpdateChatAvailability } from "app/utils/api";
import { useToast } from "app/components/providers/use-toast";

const timeOptions: string[] = [];
for (let h = 0; h < 24; h++) {
    for (let m = 0; m < 60; m += 30) {
        let displayH = h % 12;
        if (displayH === 0) displayH = 12;
        const ampm = h < 12 ? 'AM' : 'PM';
        timeOptions.push(`${displayH}:${m === 0 ? '00' : '30'} ${ampm}`);
    }
}

function timeToMinutes(time: string) {
    if (!time) return 0;
    const [hPart, mPart] = time.split(':');
    let h = parseInt(hPart);
    const m = parseInt(mPart.split(' ')[0]);
    const ampm = mPart.split(' ')[1];
    
    if (ampm === 'PM' && h !== 12) h += 12;
    if (ampm === 'AM' && h === 12) h = 0;
    return h * 60 + m;
}

function TimePicker({ value, onChange, minTime, maxTime }: { value: string, onChange: (val: string) => void, minTime?: string, maxTime?: string }) {
    const [isOpen, setIsOpen] = useState(false);
    const containerRef = useRef<HTMLDivElement>(null);

    const minMinutes = minTime ? timeToMinutes(minTime) : -1;
    const maxMinutes = maxTime ? timeToMinutes(maxTime) : 1441;

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    return (
        <div style={{ position: 'relative' }} ref={containerRef}>
            <div 
                className={styles.chatInput} 
                style={{ 
                    width: '100px', height: '36px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px', 
                    background: 'white', border: '1px solid #d1d5db', padding: '0 8px', fontSize: '12px' 
                }}
                onClick={() => setIsOpen(!isOpen)}
            >
                <FiClock size={14} color="#6b7280" />
                <span>{value}</span>
            </div>
            {isOpen && (
                <div style={{ 
                    position: 'absolute', top: 'calc(100% + 4px)', left: 0, width: '120px', maxHeight: '200px', 
                    overflowY: 'auto', background: 'white', border: '1px solid #e5e7eb', borderRadius: '8px', 
                    boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1)', zIndex: 60 
                }}>
                    {timeOptions.map(time => {
                        const minutes = timeToMinutes(time);
                        const isDisabled = minutes <= minMinutes || minutes >= maxMinutes;
                        return (
                            <div 
                                key={time} 
                                style={{ 
                                    padding: '8px 12px', fontSize: '12px', cursor: isDisabled ? 'not-allowed' : 'pointer', display: 'flex', 
                                    justifyContent: 'space-between', alignItems: 'center', 
                                    background: value === time ? '#f3f4f6' : 'transparent',
                                    color: isDisabled ? '#d1d5db' : 'inherit',
                                    opacity: isDisabled ? 0.7 : 1
                                }}
                                onClick={() => { if (!isDisabled) { onChange(time); setIsOpen(false); } }}
                            >
                                <span>{time}</span>
                                {value === time && <FiCheck size={12} color="#7c3aed" />}
                            </div>
                        );
                    })}
                </div>
            )}
        </div>
    );
}

function DatePicker({ value, onChange }: { value: string, onChange: (val: string) => void }) {
    const [isOpen, setIsOpen] = useState(false);
    const [viewDate, setViewDate] = useState(new Date());
    const [selection, setSelection] = useState<{ start: Date | null, end: Date | null }>({
        start: null,
        end: null
    });
    const containerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    
    const formatDate = (date: Date) => {
        const d = String(date.getDate()).padStart(2, '0');
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const y = date.getFullYear();
        return `${m}/${d}/${y}`;
    };

    const handleDateClick = (date: Date) => {
        if (!selection.start || (selection.start && selection.end)) {
            setSelection({ start: date, end: null });
        } else if (date < selection.start) {
            setSelection({ start: date, end: selection.start });
        } else {
            setSelection({ ...selection, end: date });
        }
    };

    const handleApply = () => {
        if (selection.start && selection.end) {
            onChange(`${formatDate(selection.start)} - ${formatDate(selection.end)}`);
        } else if (selection.start) {
            onChange(formatDate(selection.start));
        }
        setIsOpen(false);
    };

    const isSelected = (date: Date) => {
        if (!selection.start) return false;
        if (selection.end) {
            return date >= selection.start && date <= selection.end;
        }
        return date.getTime() === selection.start.getTime();
    };

    const isEdge = (date: Date) => {
        if (!selection.start) return false;
        if (date.getTime() === selection.start.getTime()) return true;
        if (selection.end && date.getTime() === selection.end.getTime()) return true;
        return false;
    };

    const renderMonth = (monthOffset: number) => {
        const date = new Date(viewDate.getFullYear(), viewDate.getMonth() + monthOffset, 1);
        const daysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
        const startDay = date.getDay();

        return (
            <div style={{ flex: 1, minWidth: '220px' }}>
                <div style={{ textAlign: 'center', fontWeight: 600, fontSize: '14px', marginBottom: '16px' }}>
                    {months[date.getMonth()]} {date.getFullYear()}
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: '2px', textAlign: 'center', fontSize: '12px' }}>
                    {['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'].map(d => <span key={d} style={{ color: '#9ca3af', paddingBottom: '8px' }}>{d}</span>)}
                    {Array.from({ length: startDay }).map((_, i) => <div key={`empty-${i}`} />)}
                    {Array.from({ length: daysInMonth }).map((_, i) => {
                        const d = i + 1;
                        const currDate = new Date(date.getFullYear(), date.getMonth(), d);
                        const selected = isSelected(currDate);
                        const edge = isEdge(currDate);
                        return (
                            <div 
                                key={d} 
                                style={{ 
                                    padding: '8px 0', cursor: 'pointer', borderRadius: edge ? '4px' : '0',
                                    background: selected ? (edge ? '#1f2937' : '#f3f4f6') : 'transparent',
                                    color: selected && edge ? 'white' : 'inherit',
                                    zIndex: 1
                                }}
                                onClick={() => handleDateClick(currDate)}
                            >
                                {d}
                            </div>
                        );
                    })}
                </div>
            </div>
        );
    };

    return (
        <div style={{ position: 'relative', width: '100%' }} ref={containerRef}>
            <div 
                className={styles.chatInput} 
                style={{ 
                    width: '100%', height: '40px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '8px', 
                    background: 'white', border: '1px solid #e5e7eb', padding: '0 12px', fontSize: '13px', color: '#374151' 
                }}
                onClick={() => setIsOpen(!isOpen)}
            >
                <FiCalendar size={14} color="#6b7280" />
                <span>{value || 'Select holiday range'}</span>
            </div>
            {isOpen && (
                <div style={{ 
                    position: 'absolute', top: 'calc(100% + 8px)', right: 0, width: 'max-content',
                    background: 'white', border: '1px solid #e5e7eb', borderRadius: '12px', 
                    boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1)', zIndex: 100, padding: '24px' 
                }}>
                    <div style={{ display: 'flex', gap: '32px', position: 'relative' }}>
                        <div style={{ position: 'absolute', top: '-4px', left: 0, right: 0, display: 'flex', justifyContent: 'space-between', padding: '0 8px', pointerEvents: 'none' }}>
                            <FiChevronLeft style={{ cursor: 'pointer', pointerEvents: 'auto' }} onClick={() => setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() - 1))} />
                            <FiChevronRight style={{ cursor: 'pointer', pointerEvents: 'auto' }} onClick={() => setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() + 1))} />
                        </div>
                        {renderMonth(0)}
                        {renderMonth(1)}
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', marginTop: '24px' }}>
                        <button 
                            onClick={() => setIsOpen(false)}
                            style={{ padding: '8px 16px', background: 'white', border: '1px solid #d1d5db', borderRadius: '6px', fontSize: '13px', cursor: 'pointer' }}
                        >
                            Cancel
                        </button>
                        <button 
                            onClick={handleApply}
                            style={{ padding: '8px 16px', background: '#1f2937', color: 'white', border: 'none', borderRadius: '6px', fontSize: '13px', cursor: 'pointer' }}
                        >
                            Apply
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}

interface ChatAvailabilityProps {
    onBack: () => void;
}

export function ChatAvailability({ onBack }: ChatAvailabilityProps) {
    const { data: response, isLoading } = useGetChatAvailability();
    const updateMutation = useUpdateChatAvailability();
    const { showSuccess, showError } = useToast();
    const [formData, setFormData] = useState<any>(null);
    const [showHolidayAdd, setShowHolidayAdd] = useState(false);
    const [newHoliday, setNewHoliday] = useState({ name: '', date: '' });

    const defaultData = {
        working_hours: { type: 'custom', schedule: [] },
        break_time: { enabled: true, intervals: [] },
        holidays: { enabled: true, list: [] },
        timezone: '(GMT-05:00) Eastern Time (US & Canada)',
        auto_reply: { enabled: true, messages: { online: 'Thank you for reaching out. We\'ll be with you in a moment.', offline: 'Thanks for your message! We\'ve received your contact details and will get back to you soon.' } }
    };

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

    const handleSave = async () => {
        try {
            await updateMutation.mutateAsync(formData);
            showSuccess("Chat availability updated successfully");
        } catch (err) {
            showError("Failed to update availability");
        }
    };

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

    const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

    const updateNested = (path: string[], value: any) => {
        setFormData((prev: any) => {
            const next = { ...prev };
            let curr = next;
            for (let i = 0; i < path.length - 1; i++) {
                if (!curr[path[i]]) curr[path[i]] = {};
                curr = curr[path[i]];
            }
            curr[path[path.length - 1]] = value;
            return next;
        });
    };

    const updateSchedule = (day: string, field: string, value: any) => {
        const newSchedule = [...(formData.working_hours?.schedule || [])];
        const idx = newSchedule.findIndex(s => s.day === day);
        if (idx > -1) {
            newSchedule[idx] = { ...newSchedule[idx], [field]: value };
        } else {
            newSchedule.push({ day, enabled: field === 'enabled' ? value : true, start: '09:00 AM', end: '05:00 PM', [field]: value });
        }
        updateNested(['working_hours', 'schedule'], newSchedule);
    };

    const addInterval = (type: 'break_time' | 'holidays') => {
        if (type === 'break_time') {
            const intervals = [...(formData.break_time?.intervals || [])];
            intervals.push({ start: '12:00 PM', end: '01:00 PM' });
            updateNested(['break_time', 'intervals'], intervals);
        }
    };

    const removeInterval = (type: 'break_time' | 'holidays', idx: number) => {
        if (type === 'break_time') {
            const intervals = [...(formData.break_time?.intervals || [])];
            intervals.splice(idx, 1);
            updateNested(['break_time', 'intervals'], intervals);
        } else if (type === 'holidays') {
            const list = [...(formData.holidays?.list || [])];
            list.splice(idx, 1);
            updateNested(['holidays', 'list'], list);
        }
    };

    return (
        <div className={styles.inboxContainer} style={{ background: '#f9fafb', minHeight: '100vh' }}>
            <div className={styles.settingsFlexHeader} style={{ marginBottom: '24px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <button
                        onClick={onBack}
                        style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', fontSize: '20px' }}
                    >
                        <FiArrowLeft />
                    </button>
                    <div>
                        <h1 className={styles.faqTitle} style={{ fontSize: '22px', marginBottom: '4px' }}>Chat availability</h1>
                        <p style={{ fontSize: '14px', color: '#6b7280' }}>Set your available time to reply to customers</p>
                    </div>
                </div>
                <button
                    className={styles.syncBtn}
                    style={{ background: '#7c3aed', gap: '8px', display: 'flex', alignItems: 'center' }}
                    onClick={handleSave}
                    disabled={updateMutation.isPending}
                >
                    <FiSave /> {updateMutation.isPending ? 'Saving...' : 'Save changes'}
                </button>
            </div>

            <div className={styles.faqPageLayout} style={{ gap: '24px' }}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '24px' }}>
                    {/* Working Hour */}
                    <div className={styles.appearanceCard}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '8px' }}>Working hour</h3>
                        <p style={{ fontSize: '13px', color: '#6b7280', marginBottom: '20px' }}>Display your online status during these hours</p>

                        <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                            <div
                                className={styles.triggerOption}
                                style={{ marginBottom: 0, borderColor: formData.working_hours?.type === 'full' ? '#7c3aed' : '#e5e7eb' }}
                                onClick={() => updateNested(['working_hours', 'type'], 'full')}
                            >
                                <div className={`${styles.radioCircle} ${formData.working_hours?.type === 'full' ? styles.radioCircleActive : ''}`}>
                                    {formData.working_hours?.type === 'full' && <div className={styles.radioInner} />}
                                </div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                    <FiClock size={16} color="#6b7280" />
                                    <span style={{ fontSize: '14px' }}>24 hours / 7 days</span>
                                </div>
                            </div>

                            <div
                                className={`${styles.triggerOption} ${formData.working_hours?.type === 'custom' ? styles.triggerOptionActive : ''}`}
                                style={{ flexDirection: 'column', alignItems: 'flex-start', gap: '16px', padding: '20px' }}
                            >
                                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }} onClick={() => updateNested(['working_hours', 'type'], 'custom')}>
                                    <div className={`${styles.radioCircle} ${formData.working_hours?.type === 'custom' ? styles.radioCircleActive : ''}`}>
                                        {formData.working_hours?.type === 'custom' && <div className={styles.radioInner} />}
                                    </div>
                                    <span style={{ fontSize: '14px', fontWeight: 500 }}>Custom time</span>
                                </div>

                                {formData.working_hours?.type === 'custom' && (
                                    <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: '12px' }}>
                                        {days.map(day => {
                                            const schedule = formData.working_hours?.schedule?.find((s: any) => s.day === day) || { day, enabled: false, start: '09:00 AM', end: '05:00 PM' };
                                            return (
                                                <div key={day} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: '12px' }}>
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                                        <input 
                                                            type="checkbox" 
                                                            checked={schedule.enabled}
                                                            onChange={(e) => updateSchedule(day, 'enabled', e.target.checked)}
                                                        />
                                                        <span style={{ fontSize: '14px', color: '#374151' }}>{day}</span>
                                                    </div>
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px', opacity: schedule.enabled ? 1 : 0.5, pointerEvents: schedule.enabled ? 'auto' : 'none' }}>
                                                        <TimePicker 
                                                            value={schedule.start} 
                                                            maxTime={schedule.end}
                                                            onChange={(val) => updateSchedule(day, 'start', val)} 
                                                        />
                                                        <span style={{ fontSize: '13px', color: '#6b7280' }}>To</span>
                                                        <TimePicker 
                                                            value={schedule.end} 
                                                            minTime={schedule.start}
                                                            onChange={(val) => updateSchedule(day, 'end', val)} 
                                                        />
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* Break time */}
                    <div className={styles.appearanceCard}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', flexWrap: 'wrap', gap: '12px' }}>
                            <h3 style={{ fontSize: '15px', fontWeight: 600 }}>Break time</h3>
                            <label className={styles.switch}>
                                <input 
                                    type="checkbox" 
                                    checked={formData.break_time?.enabled}
                                    onChange={(e) => updateNested(['break_time', 'enabled'], e.target.checked)}
                                />
                                <span className={styles.slider}></span>
                            </label>
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', marginBottom: '16px' }}>
                            {(formData.break_time?.intervals || []).map((interval: any, idx: number) => (
                                <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                        <TimePicker 
                                            value={interval.start} 
                                            maxTime={interval.end}
                                            onChange={(val) => {
                                                const newIntervals = [...formData.break_time.intervals];
                                                newIntervals[idx] = { ...newIntervals[idx], start: val };
                                                updateNested(['break_time', 'intervals'], newIntervals);
                                            }}
                                        />
                                        <span style={{ fontSize: '13px', color: '#6b7280' }}>To</span>
                                        <TimePicker 
                                            value={interval.end} 
                                            minTime={interval.start}
                                            onChange={(val) => {
                                                const newIntervals = [...formData.break_time.intervals];
                                                newIntervals[idx] = { ...newIntervals[idx], end: val };
                                                updateNested(['break_time', 'intervals'], newIntervals);
                                            }}
                                        />
                                    </div>
                                    <FiTrash2 
                                        size={16} 
                                        color="#ef4444" 
                                        style={{ cursor: 'pointer' }}
                                        onClick={() => removeInterval('break_time', idx)}
                                    />
                                </div>
                            ))}
                        </div>
                        <button 
                            style={{ color: '#7c3aed', background: 'none', border: 'none', fontSize: '13px', display: 'flex', alignItems: 'center', gap: '4px', padding: 0, fontWeight: 500, cursor: 'pointer' }}
                            onClick={() => addInterval('break_time')}
                        >
                            <FiPlus /> Add break time
                        </button>
                    </div>

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

                        <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', marginBottom: '16px' }}>
                            {(formData.holidays?.list || []).map((holiday: any, idx: number) => {
                                const isRange = holiday.date.includes(' - ');
                                const split = holiday.date.split(' - ');
                                const startStr = split[0];
                                const endStr = split[1];
                                
                                const startObj = new Date(startStr);
                                const endObj = endStr ? new Date(endStr) : null;
                                
                                const isValidStart = !isNaN(startObj.getTime());
                                const isValidEnd = endObj && !isNaN(endObj.getTime());
                                
                                const startMonth = isValidStart ? startObj.toLocaleString('default', { month: 'short' }) : (startStr.split('/')[0] || '---');
                                const startDay = isValidStart ? startObj.getDate() : (startStr.split('/')[1] || '--');
                                
                                const endMonth = isValidEnd ? endObj!.toLocaleString('default', { month: 'short' }) : '';
                                const endDay = isValidEnd ? endObj!.getDate() : '';

                                return (
                                    <div key={idx} style={{ background: '#f5f3ff', borderRadius: '12px', padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '12px' }}>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                                            <div style={{ background: '#e0e7ff', padding: '8px', borderRadius: '8px', textAlign: 'center', minWidth: isRange ? '80px' : '56px' }}>
                                                <div style={{ fontSize: '9px', color: '#4b5563', textTransform: 'uppercase', fontWeight: 700, display: 'flex', justifyContent: 'center', gap: '4px' }}>
                                                    <span>{startMonth}</span>
                                                    {isRange && <span>- {endMonth}</span>}
                                                </div>
                                                <div style={{ fontSize: '15px', fontWeight: 800, color: '#111827', marginTop: '2px', display: 'flex', justifyContent: 'center', gap: '4px' }}>
                                                    <span>{startDay}</span>
                                                    {isRange && <span>- {endDay}</span>}
                                                </div>
                                            </div>
                                            <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
                                                <span style={{ fontSize: '14px', fontWeight: 600, color: '#111827' }}>{holiday.name}</span>
                                                <span style={{ fontSize: '12px', color: '#6b7280' }}>{holiday.date}</span>
                                            </div>
                                        </div>
                                        <FiTrash2 
                                            size={16} 
                                            color="#ef4444" 
                                            style={{ cursor: 'pointer' }} 
                                            onClick={() => {
                                                const newList = [...formData.holidays.list];
                                                newList.splice(idx, 1);
                                                updateNested(['holidays', 'list'], newList);
                                            }}
                                        />
                                    </div>
                                );
                            })}
                        </div>

                        {showHolidayAdd ? (
                            <div style={{ background: '#f9fafb', border: '1px solid #e5e7eb', borderRadius: '12px', padding: '16px', marginTop: '12px' }}>
                                <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                                        <div>
                                            <label style={{ fontSize: '12px', color: '#6b7280', display: 'block', marginBottom: '8px' }}>Holiday name</label>
                                            <input 
                                                type="text" 
                                                className={styles.chatInput} 
                                                style={{ width: '100%', background: 'white' }} 
                                                value={newHoliday.name}
                                                onChange={(e) => setNewHoliday(prev => ({ ...prev, name: e.target.value }))}
                                                placeholder="e.g. Christmas"
                                            />
                                        </div>
                                        <div>
                                            <label style={{ fontSize: '12px', color: '#6b7280', display: 'block', marginBottom: '8px' }}>Date</label>
                                            <DatePicker 
                                                value={newHoliday.date} 
                                                onChange={(val) => setNewHoliday(prev => ({ ...prev, date: val }))} 
                                            />
                                        </div>
                                    </div>
                                    <button 
                                        className={styles.syncBtn} 
                                        style={{ background: '#7c3aed', width: '100%', padding: '10px' }} 
                                        onClick={() => {
                                            if (newHoliday.name && newHoliday.date) {
                                                const list = [...(formData.holidays?.list || [])];
                                                list.push({ ...newHoliday });
                                                updateNested(['holidays', 'list'], list);
                                                setNewHoliday({ name: '', date: '' });
                                                setShowHolidayAdd(false);
                                            }
                                        }}
                                    >
                                        Add Holiday
                                    </button>
                                </div>
                            </div>
                        ) : (
                            <button
                                style={{ color: '#7c3aed', background: 'none', border: 'none', fontSize: '13px', display: 'flex', alignItems: 'center', gap: '4px', padding: 0, fontWeight: 500, cursor: 'pointer' }}
                                onClick={() => setShowHolidayAdd(true)}
                            >
                                <FiPlus /> Add holiday
                            </button>
                        )}
                    </div>

                    {/* Time zone */}
                    <div className={styles.appearanceCard}>
                        <h3 style={{ fontSize: '15px', fontWeight: 600, marginBottom: '16px' }}>Time zone</h3>
                        <select 
                            className={styles.chatInput} 
                            style={{ width: '100%', textAlign: 'left', background: '#f9fafb' }}
                            value={formData.timezone}
                            onChange={(e) => updateNested(['timezone'], e.target.value)}
                        >
                            <option>(GMT-05:00) Eastern Time (US & Canada)</option>
                            <option>(GMT+00:00) Western European Time</option>
                            <option>(GMT+05:30) India Standard Time</option>
                        </select>
                    </div>

                    {/* First auto-reply */}
                    <div className={styles.appearanceCard}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', flexWrap: 'wrap', gap: '12px' }}>
                            <h3 style={{ fontSize: '15px', fontWeight: 600 }}>First auto-reply</h3>
                            <label className={styles.switch}>
                                <input 
                                    type="checkbox" 
                                    checked={formData.auto_reply?.enabled}
                                    onChange={(e) => updateNested(['auto_reply', 'enabled'], e.target.checked)}
                                />
                                <span className={styles.slider}></span>
                            </label>
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                            <div>
                                <label style={{ fontSize: '13px', color: '#6b7280', display: 'block', marginBottom: '8px' }}>Online message</label>
                                <textarea
                                    className={styles.chatInput}
                                    style={{ width: '100%', height: '80px', textAlign: 'left', background: '#f9fafb', border: 'none', padding: '12px', fontSize: '13px', resize: 'none' }}
                                    value={formData.auto_reply?.messages?.online || ""}
                                    onChange={(e) => updateNested(['auto_reply', 'messages', 'online'], e.target.value)}
                                />
                            </div>
                            <div>
                                <label style={{ fontSize: '13px', color: '#6b7280', display: 'block', marginBottom: '8px' }}>Offline message</label>
                                <textarea
                                    className={styles.chatInput}
                                    style={{ width: '100%', height: '100px', textAlign: 'left', background: '#f9fafb', border: 'none', padding: '12px', fontSize: '13px', lineHeight: 1.5, resize: 'none' }}
                                    value={formData.auto_reply?.messages?.offline || ""}
                                    onChange={(e) => updateNested(['auto_reply', 'messages', 'offline'], e.target.value)}
                                />
                            </div>
                        </div>
                    </div>
                </div>

                {/* Preview */}
                <div style={{ height: 'fit-content' }}>
                    <div className={styles.feedbackCard} style={{ padding: '24px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px', flexWrap: 'wrap', gap: '12px' }}>
                            <h3 style={{ fontSize: '15px', fontWeight: 600 }}>Preview</h3>
                            <div className={styles.actionIconBtn} style={{ minWidth: '100px', gap: '8px', fontSize: '12px' }}>
                                <FiMonitor /> Desktop
                            </div>
                        </div>
                        <div className={styles.phoneFrame} style={{ borderColor: '#f3f4f6', margin: '0 auto' }}>
                            <div className={styles.chatBody} style={{ background: 'white', position: 'relative', overflow: 'hidden' }}>
                                {/* Custom Store Header */}
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', borderBottom: '1px solid #f3f4f6' }}>
                                    <div style={{ fontSize: '12px', fontWeight: 800 }}>☰</div>
                                    <div style={{ fontSize: '10px', fontWeight: 800 }}>YOUR STORE</div>
                                    <div style={{ display: 'flex', gap: '8px' }}>
                                        <div style={{ fontSize: '12px' }}>🔍</div>
                                        <div style={{ fontSize: '12px' }}>🛒</div>
                                    </div>
                                </div>

                                {/* Chat Bot Interface */}
                                <div style={{ padding: '20px 16px' }}>
                                    <div style={{ background: 'linear-gradient(135deg, #7c3aed 0%, #a855f7 100%)', padding: '20px', borderRadius: '16px', color: 'white' }}>
                                        <div style={{ fontSize: '20px', fontWeight: 700, marginBottom: '8px' }}>Hi 👋</div>
                                        <div style={{ fontSize: '13px', opacity: 0.9 }}>How can we help you?</div>
                                    </div>

                                    <div style={{ marginTop: '16px', background: 'white', borderRadius: '12px', border: '1px solid #f3f4f6', padding: '16px', boxShadow: '0 4px 6px -1px rgba(0,0,0,0.05)' }}>
                                        <div style={{ fontSize: '13px', fontWeight: 600, marginBottom: '12px' }}>Contact us</div>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
                                            <div style={{ width: '8px', height: '8px', background: '#22c55e', borderRadius: '50%' }} />
                                            <span style={{ fontSize: '11px', color: '#6b7280' }}>We are online</span>
                                        </div>
                                        <div style={{ background: '#f59e0b', width: '28px', height: '28px', borderRadius: '6px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white' }}>
                                            ✉️
                                        </div>
                                    </div>

                                    <div style={{ marginTop: '12px', background: 'white', borderRadius: '12px', border: '1px solid #f3f4f6', padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                        <div>
                                            <div style={{ fontSize: '13px', fontWeight: 600 }}>Order tracking</div>
                                            <div style={{ fontSize: '11px', color: '#6b7280', marginTop: '2px' }}>Track your orders</div>
                                        </div>
                                        <span style={{ color: '#9ca3af' }}>›</span>
                                    </div>

                                    <div style={{ marginTop: '12px', position: 'relative' }}>
                                        <input type="text" placeholder="Search for help" style={{ width: '100%', background: '#f9fafb', border: '1px solid #f3f4f6', borderRadius: '8px', padding: '10px 32px 10px 12px', fontSize: '12px' }} />
                                        <span style={{ position: 'absolute', right: '12px', top: '10px', color: '#9ca3af' }}>🔍</span>
                                    </div>

                                    <div style={{ marginTop: '16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                        {['How long will it take to receive my order?', 'How to track my order?', 'Do you ship internationally?'].map(txt => (
                                            <div key={txt} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid #f9fafb' }}>
                                                <span style={{ fontSize: '12px', color: '#4b5563' }}>{txt}</span>
                                                <span style={{ color: '#9ca3af' }}>›</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
