
import React, { useState } from 'react';
import WidgetContainer from './WidgetContainer';
import styles from './WidgetStyles.module.css';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts';

const ALL_WOS = [
    { id: 'WO-2026-003', title: 'Avionics System Check', status: 'Completed', aircraft: '9M-DEF', assigned: 'Kumar A/L Raju', due: '8/1/2026', priority: 'Low' },
    { id: 'WO-2026-004', title: 'APU Maintenance', status: 'On Hold', aircraft: '9M-ABC', assigned: 'Lee Chong Wei', due: '20/1/2026', priority: 'Medium' },
    { id: 'WO-2026-005', title: 'Landing Gear Service', status: 'Open', aircraft: '9M-WSA', assigned: 'Siti Aminah', due: '25/1/2026', priority: 'High' },
    { id: 'WO-2026-006', title: 'Hydraulic Leak', status: 'Open', aircraft: '9M-WSA', assigned: 'Unassigned', due: '28/1/2026', priority: 'High' },
    { id: 'WO-2026-007', title: 'Weekly Inspection', status: 'In Progress', aircraft: '9M-WSB', assigned: 'Ahmad Faiz', due: '30/1/2026', priority: 'Low' },
];

const STATUS_COLORS = {
    'Open': '#38bdf8',       // Blue
    'In Progress': '#f59e0b',// Amber
    'Completed': '#4ade80',  // Green
    'On Hold': '#94a3b8'     // Grey
};

