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

// --- COMPONENT: Status Cell ---
const StatusCell = ({ data, onClick }) => {
    if (!data) return <div style={{ minWidth: '80px' }}></div>;

    const getColor = (s) => {
        switch (s) {
            case 'red': return '#ef4444';
            case 'yellow': return '#eab308';
            case 'green': return '#22c55e';
            default: return 'var(--bg-primary)';
        }
    };

    return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', minWidth: '80px', justifyContent: 'center' }}>
            <div
                onClick={onClick}
                style={{
                    backgroundColor: getColor(data.status),
                    color: '#000',
                    fontWeight: 'bold',
                    width: '32px',
                    height: '32px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: 'pointer',
                    borderRadius: '4px',
                    boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
                    fontSize: '0.9rem',
                    transition: 'transform 0.1s',
                    opacity: data.total === 0 ? 0.3 : 1
                }}
                onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.1)'}
                onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}
            >
                {data.alert}
            </div>
            <span style={{ color: 'var(--text-secondary)', fontSize: '0.9rem', width: '24px', textAlign: 'left' }}>{data.total}</span>
        </div>
    );
};

// --- COMPONENT: Drill Down Modal (CRUD) ---
const DrillDownModal = ({ isOpen, onClose, title, tasks, onAdd, onEdit, onDelete, context }) => {
    if (!isOpen) return null;

    const [isAdding, setIsAdding] = useState(false);
    const [newItem, setNewItem] = useState({ description: '', status: 'green', date: '' });
    const [editItemId, setEditItemId] = useState(null);

    const handleSave = () => {
        if (newItem.description) {
            onAdd({ ...newItem, ...context });
            setNewItem({ description: '', status: 'green', date: '' });
            setIsAdding(false);
        }
    };

    const handleUpdate = (id) => {
        onEdit(id, newItem);
        setEditItemId(null);
        setNewItem({ description: '', status: 'green', date: '' });
    };

    const startEdit = (task) => {
        setEditItemId(task.id);
        setNewItem({ description: task.description, status: task.status, date: task.date });
    };

    return (
        <div style={{
            position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
            backgroundColor: 'rgba(0,0,0,0.85)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000
        }}>
            <div style={{
                backgroundColor: 'var(--bg-secondary)', padding: '2rem', borderRadius: '12px',
                border: '1px solid var(--border-color)', width: '600px', maxHeight: '80vh', display: 'flex', flexDirection: 'column'
            }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
                    <h3 style={{ margin: 0, color: 'var(--text-primary)', fontSize: '1.2rem' }}>{title}</h3>
                    <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-secondary)', cursor: 'pointer', fontSize: '1.5rem' }}>&times;</button>
                </div>

                {/* List of Tasks */}
                <div style={{ flex: 1, overflowY: 'auto', marginBottom: '1.5rem', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
                    {tasks.length === 0 && !isAdding && (
                        <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)', fontStyle: 'italic' }}>
                            No tasks found for this category.
                        </div>
                    )}

                    {tasks.map(task => (
                        <div key={task.id} style={{
                            padding: '1rem', background: 'rgba(255,255,255,0.03)', borderRadius: '6px',
                            borderLeft: `4px solid ${task.status === 'red' ? '#ef4444' : task.status === 'yellow' ? '#eab308' : '#22c55e'}`,
                            display: 'flex', justifyContent: 'space-between', alignItems: 'center'
                        }}>
                            {editItemId === task.id ? (
                                <div style={{ flex: 1, display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                                    <input
                                        autoFocus
                                        value={newItem.description}
                                        onChange={e => setNewItem({ ...newItem, description: e.target.value })}
                                        style={{ flex: 1, padding: '0.4rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                                    />
                                    <select
                                        value={newItem.status}
                                        onChange={e => setNewItem({ ...newItem, status: e.target.value })}
                                        style={{ padding: '0.4rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                                    >
                                        <option value="green">Safe</option>
                                        <option value="yellow">Warning</option>
                                        <option value="red">Critical</option>
                                    </select>
                                    <button onClick={() => handleUpdate(task.id)} style={{ padding: '0.4rem', background: '#22c55e', border: 'none', borderRadius: '4px', cursor: 'pointer', color: 'black' }}>Save</button>
                                    <button onClick={() => setEditItemId(null)} style={{ padding: '0.4rem', background: 'gray', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>Cancel</button>
                                </div>
                            ) : (
                                <>
                                    <div style={{ flex: 1 }}>
                                        <div style={{ fontWeight: 500, color: 'var(--text-primary)' }}>{task.description}</div>
                                        <div style={{ fontSize: '0.8rem', color: 'var(--text-secondary)', marginTop: '0.2rem', display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                            <span style={{ color: 'var(--accent-primary)' }}>[{task.reg}]</span>
                                            Due: {task.date || 'N/A'}
                                        </div>
                                    </div>
                                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                                        <button onClick={() => startEdit(task)} style={{ padding: '0.4rem 0.8rem', background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '4px', color: 'var(--text-primary)', cursor: 'pointer' }}>Edit</button>
                                        <button onClick={() => onDelete(task.id)} style={{ padding: '0.4rem 0.8rem', background: 'rgba(239, 68, 68, 0.2)', border: 'none', borderRadius: '4px', color: '#ef4444', cursor: 'pointer' }}>Delete</button>
                                    </div>
                                </>
                            )}
                        </div>
                    ))}

                    {/* Add Item Form */}
                    {isAdding && (
                        <div style={{ padding: '1rem', background: 'rgba(255,255,255,0.05)', borderRadius: '6px', border: '1px dashed var(--border-color)' }}>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.8rem' }}>
                                <input
                                    placeholder="Task Description"
                                    value={newItem.description}
                                    onChange={e => setNewItem({ ...newItem, description: e.target.value })}
                                    style={{ padding: '0.6rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                                />
                                <div style={{ display: 'flex', gap: '1rem' }}>
                                    <select
                                        value={newItem.status}
                                        onChange={e => setNewItem({ ...newItem, status: e.target.value })}
                                        style={{ flex: 1, padding: '0.6rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', 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={newItem.date}
                                        onChange={e => setNewItem({ ...newItem, date: e.target.value })}
                                        style={{ flex: 1, padding: '0.6rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                                    />
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem', marginTop: '0.5rem' }}>
                                    <button onClick={() => setIsAdding(false)} style={{ padding: '0.5rem 1rem', background: 'transparent', border: '1px solid var(--text-secondary)', borderRadius: '4px', color: 'var(--text-secondary)', cursor: 'pointer' }}>Cancel</button>
                                    <button onClick={handleSave} style={{ padding: '0.5rem 1rem', background: 'var(--accent-primary)', border: 'none', borderRadius: '4px', color: 'white', cursor: 'pointer' }}>Save Item</button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>

                {!isAdding && context.reg !== 'All' && (
                    <button
                        onClick={() => setIsAdding(true)}
                        style={{
                            width: '100%', padding: '0.8rem', background: 'var(--accent-primary)', border: 'none',
                            borderRadius: '6px', color: 'white', cursor: 'pointer', fontWeight: 600,
                            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem'
                        }}
                    >
                        <span>+</span> Add New Task
                    </button>
                )}
                {context.reg === 'All' && (
                    <div style={{ textAlign: 'center', color: 'var(--text-secondary)', fontSize: '0.8rem' }}>
                        * Navigate to specific aircraft to add tasks.
                    </div>
                )}
            </div>
        </div>
    );
};

const FleetSynthesis = () => {
    const [tasks, setTasks] = useState(INITIAL_TASKS);
    const [modalData, setModalData] = useState({ isOpen: false, reg: null, category: null, type: null });
    const [viewMode, setViewMode] = useState('Filters'); // 'Filters', 'Dashboard', 'Details'
    const [filters, setFilters] = useState({
        aircraft: '',
        status: 'Applicable',
        remainingHours: '',
        remainingCycles: '',
        remainingMonths: ''
    });

    // Matrix Calculation Logic
    const matrixData = useMemo(() => {
        // Init rows using imported AIRCRAFT_LIST (renamed to AIRCRAFT_FLEET in mock data)
        const rows = AIRCRAFT_FLEET.map(ac => ({
            ...ac,
            reg: ac.id, // Map 'id' (9M-WAD) to 'reg' for compatibility with existing logic
            allSchedules: { alert: 0, total: 0, status: 'green' },
            details: {}
        }));
        const allRow = { registration: 'All', type: '', sn: '', allSchedules: { alert: 0, total: 0, status: 'green' }, details: {} };

        // Process Task
        const processTask = (task, row) => {
            if (!row.details[task.category]) {
                row.details[task.category] = { alert: 0, total: 0, status: 'green' };
            }

            row.details[task.category].total += 1;
            row.allSchedules.total += 1;

            if (task.status === 'red' || task.status === 'yellow') {
                row.details[task.category].alert += 1;
                row.allSchedules.alert += 1;
            }

            // Status Priority
            const updateStatus = (current, newStatus) => {
                if (current === 'red') return 'red';
                if (newStatus === 'red') return 'red';
                if (current === 'yellow') return 'yellow';
                if (newStatus === 'yellow') return 'yellow';
                return 'green';
            };

            row.details[task.category].status = updateStatus(row.details[task.category].status, task.status);
            row.allSchedules.status = updateStatus(row.allSchedules.status, task.status);
        };

        tasks.forEach(task => {
            // Find row by registration. In FleetWidget we used 'id' as 'reg'.
            const row = rows.find(r => r.reg === task.reg);
            if (row) processTask(task, row);
            processTask(task, allRow); // Add to aggregate
        });

        // Fill empty categories
        [allRow, ...rows].forEach(row => {
            CATEGORIES.forEach(cat => {
                if (!row.details[cat]) row.details[cat] = { alert: 0, total: 0, status: 'none' };
            });
        });

        return [allRow, ...rows];
    }, [tasks]);

    // Modal Handlers
    const handleCellClick = (reg, category, type) => {
        setModalData({ isOpen: true, reg, category, type });
    };

    const handleAddTask = (newTask) => {
        setTasks([...tasks, { id: Date.now(), ...newTask }]);
    };

    const handleEditTask = (id, updatedFields) => {
        setTasks(tasks.map(t => t.id === id ? { ...t, ...updatedFields } : t));
    };

    const handleDeleteTask = (id) => {
        setTasks(tasks.filter(t => t.id !== id));
    };

    // Filter tasks
    const modalTasks = tasks.filter(t => {
        const matchCategory = modalData.category === 'All Schedules' ? true : t.category === modalData.category;
        const matchReg = modalData.reg === 'All' ? true : t.reg === modalData.reg;
        return matchCategory && matchReg;
    });

    const modalTitle = modalData.reg === 'All'
        ? `Fleet Overview: ${modalData.category}`
        : `${modalData.reg} - ${modalData.category}`;

    // --- RENDER HELPERS ---

    // Helper for Action Toolbar
    const renderActionToolbar = () => (
        <div style={{
            background: 'linear-gradient(to right, #1e3a8a, #2563eb)', // Premium Blue Gradient
            padding: '0.75rem 1.25rem',
            borderRadius: '12px',
            marginBottom: '1rem',
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '0.75rem',
            alignItems: 'center',
            boxShadow: '0 4px 10px -2px rgba(30, 64, 175, 0.4)',
            width: '100%',
            boxSizing: 'border-box'
        }}>
            {['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')}
                >
                    {label}
                </button>
            ))}
        </div>
    );

    // 1. FILTERS VIEW (Default)
    const renderFiltersView = () => (
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '1.5rem', background: '#f8fafc' }}>
            {/* Action Center Filters */}
            <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' }}>Fleet Synthesis 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'}
                    >
                        <option value="">Select Aircraft...</option>
                        {AIRCRAFT_FLEET.map(ac => <option key={ac.id} value={ac.id}>{ac.id}</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="Applicable">Applicable</option>
                            <option value="Critical">Critical</option>
                            <option value="Warning">Warning</option>
                            <option value="green">Safe</option>
                        </select>
                    </div>

                    {['Remaining Hours', 'Remaining Cycles', 'Remaining Months'].map((label) => (
                        <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 buttons integrated into the filter card */}
                <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 */}
            {renderActionToolbar()}
        </div>
    );

    // 2. DASHBOARD VIEW (Matrix)
    const renderDashboardView = () => (
        <div style={{ padding: '1rem', overflow: 'auto', height: '100%', position: 'relative' }}>
            <button
                onClick={() => setViewMode('Filters')}
                style={{
                    position: 'absolute',
                    top: '0.5rem',
                    right: '1rem',
                    background: 'var(--bg-secondary)',
                    border: '1px solid var(--border-color)',
                    color: 'var(--text-secondary)',
                    padding: '0.3rem 0.8rem',
                    borderRadius: '4px',
                    cursor: 'pointer',
                    zIndex: 10,
                    fontSize: '0.8rem',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.4rem'
                }}
            >
                ← Back to Filters
            </button>

            {/* Matrix Table */}
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '1rem', minWidth: '1000px', marginTop: '1.5rem' }}>
                <thead>
                    <tr>
                        <th rowSpan="2" style={{ textAlign: 'left', padding: '1.25rem', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)', fontSize: '1rem' }}>A/C Type</th>
                        <th rowSpan="2" style={{ textAlign: 'left', padding: '1.25rem', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)', fontSize: '1rem' }}>A/C SN</th>
                        <th rowSpan="2" style={{ textAlign: 'left', padding: '1.25rem', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)', fontSize: '1rem' }}>A/C Registration</th>
                        <th rowSpan="2" style={{ textAlign: 'center', padding: '1.25rem', borderBottom: '1px solid var(--border-color)', borderRight: '1px solid var(--border-color)', color: 'var(--text-primary)', backgroundColor: 'var(--bg-secondary)', fontSize: '1rem' }}>All Schedules</th>
                        <th colSpan="7" style={{ textAlign: 'center', padding: '0.75rem', borderBottom: '1px solid var(--border-color)', backgroundColor: 'var(--bg-secondary)', color: 'var(--text-primary)', fontSize: '1rem' }}>Schedules Details</th>
                    </tr>
                    <tr>
                        {CATEGORIES.map(header => (
                            <th key={header} style={{ padding: '0.75rem', borderBottom: '1px solid var(--border-color)', color: 'var(--text-secondary)', fontSize: '0.9rem' }}>{header}</th>
                        ))}
                    </tr>
                </thead>
                <tbody>
                    {matrixData.map((row, index) => (
                        <tr key={index} style={{
                            borderBottom: '1px solid var(--border-color)',
                            backgroundColor: row.registration === 'All' ? 'rgba(255,255,255,0.04)' : 'transparent',
                            fontWeight: row.registration === 'All' ? 'bold' : 'normal'
                        }}>
                            <td style={{ padding: '1rem', color: 'var(--text-secondary)' }}>{row.type}</td>
                            <td style={{ padding: '1rem', color: 'var(--text-secondary)' }}>{row.sn}</td>
                            <td style={{ padding: '1rem', color: 'var(--accent-primary)' }}>{row.registration || row.reg}</td>

                            {/* All Schedules Column */}
                            <td style={{ padding: '0.5rem', borderRight: '1px solid var(--border-color)', backgroundColor: 'rgba(255,255,255,0.01)' }}>
                                <div style={{ display: 'flex', justifyContent: 'center' }}>
                                    <StatusCell
                                        data={row.allSchedules}
                                        onClick={() => handleCellClick(row.registration || row.reg, 'All Schedules', row.type)}
                                    />
                                </div>
                            </td>

                            {/* Details Columns */}
                            {CATEGORIES.map(cat => (
                                <td key={cat} style={{ padding: '0.5rem' }}>
                                    <StatusCell
                                        data={row.details[cat]}
                                        onClick={() => handleCellClick(row.registration || row.reg, cat, row.type)}
                                    />
                                </td>
                            ))}
                        </tr>
                    ))}
                </tbody>
            </table>

            {/* Legend */}
            <div style={{ marginTop: '2rem', fontSize: '1rem', color: 'var(--text-secondary)', display: 'flex', gap: '2rem' }}>
                <span><strong>Legend:</strong></span>
                <span style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}><div style={{ width: '16px', height: '16px', background: '#ef4444', borderRadius: '2px' }}></div> Critical / Overdue</span>
                <span style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}><div style={{ width: '16px', height: '16px', background: '#eab308', borderRadius: '2px' }}></div> Warning / Due Soon</span>
                <span style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}><div style={{ width: '16px', height: '16px', background: '#22c55e', borderRadius: '2px' }}></div> Safe</span>
            </div>
        </div>
    );

    // 3. DETAILS VIEW (List -> Table)
    const renderDetailsView = () => (
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'transparent' }}>
            <div style={{ flex: 1, width: '100%', background: 'transparent', display: 'grid', placeItems: 'center' }}>
                <div style={{ display: 'flex', flexDirection: 'column', width: '96%', margin: '0 auto', gap: '1rem' }}>
                    {renderActionToolbar()}
                    <div style={{
                        maxHeight: '50vh',
                        width: '100%',
                        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={{ height: '60px', padding: '0 1rem', borderBottom: '1px solid var(--border-color)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--bg-secondary)', position: 'sticky', top: 0, zIndex: 20, boxSizing: 'border-box' }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                                <button
                                    onClick={() => setViewMode('Filters')}
                                    style={{
                                        background: 'transparent',
                                        border: '1px solid var(--border-color)',
                                        padding: '0.3rem 0.6rem',
                                        borderRadius: '4px',
                                        cursor: 'pointer',
                                        color: 'var(--text-secondary)',
                                        display: 'flex', alignItems: 'center', gap: '0.4rem', fontSize: '0.85rem'
                                    }}
                                >
                                    ← Back
                                </button>
                                <div style={{ fontWeight: 700, fontSize: '1.1rem', color: 'var(--text-primary)' }}>Fleet Synthesis - DETAILS ({tasks.length})</div>
                            </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: '1800px', background: 'transparent' }}>
                            <thead>
                                <tr style={{ borderBottom: '1px solid var(--border-color)' }}>
                                    <th style={{ padding: '0.75rem', textAlign: 'center', width: '60px', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}><input type="checkbox" /></th>
                                    <th style={{ padding: '0.75rem', textAlign: 'center', width: '80px', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Alarm</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>A/C Registration</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Type</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Reference</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Description</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>PN</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>SN</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Category Part</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Threshold</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Interval</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Last Action</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>WO Number</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Remaining</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'left', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', background: 'var(--bg-secondary)', zIndex: 10 }}>Due Date</th>
                                    <th style={{ padding: '0.75rem', textAlign: 'center', width: '150px', minWidth: '150px', fontWeight: 700, fontSize: '0.85rem', color: 'var(--text-secondary)', position: 'sticky', top: '60px', right: 0, background: 'var(--bg-secondary)', zIndex: 30, boxShadow: '-2px 0 5px rgba(0,0,0,0.1)' }}>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {tasks.map((task, idx) => (
                                    <tr key={task.id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)', 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: task.status === 'red' ? '#ef4444' : task.status === 'yellow' ? '#eab308' : '#22c55e',
                                                borderRadius: '4px',
                                                margin: '0 auto'
                                            }}></div>
                                        </td>
                                        <td style={{ padding: '0.75rem', color: 'var(--accent-primary)', fontWeight: 600, fontSize: '0.85rem' }}>{task.reg}</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>{task.category === 'Checks' ? 'Checks' : 'OOP'}</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>AW139 CPI - ADD 1</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: '0.85rem' }} title={task.description}>{task.description}</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--accent-primary)', fontSize: '0.85rem' }}>DK120</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--accent-primary)', fontSize: '0.85rem' }}>SD{59000 + idx}</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>H/T LLP</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>50:00 Hours</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>6 Months</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>20.06.2025</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>WO-218{10 + idx}</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>1.93 Months</td>
                                        <td style={{ padding: '0.75rem', color: 'var(--text-primary)', fontSize: '0.85rem' }}>{task.date}</td>
                                        <td style={{ padding: '0.75rem', textAlign: 'center', width: '150px', minWidth: '150px', position: 'sticky', right: 0, background: idx % 2 === 0 ? 'var(--bg-primary)' : 'var(--bg-secondary)', zIndex: 15, boxShadow: '-2px 0 5px rgba(0,0,0,0.1)' }}>
                                            <div style={{ display: 'flex', gap: '0.5rem', justifyContent: 'center' }}>
                                                <button
                                                    onClick={() => handleCellClick(task.reg, task.category, 'Manual')}
                                                    style={{ padding: '0.4rem 0.8rem', background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '4px', color: 'var(--text-primary)', cursor: 'pointer', fontSize: '0.8rem' }}
                                                >
                                                    Edit
                                                </button>
                                                <button
                                                    onClick={() => handleDeleteTask(task.id)}
                                                    style={{ padding: '0.4rem 0.8rem', background: 'rgba(239, 68, 68, 0.2)', border: 'none', borderRadius: '4px', color: '#ef4444', cursor: 'pointer', fontSize: '0.8rem' }}
                                                >
                                                    Delete
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div >
    );

    return (
        <WidgetContainer title="Fleet Synthesis">
            {viewMode === 'Filters' && renderFiltersView()}
            {viewMode === 'Dashboard' && renderDashboardView()}
            {viewMode === 'Details' && renderDetailsView()}

            <DrillDownModal
                isOpen={modalData.isOpen}
                onClose={() => setModalData({ ...modalData, isOpen: false })}
                title={modalTitle}
                context={{ reg: modalData.reg, category: modalData.category, type: modalData.type }}
                tasks={modalTasks}
                onAdd={handleAddTask}
                onEdit={handleEditTask}
                onDelete={handleDeleteTask}
            />
        </WidgetContainer>
    );
};

export default FleetSynthesis;
