import React, { useState, useEffect, useMemo } from 'react';
import WidgetContainer from './WidgetContainer';
import styles from './WidgetStyles.module.css';
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from 'recharts';
import { AIRCRAFT_FLEET, INITIAL_TASKS } from '../../data/mockFleetData';

const STATUS_COLORS = {
    'In Service': '#4ade80',  // Green
    'Maintenance': '#f59e0b', // Amber
    'Grounded': '#ef4444'     // Red
};

const FleetWidget = ({ onExpand, onNavigate }) => {
    // Merge fleet data with derived status from tasks
    // If any task is 'red', status is Grounded. If 'yellow', Maintenance. Else In Service.
    // However, existing data has 'status' field. Let's respect the task data to override if needed or just use the fleet data status as source of truth initially, 
    // but calculating it makes it "functional".

    // Let's create a derived state.
    const [fleetData, setFleetData] = useState([]);
    const [activeIds, setActiveIds] = useState([]);
    const [isEditing, setIsEditing] = useState(false);
    const [isAdding, setIsAdding] = useState(false);
    const [newAircraft, setNewAircraft] = useState({ id: '', type: '', hours: '', cycles: '', status: 'In Service' });

    useEffect(() => {
        // Initialize fleet data merging with task status
        const enrichedFleet = AIRCRAFT_FLEET.map(ac => {
            const acTasks = INITIAL_TASKS.filter(t => t.reg === ac.id);
            const hasCritical = acTasks.some(t => t.status === 'red');
            const hasWarning = acTasks.some(t => t.status === 'yellow');

            let calculatedStatus = 'In Service';
            if (hasCritical) calculatedStatus = 'Grounded';
            else if (hasWarning) calculatedStatus = 'Maintenance';

            // Prefer calculated status to ensure sync with Synthesis
            return { ...ac, status: calculatedStatus };
        });
        setFleetData(enrichedFleet);
        setActiveIds(enrichedFleet.map(f => f.id));
    }, []);

    // Filter Logic
    const displayedFleet = fleetData.filter(f => activeIds.includes(f.id));

    // Prepare Data for Chart
    const statusCounts = displayedFleet.reduce((acc, curr) => {
        acc[curr.status] = (acc[curr.status] || 0) + 1;
        return acc;
    }, {});

    const chartData = Object.keys(statusCounts).map(status => ({
        name: status,
        value: statusCounts[status]
    }));

    // Simulated Telemetry (Real-Time Data)
    useEffect(() => {
        const interval = setInterval(() => {
            setFleetData(currentFleet =>
                currentFleet.map(ac => {
                    if (ac.status === 'In Service') {
                        // Increment flight hours slightly (0.1 every tick) for active aircraft
                        return { ...ac, hours: parseFloat((ac.hours + 0.1).toFixed(1)) };
                    }
                    return ac;
                })
            );
        }, 5000); // Update every 5 seconds

        return () => clearInterval(interval);
    }, []);

    const toggleAircraft = (id) => {
        if (activeIds.includes(id)) {
            setActiveIds(activeIds.filter(aid => aid !== id));
        } else {
            setActiveIds([...activeIds, id]);
        }
    };

    const handleAdd = () => {
        setIsAdding(true);
        setIsEditing(false);
    };

    const saveNewAircraft = () => {
        if (!newAircraft.id || !newAircraft.type) return;
        const ac = { ...newAircraft, hours: Number(newAircraft.hours), cycles: Number(newAircraft.cycles) };
        setFleetData([...fleetData, ac]);
        setActiveIds([...activeIds, ac.id]);
        setNewAircraft({ id: '', type: '', hours: '', cycles: '', status: 'In Service' });
        setIsAdding(false);
    };

    // Check if we are in "Widget Mode" (Summary) or "Expanded Mode" (Detail)
    const showChart = !onExpand && !isEditing;

    return (
        <WidgetContainer
            title="Fleet Status"
            onEdit={() => setIsEditing(!isEditing)}
            onAdd={handleAdd}
            onExpand={onExpand}
        >
            {isAdding && (
                <div className={styles.addItemForm}>
                    <input
                        placeholder="Tail Number (e.g. 9M-WSE)"
                        value={newAircraft.id}
                        onChange={e => setNewAircraft({ ...newAircraft, id: e.target.value })}
                        style={{ marginBottom: '0.5rem', width: '100%', padding: '0.5rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                    />
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.5rem', marginBottom: '0.5rem' }}>
                        <input
                            placeholder="Type (e.g. AW139)"
                            value={newAircraft.type}
                            onChange={e => setNewAircraft({ ...newAircraft, type: e.target.value })}
                            style={{ padding: '0.5rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                        />
                        <select
                            value={newAircraft.status}
                            onChange={e => setNewAircraft({ ...newAircraft, status: e.target.value })}
                            style={{ padding: '0.5rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                        >
                            <option>In Service</option>
                            <option>Maintenance</option>
                            <option>Grounded</option>
                        </select>
                    </div>
                    <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '0.5rem' }}>
                        <input
                            placeholder="Hours"
                            type="number"
                            value={newAircraft.hours}
                            onChange={e => setNewAircraft({ ...newAircraft, hours: e.target.value })}
                            style={{ flex: 1, padding: '0.5rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                        />
                        <input
                            placeholder="Cycles"
                            type="number"
                            value={newAircraft.cycles}
                            onChange={e => setNewAircraft({ ...newAircraft, cycles: e.target.value })}
                            style={{ flex: 1, padding: '0.5rem', borderRadius: '4px', border: '1px solid var(--border-color)', background: 'var(--bg-primary)', color: 'white' }}
                        />
                    </div>
                    <div className={styles.formActions}>
                        <button onClick={saveNewAircraft} className={styles.saveBtn}>Save</button>
                        <button onClick={() => setIsAdding(false)} className={styles.cancelBtn}>Cancel</button>
                    </div>
                </div>
            )}

            {isEditing ? (
                <div className={styles.editModeOverlay}>
                    <h4>Manage Active Fleet</h4>
                    <div className={styles.checklist}>
                        {fleetData.map(ac => (
                            <label key={ac.id} className={styles.checkItem}>
                                <input
                                    type="checkbox"
                                    checked={activeIds.includes(ac.id)}
                                    onChange={() => toggleAircraft(ac.id)}
                                />
                                <span>{ac.id} ({ac.type})</span>
                            </label>
                        ))}
                    </div>
                    <button onClick={() => setIsEditing(false)} className={styles.doneBtn}>Done</button>
                </div>
            ) : showChart ? (
                <div style={{ width: '100%', height: '100%', minHeight: '150px' }}>
                    <ResponsiveContainer width="100%" height="100%">
                        <PieChart>
                            <Pie
                                data={chartData}
                                cx="50%"
                                cy="50%"
                                innerRadius={40}
                                outerRadius={60}
                                paddingAngle={5}
                                dataKey="value"
                            >
                                {chartData.map((entry, index) => (
                                    <Cell key={`cell-${index}`} fill={STATUS_COLORS[entry.name]} />
                                ))}
                            </Pie>
                            <Tooltip
                                contentStyle={{ backgroundColor: 'var(--bg-secondary)', border: 'none', borderRadius: '8px' }}
                                itemStyle={{ color: 'var(--text-primary)' }}
                            />
                            <Legend
                                verticalAlign="bottom"
                                height={36}
                                iconType="circle"
                                wrapperStyle={{ fontSize: '0.8rem', color: 'var(--text-secondary)' }}
                            />
                        </PieChart>
                    </ResponsiveContainer>
                </div>
            ) : (
                <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                    {/* Header */}
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: '1.5fr 1fr 1fr',
                        padding: '0.5rem 0.5rem',
                        borderBottom: '1px solid rgba(255,255,255,0.1)',
                        fontWeight: '700',
                        fontSize: '0.8rem',
                        color: 'var(--text-secondary)',
                        textAlign: 'center'
                    }}>
                        <div style={{ textAlign: 'left' }}>A/C</div>
                        <div>H</div>
                        <div>C</div>
                    </div>

                    {/* Table Body */}
                    <div className={styles.list} style={{ padding: '0 0.5rem' }}>
                        {displayedFleet.map(ac => (
                            <div key={ac.id} onClick={() => onNavigate && onNavigate('Aircraft Details')} style={{
                                display: 'grid',
                                gridTemplateColumns: '1.5fr 1fr 1fr',
                                padding: '0.75rem 0',
                                borderBottom: '1px solid rgba(255,255,255,0.05)',
                                alignItems: 'center',
                                fontSize: '0.9rem',
                                color: 'white',
                                textAlign: 'center',
                                cursor: 'pointer',
                                transition: 'background 0.2s',
                                ':hover': { background: 'rgba(255,255,255,0.05)' }
                            }}>
                                <div style={{ textAlign: 'left', fontWeight: 600, display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                                    {ac.id}
                                    <span style={{
                                        width: '6px',
                                        height: '6px',
                                        borderRadius: '50%',
                                        backgroundColor: STATUS_COLORS[ac.status] || '#999',
                                        boxShadow: ac.status === 'In Service' ? '0 0 5px #4ade80' : 'none'
                                    }} title={ac.status} />
                                </div>
                                <div style={{ fontFamily: 'monospace', color: ac.status === 'In Service' ? '#38bdf8' : 'inherit' }}>
                                    {ac.hours?.toFixed(1)}
                                </div>
                                <div style={{ fontFamily: 'monospace', color: 'var(--text-secondary)' }}>
                                    {ac.cycles}
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </WidgetContainer>
    );
};

export default FleetWidget;
