import React, { useState, useEffect, lazy, Suspense, useRef } from 'react';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGoogle, faApple, faMicrosoft } from '@fortawesome/free-brands-svg-icons';
import { faServer } from '@fortawesome/free-solid-svg-icons';

const RichTextEditor = lazy(() => import('./RichTextEditor'));

interface CalendarEventModalProps {
    event?: any; // Existing event if editing
    initialDate?: Date; // If creating new
    initialStartTime?: string; // If creating new from slot
    connections: any[]; // To select calendar
    onClose: () => void;
    onSave: (eventData: any) => Promise<void>;
    onDelete?: (eventId: string, calendarId: string) => Promise<void>;
}

export default function CalendarEventModal({
    event,
    initialDate,
    initialStartTime,
    connections,
    onClose,
    onSave,
    onDelete
}: CalendarEventModalProps) {
    // Flatten calendars from connections to get selectable options
    const availableCalendars = connections
        .flatMap(conn => (conn.calendars || []).map((cal: any) => ({
            ...cal,
            provider: conn.provider,
            providerName: conn.provider === 'google' ? 'Google Calendar' :
                conn.provider === 'apple' ? 'Apple Calendar' :
                    conn.provider === 'synology' ? 'Synology Calendar' :
                        'Outlook Calendar'
        })))
        .filter((cal: any) => cal.editable); // Only editable calendars

    const [title, setTitle] = useState(event?.title || '');
    const [description, setDescription] = useState(event?.description || '');
    const [location, setLocation] = useState(event?.location || '');
    const [url, setUrl] = useState(event?.url || '');
    const [recurrence, setRecurrence] = useState(event?.recurrence || 'none');
    const [calendarId, setCalendarId] = useState(event?.calendarId || (availableCalendars.length > 0 ? availableCalendars[0].id : ''));

    // Date/Time State
    // If event exists, use its start/end.
    // If new, use initialDate + initialStartTime.
    // Default duration: 1 hour.

    const getInitialStart = () => {
        // Support both nested (start.dateTime) and flat (startTime) event formats
        if (event?.start?.dateTime) return new Date(event.start.dateTime);
        if (event?.startTime) return new Date(event.startTime);
        if (initialDate) {
            const d = new Date(initialDate);
            if (initialStartTime) {
                const [h, m] = initialStartTime.split(':').map(Number);
                d.setHours(h, m, 0, 0);
            } else {
                // Default to next hour if no time specified (though usually slot click gives time)
                const now = new Date();
                d.setHours(now.getHours() + 1, 0, 0, 0);
            }
            return d;
        }
        return new Date();
    };

    const getInitialEnd = () => {
        // Support both nested (end.dateTime) and flat (endTime) event formats
        if (event?.end?.dateTime) return new Date(event.end.dateTime);
        if (event?.endTime) return new Date(event.endTime);
        const start = getInitialStart();
        return new Date(start.getTime() + 60 * 60 * 1000); // +1 hour
    };

    const [startDate, setStartDate] = useState(getInitialStart());
    const [endDate, setEndDate] = useState(getInitialEnd());
    const [allDay, setAllDay] = useState(!!event?.allDay);
    const [isSaving, setIsSaving] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);
    const [error, setError] = useState('');
    const [isCalendarSelectorOpen, setIsCalendarSelectorOpen] = useState(false);
    const calendarSelectorRef = useRef<HTMLDivElement>(null);

    // Close dropdown on outside click
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (calendarSelectorRef.current && !calendarSelectorRef.current.contains(event.target as Node)) {
                setIsCalendarSelectorOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const selectedCal = availableCalendars.find((c: any) => c.id === calendarId);
    const supportsURL = selectedCal && (selectedCal.provider !== 'google' && selectedCal.provider !== 'outlook');
    const getProviderIcon = (provider: string) => {
        switch (provider) {
            case 'google': return <FontAwesomeIcon icon={faGoogle} style={{ opacity: 0.8 }} />;
            case 'apple': return <FontAwesomeIcon icon={faApple} style={{ opacity: 0.8 }} />;
            case 'outlook': return <FontAwesomeIcon icon={faMicrosoft} style={{ opacity: 0.8 }} />;
            case 'synology': return <FontAwesomeIcon icon={faServer} style={{ opacity: 0.8, fontSize: '0.8rem' }} />;
            default: return null;
        }
    };

    const handleSubmit = async () => {
        if (!title.trim()) {
            setError('Title is required');
            return;
        }
        if (!calendarId) {
            setError('Please select a calendar');
            return;
        }
        if (endDate <= startDate) {
            setError('End time must be after start time');
            return;
        }

        setIsSaving(true);
        setError('');
        try {
            await onSave({
                id: event?.id,
                title,
                description,
                location,
                url: url || undefined,
                recurrence: recurrence !== 'none' ? recurrence : undefined,
                calendarId,
                allDay,
                start: { dateTime: startDate.toISOString() },
                end: { dateTime: endDate.toISOString() }
            });
            onClose();
        } catch (err: any) {
            console.error(err);
            setError(err.message || 'Failed to save event');
            setIsSaving(false);
        }
    };

    const [isDeleteConfirming, setIsDeleteConfirming] = useState(false);

    const handleDelete = async () => {
        if (!event?.id || !onDelete) return;

        if (!isDeleteConfirming) {
            setIsDeleteConfirming(true);
            setTimeout(() => setIsDeleteConfirming(false), 3000); // Reset after 3 seconds
            return;
        }

        setIsDeleting(true);
        try {
            await onDelete(event.id, event.calendarId);
            onClose();
        } catch (err: any) {
            setError(err.message || 'Failed to delete event');
            setIsDeleting(false);
            setIsDeleteConfirming(false);
        }
    };

    // Helper to format date for input type="datetime-local"
    // Format: YYYY-MM-DDThh:mm
    const toLocalISOString = (date: Date) => {
        const offset = date.getTimezoneOffset() * 60000;
        const localISOTime = (new Date(date.getTime() - offset)).toISOString().slice(0, 16);
        return localISOTime;
    };

    const handleStartDateChange = (val: string) => {
        const newStart = new Date(val);
        setStartDate(newStart);
        // Auto-adjust end date if it becomes before start
        if (endDate <= newStart) {
            setEndDate(new Date(newStart.getTime() + 60 * 60 * 1000));
        }
    };


    return (
        <div className="weekly-modal-overlay" onClick={onClose}>
            <div className="weekly-modal-content" onClick={e => e.stopPropagation()} style={{ 
                maxWidth: '450px', 
                padding: '20px', 
                borderRadius: '12px',
                boxShadow: '0 10px 25px rgba(0,0,0,0.15)',
                border: '1px solid var(--weekly-border)'
            }}>
                {error && <div style={{ color: '#ef4444', marginBottom: '1rem', fontSize: '0.85rem', textAlign: 'center' }}>{error}</div>}

                <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                    {/* Title Input */}
                    <input
                        type="text"
                        value={title}
                        onChange={e => setTitle(e.target.value)}
                        placeholder="New Event"
                        autoFocus
                        style={{ 
                            width: '100%', 
                            padding: '12px 16px', 
                            fontSize: '1.25rem', 
                            fontWeight: 600,
                            border: 'none', 
                            borderBottom: '1px solid var(--weekly-border)',
                            borderRadius: '0',
                            background: 'transparent',
                            outline: 'none',
                            marginBottom: '4px'
                        }}
                    />

                    {/* Location Input */}
                    <input
                        type="text"
                        value={location}
                        onChange={e => setLocation(e.target.value)}
                        placeholder="Location or Video Call"
                        style={{ 
                            width: '100%', 
                            padding: '8px 16px', 
                            border: 'none', 
                            borderBottom: '1px solid var(--weekly-border)',
                            borderRadius: '0',
                            background: 'transparent',
                            outline: 'none',
                            fontSize: '0.95rem'
                        }}
                    />

                    {/* Calendar row: Label + Custom Selector */}
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 16px', position: 'relative' }}>
                        <span style={{ fontSize: '0.9rem', color: 'var(--weekly-text-light)', fontWeight: 500 }}>Calendar</span>
                        
                        <div ref={calendarSelectorRef} style={{ position: 'relative', flex: 1, display: 'flex', justifyContent: 'flex-end' }}>
                            <button
                                type="button"
                                onClick={() => !event && setIsCalendarSelectorOpen(!isCalendarSelectorOpen)}
                                disabled={!!event}
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '8px',
                                    background: 'transparent',
                                    border: 'none',
                                    fontWeight: 500,
                                    cursor: event ? 'default' : 'pointer',
                                    outline: 'none',
                                    color: 'var(--weekly-text)',
                                    fontSize: '0.95rem',
                                    padding: '4px 0',
                                    maxWidth: '200px',
                                    justifyContent: 'flex-end'
                                }}
                            >
                                <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                    {selectedCal?.summary || selectedCal?.title || 'Select Calendar'}
                                </span>
                                <div style={{ 
                                    width: '12px', 
                                    height: '12px', 
                                    borderRadius: '50%', 
                                    backgroundColor: selectedCal?.backgroundColor || selectedCal?.color || '#3b82f6' 
                                }} />
                                {!event && (isCalendarSelectorOpen ? <ChevronUp size={14} /> : <ChevronDown size={14} />)}
                            </button>

                            {isCalendarSelectorOpen && (
                                <div style={{
                                    position: 'absolute',
                                    top: '100%',
                                    right: 0,
                                    zIndex: 100,
                                    minWidth: '220px',
                                    backgroundColor: 'var(--weekly-bg-popover, #ffffff)',
                                    borderRadius: '10px',
                                    boxShadow: '0 4px 15px rgba(0,0,0,0.1)',
                                    border: '1px solid var(--weekly-border)',
                                    marginTop: '5px',
                                    padding: '6px',
                                    maxHeight: '250px',
                                    overflowY: 'auto'
                                }}>
                                    {availableCalendars.map((cal: any) => (
                                        <div
                                            key={cal.id}
                                            onClick={() => {
                                                setCalendarId(cal.id);
                                                setIsCalendarSelectorOpen(false);
                                            }}
                                            style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                gap: '10px',
                                                padding: '8px 12px',
                                                borderRadius: '6px',
                                                cursor: 'pointer',
                                                fontSize: '0.9rem',
                                                color: 'var(--weekly-text)',
                                                backgroundColor: calendarId === cal.id ? 'var(--weekly-selection, rgba(59, 130, 246, 0.1))' : 'transparent',
                                                transition: 'background 0.2s',
                                                textAlign: 'left'
                                            }}
                                            onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'var(--weekly-hover, rgba(0,0,0,0.05))'}
                                            onMouseLeave={(e) => e.currentTarget.style.backgroundColor = calendarId === cal.id ? 'var(--weekly-selection, rgba(59, 130, 246, 0.1))' : 'transparent'}
                                        >
                                            <div style={{ width: '10px', height: '10px', borderRadius: '50%', backgroundColor: cal.backgroundColor || cal.color || '#3b82f6', flexShrink: 0 }} />
                                            <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                                {cal.summary || cal.title}
                                            </span>
                                            <span style={{ color: 'var(--weekly-text-light)', opacity: 0.6 }}>
                                                {getProviderIcon(cal.provider)}
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>

                    {/* All Day row */}
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 16px' }}>
                        <span style={{ fontSize: '0.9rem', color: 'var(--weekly-text-light)', fontWeight: 500 }}>All Day</span>
                        <input
                            type="checkbox"
                            checked={allDay}
                            onChange={e => setAllDay(e.target.checked)}
                            style={{ width: '18px', height: '18px', cursor: 'pointer' }}
                        />
                    </div>

                    {/* Date/Time rows */}
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', padding: '0 16px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <span style={{ fontSize: '0.9rem', color: 'var(--weekly-text-light)', fontWeight: 500 }}>Starts</span>
                            <input
                                type={allDay ? "date" : "datetime-local"}
                                value={allDay ? startDate.toISOString().split('T')[0] : toLocalISOString(startDate)}
                                onChange={e => handleStartDateChange(e.target.value)}
                                style={{ 
                                    padding: '4px 8px', 
                                    border: 'none', 
                                    borderRadius: '6px', 
                                    background: 'var(--weekly-bg-secondary, #f3f4f6)',
                                    fontSize: '0.9rem',
                                    textAlign: 'center'
                                }}
                            />
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <span style={{ fontSize: '0.9rem', color: 'var(--weekly-text-light)', fontWeight: 500 }}>Ends</span>
                            <input
                                type={allDay ? "date" : "datetime-local"}
                                value={allDay ? endDate.toISOString().split('T')[0] : toLocalISOString(endDate)}
                                onChange={e => setEndDate(new Date(e.target.value))}
                                style={{ 
                                    padding: '4px 8px', 
                                    border: 'none', 
                                    borderRadius: '6px', 
                                    background: 'var(--weekly-bg-secondary, #f3f4f6)',
                                    fontSize: '0.9rem',
                                    textAlign: 'center'
                                }}
                            />
                        </div>
                    </div>

                    {/* Meta Fields Group */}
                    <div style={{ padding: '8px 16px', display: 'flex', flexDirection: 'column', gap: '12px', marginTop: '4px' }}>
                        {/* Recurrence */}
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <span style={{ fontSize: '0.9rem', color: 'var(--weekly-text-light)', fontWeight: 500 }}>Repeat</span>
                            <select
                                value={recurrence}
                                onChange={e => setRecurrence(e.target.value)}
                                style={{ 
                                    background: 'transparent', 
                                    border: 'none', 
                                    textAlign: 'right',
                                    fontSize: '0.9rem',
                                    cursor: 'pointer',
                                    outline: 'none',
                                    color: 'var(--weekly-text)'
                                }}
                            >
                                <option value="none">Never</option>
                                <option value="daily">Every Day</option>
                                <option value="weekly">Every Week</option>
                                <option value="monthly">Every Month</option>
                                <option value="yearly">Every Year</option>
                            </select>
                        </div>

                        {/* URL (Conditional) */}
                        {supportsURL && (
                            <input
                                type="url"
                                value={url}
                                onChange={e => setUrl(e.target.value)}
                                placeholder="URL"
                                style={{ 
                                    width: '100%', 
                                    padding: '6px 0', 
                                    border: 'none', 
                                    borderBottom: '1px solid var(--weekly-border)',
                                    background: 'transparent',
                                    fontSize: '0.9rem',
                                    outline: 'none'
                                }}
                            />
                        )}

                        {/* Notes */}
                        <div style={{ marginTop: '4px' }}>
                            <Suspense fallback={
                                <textarea
                                    value={description}
                                    onChange={e => setDescription(e.target.value)}
                                    placeholder="Notes"
                                    rows={3}
                                    style={{ width: '100%', padding: '8px 0', border: 'none', borderBottom: '1px solid var(--weekly-border)', background: 'transparent', resize: 'none', fontSize: '0.9rem', outline: 'none' }}
                                />
                            }>
                                <RichTextEditor
                                    value={description}
                                    onChange={setDescription}
                                    placeholder="Notes"
                                    minHeight="80px"
                                />
                            </Suspense>
                        </div>
                    </div>
                </div>

                <div className="weekly-modal-actions" style={{ marginTop: '20px', display: 'flex', justifyContent: 'space-between', borderTop: '1px solid var(--weekly-border)', paddingTop: '15px' }}>
                    <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                        {event && onDelete && (
                            <button
                                onClick={handleDelete}
                                disabled={isSaving || isDeleting}
                                style={{
                                    padding: '8px 12px',
                                    background: 'none',
                                    color: '#ef4444',
                                    border: 'none',
                                    borderRadius: '6px',
                                    fontSize: '0.9rem',
                                    fontWeight: 500,
                                    cursor: 'pointer',
                                    transition: 'all 0.2s',
                                    opacity: isSaving || isDeleting ? 0.5 : 1
                                }}
                            >
                                {isDeleting ? 'Deleting...' : isDeleteConfirming ? 'Confirm Delete' : 'Delete'}
                            </button>
                        )}
                        {!event && (
                            <button className="weekly-btn-ghost" onClick={onClose} style={{ padding: '8px 12px', fontSize: '0.9rem', color: 'var(--weekly-text-light)', border: 'none', background: 'none', cursor: 'pointer' }}>
                                Cancel
                            </button>
                        )}
                    </div>
                    
                    <div style={{ display: 'flex', gap: '8px' }}>
                        {event && (
                            <button className="weekly-btn-ghost" onClick={onClose} style={{ padding: '8px 12px', fontSize: '0.9rem', color: 'var(--weekly-text-light)', border: 'none', background: 'none', cursor: 'pointer' }}>
                                Cancel
                            </button>
                        )}
                        <button 
                            className="weekly-btn-primary" 
                            onClick={handleSubmit} 
                            disabled={isSaving || isDeleting}
                            style={{ 
                                padding: '8px 20px', 
                                borderRadius: '8px', 
                                fontSize: '0.95rem', 
                                fontWeight: 600,
                                backgroundColor: '#3b82f6',
                                color: 'white',
                                border: 'none',
                                cursor: 'pointer',
                                opacity: isSaving || isDeleting ? 0.7 : 1
                            }}
                        >
                            {isSaving ? 'Saving...' : 'Save'}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}
