import React, { useState, useEffect, useMemo } from 'react';
import WidgetContainer from './WidgetContainer';
import styles from './WidgetStyles.module.css';
import { INITIAL_TASKS } from '../../data/mockFleetData';

const ForecastWidget = ({ onExpand, onNavigate }) => {
    // State
    const [items, setItems] = useState([]);
    const [isAdding, setIsAdding] = useState(false);

    // Explicitly expanded or passed as prop implies NOT dashboard widget mode
    const isDashboardWidget = !!onExpand;
    const [localExpanded, setLocalExpanded] = useState(false);
    const isExpanded = !isDashboardWidget || localExpanded; // If not a widget (full view), always expanded
    const [editingId, setEditingId] = useState(null);
    const [viewMode, setViewMode] = useState('Dashboard'); // 'Dashboard' or 'Details'

    // Form State (for both Add and Edit)
    const [formData, setFormData] = useState({
        description: '',
        aircraft: '',
        due: '',
        status: 'yellow',
        type: 'Checks'
    });

    // Filters matching PDF layout
    const [filters, setFilters] = useState({
        aircraft: 'All',
        status: 'All',
        remainingHours: '',
        remainingCycles: '',
        remainingMonths: ''
    });

    // Initialize Data
    useEffect(() => {
        const mappedTasks = INITIAL_TASKS.map(task => ({
            id: task.id,
            type: task.category,
            aircraft: task.reg,
            description: task.description,
            due: task.date,
            status: task.status,
            priority: task.status === 'red' ? 'High' : task.status === 'yellow' ? 'Medium' : 'Low',
            operator: 'Weststar Aviation'
        }));
        setItems(mappedTasks);
    }, []);

    // Helper: Distinct Lists for Dropdowns
    const uniqueAircraft = useMemo(() => ['All', ...new Set(items.map(i => i.aircraft))], [items]);
    const uniqueTypes = useMemo(() => [...new Set(INITIAL_TASKS.map(t => t.category)), 'Manual'], []);

    // Filter Logic
    const filteredItems = useMemo(() => {
        return items.filter(item => {
            const matchesAircraft = filters.aircraft === 'All' || item.aircraft === filters.aircraft;
            const matchesStatus = filters.status === 'All'
                ? true
                : filters.status === 'Applicable' ? true // Mock 'Applicable' logic
                    : item.status === filters.status;

            // Mock logic for remaining limits filters (since we don't have actual hours/cycles data attached to tasks yet)
            // In a real app, we'd check against item.remainingHours etc.

            return matchesAircraft && matchesStatus;
        }).sort((a, b) => {
            // Sort by Priority then Date
            const priorityOrder = { 'High': 0, 'Medium': 1, 'Low': 2 };
            if (priorityOrder[a.priority] !== priorityOrder[b.priority]) return priorityOrder[a.priority] - priorityOrder[b.priority];
            return new Date(a.due) - new Date(b.due);
        });
    }, [items, filters]);

    // Handlers
    const handleExpandToggle = () => {
        if (!isDashboardWidget) return; // Can't toggle if full view
        const newExpandedState = !localExpanded;
        setLocalExpanded(newExpandedState);
        if (onExpand) onExpand(newExpandedState);
        // Reset edit/add modes on toggle
        setIsAdding(false);
        setEditingId(null);
    };

    const handleAddClick = () => {
        setFormData({ description: '', aircraft: uniqueAircraft[1] || '', due: '', status: 'yellow', type: 'Checks' });
        setIsAdding(true);
        setEditingId(null);
    };

    const handleEditClick = (item) => {
        setFormData({
            description: item.description,
            aircraft: item.aircraft,
            due: item.due,
            status: item.status,
            type: item.type
        });
        setEditingId(item.id);
        setIsAdding(false);
    };

    const handleSave = () => {
        if (!formData.description || !formData.aircraft) return;

        const newItem = {
            ...formData,
            priority: formData.status === 'red' ? 'High' : formData.status === 'yellow' ? 'Medium' : 'Low',
            operator: 'Weststar Aviation'
        };

        if (isAdding) {
            setItems([...items, { id: Date.now(), ...newItem }]);
            setIsAdding(false);
        } else if (editingId) {
            setItems(items.map(item => item.id === editingId ? { ...item, ...newItem } : item));
            setEditingId(null);
        }
    };

    const handleDelete = (id) => {
        if (window.confirm('Are you sure you want to delete this task?')) {
            setItems(items.filter(i => i.id !== id));
        }
    };

    // Render Form (Shared)
    const renderFormInputs = () => (
        <>
            <input
                placeholder="Description"
                value={formData.description}
                onChange={e => setFormData({ ...formData, description: e.target.value })}
                style={{ flex: 2, padding: '0.4rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white', minWidth: '150px' }}
            />
            <select
                value={formData.aircraft}
                onChange={e => setFormData({ ...formData, aircraft: e.target.value })}
                style={{ flex: 1, padding: '0.4rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
            >
                {uniqueAircraft.filter(a => a !== 'All').map(ac => <option key={ac} value={ac}>{ac}</option>)}
            </select>
            <select
                value={formData.type}
                onChange={e => setFormData({ ...formData, type: e.target.value })}
                style={{ flex: 1, padding: '0.4rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
            >
                {uniqueTypes.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
            <select
                value={formData.status}
                onChange={e => setFormData({ ...formData, status: e.target.value })}
                style={{ flex: 1, padding: '0.4rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
            >
                <option value="green">Safe (Green)</option>
                <option value="yellow">Warning (Yellow)</option>
                <option value="red">Critical (Red)</option>
            </select>
            <input
                type="date"
                value={formData.due}
                onChange={e => setFormData({ ...formData, due: e.target.value })}
                style={{ flex: 1, padding: '0.4rem', borderRadius: '4px', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', color: 'white' }}
            />
        </>
    );

    const displayedItems = isExpanded ? filteredItems : filteredItems.slice(0, 5);

    return (
        <WidgetContainer
            title={isExpanded ? "Fleet Synthesis" : "Maintenance Forecast"} // Updated title to match PDF context if needed, or keep generic
            onExpand={handleExpandToggle}
            onAdd={handleExpandToggle}
            isExpanded={isExpanded}
        >
            <div className={styles.list} style={{ height: '100%', overflowY: 'auto', paddingRight: '0.5rem', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>

                {/* SAP-STYLE FILTERS (Only in Action Center Mode) */}
                {isExpanded && (
                    <div style={{
                        padding: '1.5rem',
                        background: '#ffffff',
                        borderRadius: '12px',
                        marginBottom: '1.5rem',
                        color: '#333',
                        border: '1px solid #e2e8f0',
                        boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03)'
                    }}>
                        <div style={{ marginBottom: '1.5rem', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <div style={{ fontSize: '1.25rem', fontWeight: 700, color: '#1e293b', letterSpacing: '-0.025em' }}>Action Center Filters</div>
                            <div style={{ fontSize: '0.85rem', color: '#64748b' }}>Refine your search</div>
                        </div>

                        {/* Row 1: A/C Registration */}
                        <div style={{ marginBottom: '1.5rem' }}>
                            <label style={{ display: 'block', fontSize: '0.9rem', fontWeight: 700, marginBottom: '0.5rem', color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.05em' }}>A/C Registration</label>
                            <select
                                value={filters.aircraft}
                                onChange={e => setFilters({ ...filters, aircraft: e.target.value })}
                                style={{
                                    width: '100%',
                                    maxWidth: '350px',
                                    padding: '1rem',
                                    borderRadius: '8px',
                                    border: '1px solid #cbd5e1',
                                    background: '#f8fafc',
                                    color: '#0f172a',
                                    fontSize: '1.1rem',
                                    outline: 'none',
                                    transition: 'all 0.2s',
                                    fontWeight: 500
                                }}
                                onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                                onBlur={(e) => e.target.style.borderColor = '#cbd5e1'}
                            >
                                {uniqueAircraft.map(ac => <option key={ac} value={ac}>{ac === 'All' ? 'Select Aircraft...' : ac}</option>)}
                            </select>
                        </div>

                        {/* Row 2: Status & Limits */}
                        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '3rem', alignItems: 'start' }}>
                            <div>
                                <label style={{ display: 'block', fontSize: '0.9rem', fontWeight: 700, marginBottom: '0.5rem', color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Visits/Tasks Status</label>
                                <select
                                    value={filters.status}
                                    onChange={e => setFilters({ ...filters, status: e.target.value })}
                                    style={{ width: '100%', padding: '1rem', borderRadius: '8px', border: '1px solid #cbd5e1', background: '#f8fafc', color: '#0f172a', outline: 'none', transition: 'all 0.2s', fontSize: '1.1rem', fontWeight: 500 }}
                                    onFocus={(e) => e.target.style.borderColor = '#3b82f6'}
                                    onBlur={(e) => e.target.style.borderColor = '#cbd5e1'}
                                >
                                    <option value="All">Applicable</option>
                                    <option value="red">Critical</option>
                                    <option value="yellow">Warning</option>
                                    <option value="green">Safe</option>
                                </select>
                            </div>

                            {['Remaining Hours', 'Remaining Cycles', 'Remaining Months'].map((label, idx) => (
                                <div key={label}>
                                    <label style={{ display: 'block', fontSize: '0.9rem', fontWeight: 700, marginBottom: '0.5rem', color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</label>
                                    <input
                                        type="number"
                                        placeholder="-"
                                        style={{
                                            width: '100%',
                                            padding: '1rem',
                                            borderRadius: '8px',
                                            border: '1px solid #cbd5e1',
                                            background: '#f8fafc',
                                            color: '#0f172a',
                                            fontSize: '1.1rem',
                                            outline: 'none',
                                            transition: 'all 0.2s'
                                        }}
                                        onFocus={(e) => {
                                            e.target.style.borderColor = '#3b82f6';
                                            e.target.style.background = '#ffffff';
                                        }}
                                        onBlur={(e) => {
                                            e.target.style.borderColor = '#cbd5e1';
                                            e.target.style.background = '#f8fafc';
                                        }}
                                    />
                                </div>
                            ))}
                        </div>

                        {/* Footer: Toggle Buttons */}
                        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '2.5rem', gap: '1.5rem' }}>
                            <button
                                onClick={() => setViewMode('Dashboard')}
                                style={{
                                    padding: '1rem 3rem',
                                    background: viewMode === 'Dashboard' ? '#3b82f6' : 'white',
                                    border: viewMode === 'Dashboard' ? 'none' : '1px solid #cbd5e1',
                                    borderRadius: '8px',
                                    fontWeight: 600,
                                    fontSize: '1.1rem',
                                    color: viewMode === 'Dashboard' ? 'white' : '#64748b',
                                    cursor: 'pointer',
                                    boxShadow: viewMode === 'Dashboard' ? '0 4px 6px -1px rgba(59, 130, 246, 0.3)' : 'none',
                                    transition: 'all 0.2s'
                                }}
                            >
                                Dashboard
                            </button>
                            <button
                                onClick={() => setViewMode('Details')}
                                style={{
                                    padding: '1rem 3rem',
                                    background: viewMode === 'Details' ? '#3b82f6' : 'white',
                                    border: viewMode === 'Details' ? 'none' : '1px solid #cbd5e1',
                                    borderRadius: '8px',
                                    fontWeight: 600,
                                    fontSize: '1.1rem',
                                    color: viewMode === 'Details' ? 'white' : '#64748b',
                                    cursor: 'pointer',
                                    boxShadow: viewMode === 'Details' ? '0 4px 6px -1px rgba(59, 130, 246, 0.3)' : 'none',
                                    transition: 'all 0.2s'
                                }}
                            >
                                Details
                            </button>
                        </div>
                    </div>
                )}

                {/* SAP-STYLE ACTION TOOLBAR */}
                {isExpanded && (
                    <div style={{
                        background: 'linear-gradient(to right, #1e3a8a, #2563eb)', // Premium Blue Gradient
                        padding: '0.75rem 1.25rem',
                        borderRadius: '12px',
                        marginBottom: '1.5rem',
                        display: 'flex',
                        justifyContent: 'flex-end',
                        gap: '0.75rem',
                        alignItems: 'center',
                        boxShadow: '0 4px 10px -2px rgba(30, 64, 175, 0.4)'
                    }}>
                        {['Maintenance Plan', 'Update Task', 'Application History', 'Create WP', 'Include into WP'].map(label => (
                            <button
                                key={label}
                                style={{
                                    background: 'rgba(255, 255, 255, 0.95)',
                                    color: '#0f172a',
                                    border: 'none',
                                    padding: '0.5rem 1.25rem',
                                    borderRadius: '8px',
                                    fontWeight: '600',
                                    fontSize: '0.85rem',
                                    cursor: 'pointer',
                                    whiteSpace: 'nowrap',
                                    transition: 'transform 0.1s, background 0.2s',
                                    boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                                }}
                                onMouseOver={e => {
                                    e.target.style.transform = 'translateY(-2px)';
                                    e.target.style.background = '#ffffff';
                                }}
                                onMouseOut={e => {
                                    e.target.style.transform = 'translateY(0)';
                                    e.target.style.background = 'rgba(255, 255, 255, 0.95)';
                                }}
                                onClick={() => label === 'Update Task' ? alert('Select a task to update') : console.log(label)}
                            >
                                {label}
                            </button>
                        ))}
                    </div>
                )}

                {/* TOOLBAR (Add button) */}
                {isExpanded && (
                    <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '1rem' }}>
                        <button
                            onClick={handleAddClick}
                            style={{ padding: '0.5rem 1rem', background: 'var(--accent-primary)', border: 'none', borderRadius: '4px', color: 'white', cursor: 'pointer', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.5rem' }}
                        >
                            + New Task
                        </button>
                    </div>
                )}

                {/* ADD NEW ITEM FORM */}
                {isExpanded && isAdding && (
                    <div style={{ padding: '0.75rem', background: 'rgba(34, 197, 94, 0.1)', borderRadius: '6px', border: '1px dashed #22c55e', display: 'flex', gap: '0.5rem', flexDirection: 'column', marginBottom: '1rem' }}>
                        <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                            {renderFormInputs()}
                        </div>
                        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem' }}>
                            <button onClick={() => setIsAdding(false)} style={{ padding: '0.4rem 0.8rem', background: 'transparent', border: '1px solid var(--text-secondary)', borderRadius: '4px', color: 'var(--text-secondary)', cursor: 'pointer' }}>Cancel</button>
                            <button onClick={handleSave} style={{ padding: '0.4rem 0.8rem', background: '#22c55e', border: 'none', borderRadius: '4px', color: 'white', cursor: 'pointer' }}>Save Task</button>
                        </div>
                    </div>
                )}

                {/* LIST / TABLE CONTENT */}
                {viewMode === 'Details' ? (
                    // DETAILS TABLE VIEW
                    <div style={{ flex: 1, padding: '2rem', width: '100%', maxWidth: '100%', background: 'transparent' }}>
                        <div style={{
                            maxHeight: '65vh',
                            maxWidth: '95%',
                            margin: '0 auto',
                            overflow: 'auto',
                            borderRadius: '12px',
                            border: '1px solid var(--border-color)',
                            boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.1)',
                            background: 'var(--bg-secondary)'
                        }}>
                            <div style={{ padding: '1rem', borderBottom: '1px solid var(--border-color)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--bg-secondary)', position: 'sticky', top: 0, zIndex: 20 }}>
                                <div style={{ fontWeight: 700, fontSize: '1.1rem', color: 'var(--text-primary)' }}>Fleet Synthesis - DETAILS ({items.length})</div>
                                <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                                    <span style={{ color: 'var(--text-secondary)', fontSize: '1.2rem' }}>🔍</span>
                                    <input placeholder="Type to filter..." style={{ border: 'none', borderBottom: '1px solid var(--border-color)', padding: '0.25rem', outline: 'none', background: 'transparent', color: 'var(--text-primary)' }} />
                                    <button style={{ marginLeft: '1rem', padding: '0.4rem 1rem', background: 'var(--bg-primary)', border: '1px solid var(--border-color)', borderRadius: '4px', cursor: 'pointer', fontWeight: 600, color: 'var(--text-primary)' }}>Report</button>
                                </div>
                            </div>
                            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: '1500px', fontSize: '0.85rem' }}>
                                <thead style={{ background: 'var(--bg-secondary)', position: 'sticky', top: '60px', zIndex: 10, boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
                                    <tr>
                                        <th style={{ padding: '0.75rem', textAlign: 'center', width: '50px', borderBottom: '1px solid var(--border-color)' }}><input type="checkbox" /></th>
                                        <th style={{ padding: '0.75rem', textAlign: 'center', width: '80px', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Alarm</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>A/C Registration</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Type</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Reference</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Description</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>PN</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>SN</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Category Part</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Threshold</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Interval</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Last Action</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>WO Number</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Remaining</th>
                                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)' }}>Due Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {items.map((item, idx) => (
                                        <tr key={item.id} onClick={() => onNavigate && onNavigate('Fleet Synthesis')} style={{ cursor: 'pointer', borderBottom: '1px solid var(--border-color)', background: idx % 2 === 0 ? 'transparent' : 'rgba(255,255,255,0.02)' }}>
                                            <td style={{ padding: '0.75rem', textAlign: 'center' }}><input type="checkbox" /></td>
                                            <td style={{ padding: '0.75rem', textAlign: 'center' }}>
                                                <div style={{ width: '20px', height: '20px', background: item.status === 'red' ? '#ef4444' : item.status === 'yellow' ? '#eab308' : '#22c55e', borderRadius: '4px', margin: '0 auto' }}></div>
                                            </td>
                                            <td style={{ padding: '0.75rem', color: 'var(--accent-primary)', fontWeight: 600 }}>{item.aircraft}</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>{item.type}</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>AW139 CPI - ADD 1</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={item.description}>{item.description}</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--accent-primary)' }}>DK120</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--accent-primary)' }}>SD{59000 + idx}</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>H/T LLP</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>50:00 Hours</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>6 Months</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>20.06.2025</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>WO-218{10 + idx}</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>1.93 Months</td>
                                            <td style={{ padding: '0.75rem', color: 'var(--text-primary)' }}>{item.due}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                ) : (
                    // DASHBOARD LIST VIEW
                    <>
                        {displayedItems.length === 0 ? (
                            <div style={{ textAlign: 'center', color: 'var(--text-secondary)', padding: '2rem' }}>No tasks found matching your filters.</div>
                        ) : (
                            displayedItems.map(item => (
                                <div key={item.id} onClick={() => onNavigate && onNavigate('Forecast')} style={{
                                    display: 'flex', flexDirection: 'column',
                                    padding: '0.75rem', borderRadius: '6px',
                                    background: 'var(--bg-secondary)',
                                    border: '1px solid rgba(255,255,255,0.05)',
                                    borderLeft: `4px solid ${item.status === 'red' ? '#ef4444' : item.status === 'yellow' ? '#eab308' : '#22c55e'}`,
                                    cursor: 'pointer',
                                    transition: 'background 0.2s',
                                    ':hover': { background: 'rgba(255,255,255,0.05)' }
                                }}>
                                    {editingId === item.id ? (
                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                                            <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                                                {renderFormInputs()}
                                            </div>
                                            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem' }}>
                                                <button onClick={() => setEditingId(null)} style={{ padding: '0.4rem 0.8rem', background: 'transparent', border: '1px solid var(--text-secondary)', borderRadius: '4px', color: 'var(--text-secondary)', cursor: 'pointer' }}>Cancel</button>
                                                <button onClick={handleSave} style={{ padding: '0.4rem 0.8rem', background: '#eab308', border: 'none', borderRadius: '4px', color: 'black', cursor: 'pointer' }}>Update</button>
                                            </div>
                                        </div>
                                    ) : (
                                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                            {/* Left: Info */}
                                            <div style={{ flex: 1 }}>
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', marginBottom: '0.2rem' }}>
                                                    <span style={{ fontWeight: 600, fontSize: '1rem', color: 'white' }}>{item.description}</span>
                                                    {item.status === 'red' && <span style={{ fontSize: '0.7rem', background: '#ef4444', color: 'white', padding: '2px 6px', borderRadius: '4px' }}>CRITICAL</span>}
                                                </div>
                                                <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
                                                    <span style={{ color: 'var(--accent-primary)', fontWeight: 'bold' }}>[{item.aircraft}]</span> Due: {item.due} <span style={{ opacity: 0.5 }}>| {item.type}</span>
                                                </div>
                                            </div>

                                            {/* Right: Actions */}
                                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                                {isExpanded ? (
                                                    <>
                                                        <button onClick={() => handleEditClick(item)} style={{ padding: '0.5rem 1rem', background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '4px', color: 'var(--text-secondary)', cursor: 'pointer' }}>Edit</button>
                                                        <button
                                                            onClick={() => handleDelete(item.id)}
                                                            style={{ padding: '0.5rem 1rem', background: 'rgba(239, 68, 68, 0.2)', border: 'none', borderRadius: '4px', color: '#ef4444', cursor: 'pointer' }}
                                                        >
                                                            Delete
                                                        </button>
                                                    </>
                                                ) : (
                                                    <span style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', fontStyle: 'italic' }}>
                                                        {item.status === 'red' ? 'Action Required' : 'Upcoming'}
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    )}
                                </div>
                            ))
                        )}
                    </>
                )}

                {/* View All Button */}
                {!isExpanded && items.length > 5 && viewMode !== 'Details' && (
                    <div style={{ textAlign: 'center', marginTop: '0.5rem', borderTop: '1px solid var(--border-color)', paddingTop: '0.5rem' }}>
                        <button
                            onClick={handleExpandToggle}
                            style={{ background: 'none', border: 'none', color: 'var(--accent-primary)', cursor: 'pointer', fontSize: '0.9rem' }}
                        >
                            View All ({items.length}) Items
                        </button>
                    </div>
                )}
            </div>
        </WidgetContainer>
    );
};

export default ForecastWidget;