const WorkOrderWidget = ({ onExpand, onNavigate }) => {
    const [orders, setOrders] = useState(ALL_WOS);
    const [pinnedIds, setPinnedIds] = useState([]); // User selected items to replace totals
    const [isEditing, setIsEditing] = useState(false);

    // If onExpand is NOT provided, we assume we are in the "Full View" (Expanded state),
    // so we show the full list by default.
    const isExpandedView = !onExpand;

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

    const chartData = [
        { name: 'Open', count: statusCounts['Open'] || 0 },
        { name: 'In Progress', count: statusCounts['In Progress'] || 0 },
        { name: 'Hold', count: statusCounts['On Hold'] || 0 },
        { name: 'Done', count: statusCounts['Completed'] || 0 },
    ];

    const togglePin = (id) => {
        if (pinnedIds.includes(id)) {
            setPinnedIds(pinnedIds.filter(pid => pid !== id));
        } else {
            setPinnedIds([...pinnedIds, id]);
        }
    };

    // Render a Single List Item (Reusable)
    const renderListItem = (wo) => (
        <div key={wo.id} onClick={() => onNavigate && onNavigate('Work Orders')} style={{
            backgroundColor: 'rgba(255,255,255,0.03)',
            borderRadius: '8px',
            padding: '1rem',
            marginBottom: '0.75rem',
            border: '1px solid rgba(255,255,255,0.05)',
            display: 'flex',
            gap: '1rem',
            alignItems: 'flex-start',
            cursor: 'pointer',
            transition: 'background 0.2s',
            ':hover': { backgroundColor: 'rgba(255,255,255,0.08)' }
        }}>
            {/* Icon */}
            <div style={{ marginTop: '0.2rem', color: wo.status === 'Completed' ? '#4ade80' : '#f59e0b' }}>
                {wo.status === 'Completed' ? (
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <polyline points="20 6 9 17 4 12"></polyline>
                    </svg>
                ) : (
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line>
                    </svg>
                )}
            </div>

            {/* Content */}
            <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem' }}>
                    <span style={{ fontWeight: 700, color: 'white', letterSpacing: '0.02em', fontSize: '0.9rem' }}>{wo.id}</span>
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        {wo.priority && (
                            <span style={{
                                fontSize: '0.7rem', padding: '0.15rem 0.5rem', borderRadius: '10px',
                                backgroundColor: 'rgba(255,255,255,0.1)', color: 'white', fontWeight: 500
                            }}>{wo.priority}</span>
                        )}
                        <span style={{
                            fontSize: '0.7rem', padding: '0.15rem 0.5rem', borderRadius: '10px',
                            backgroundColor: wo.status === 'Completed' ? 'rgba(34, 197, 94, 0.2)' : 'rgba(56, 189, 248, 0.2)',
                            color: wo.status === 'Completed' ? '#4ade80' : '#38bdf8', fontWeight: 600
                        }}>{wo.status}</span>
                    </div>
                </div>
                <div style={{ fontSize: '0.95rem', fontWeight: 600, color: 'var(--text-primary)', marginBottom: '0.2rem' }}>
                    {wo.aircraft}
                </div>
                <div style={{ fontSize: '0.85rem', color: 'var(--text-secondary)' }}>
                    {wo.title}
                </div>
            </div>
        </div>
    );

    // Determine what to display based on state
    const showFullList = isExpandedView;
    const showPinnedList = !isExpandedView && pinnedIds.length > 0;
    const showChart = !isExpandedView && pinnedIds.length === 0;

    return (
        <WidgetContainer
            title={isExpandedView ? "All Work Orders" : showPinnedList ? "Pinned Orders" : "Work Orders"}
            onEdit={!isExpandedView ? () => setIsEditing(!isEditing) : undefined}
            onExpand={onExpand}
        >
            {isEditing ? (
                <div className={styles.editModeOverlay}>
                    <h4>Select Orders to Pin on Widget</h4>
                    <p style={{ fontSize: '0.8rem', color: '#94a3b8', marginBottom: '1rem' }}>Selected items will replace the summary chart.</p>
                    <div className={styles.checklist}>
                        {orders.map(wo => (
                            <label key={wo.id} className={styles.checkItem}>
                                <input
                                    type="checkbox"
                                    checked={pinnedIds.includes(wo.id)}
                                    onChange={() => togglePin(wo.id)}
                                />
                                <span>{wo.title} ({wo.aircraft})</span>
                            </label>
                        ))}
                    </div>
                    <button onClick={() => setIsEditing(false)} className={styles.doneBtn}>Done</button>
                    <button onClick={() => { setPinnedIds([]); setIsEditing(false); }} style={{ marginTop: '0.5rem', background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: '0.8rem' }}>Clear All Pins (Show Chart)</button>
                </div>
            ) : (
                <div className={styles.list} style={{ height: '100%', overflowY: 'auto' }}>
                    {showFullList ? (
                        // FULL LIST MODE
                        orders.map(wo => renderListItem(wo))
                    ) : showPinnedList ? (
                        // PINNED ITEMS MODE
                        orders.filter(wo => pinnedIds.includes(wo.id)).map(wo => renderListItem(wo))
                    ) : (
                        // CHART MODE (Default)
                        <div style={{ width: '100%', height: '100%', minHeight: '150px' }}>
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                                    <XAxis
                                        dataKey="name"
                                        stroke="var(--text-secondary)"
                                        fontSize={10}
                                        tickLine={false}
                                        axisLine={false}
                                    />
                                    <YAxis
                                        stroke="var(--text-secondary)"
                                        fontSize={10}
                                        tickLine={false}
                                        axisLine={false}
                                    />
                                    <Tooltip
                                        cursor={{ fill: 'rgba(255,255,255,0.05)' }}
                                        contentStyle={{ backgroundColor: 'var(--bg-secondary)', border: 'none', borderRadius: '8px', color: 'var(--text-primary)' }}
                                    />
                                    <Bar dataKey="count" radius={[4, 4, 0, 0]}>
                                        {chartData.map((entry, index) => {
                                            let color = STATUS_COLORS['Open'];
                                            if (entry.name === 'In Progress') color = STATUS_COLORS['In Progress'];
                                            if (entry.name === 'Done') color = STATUS_COLORS['Completed'];
                                            if (entry.name === 'Hold') color = STATUS_COLORS['On Hold'];
                                            return <Cell key={`cell-${index}`} fill={color} />;
                                        })}
                                    </Bar>
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    )}
                </div>
            )}
        </WidgetContainer>
    );
};

export default WorkOrderWidget;
