import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import assetService from '../services/assetService';
import LoadingSpinner from '../components/common/LoadingSpinner';
import { toast } from 'react-toastify';

const today = new Date().toISOString().slice(0, 10);
const in7   = new Date(Date.now() + 7  * 86400000).toISOString().slice(0, 10);
const in30  = new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10);
const in90  = new Date(Date.now() + 90 * 86400000).toISOString().slice(0, 10);

const getRange = (date) => {
    if (!date) return null;
    if (date < today)  return { label: 'Überfällig', color: '#ef4444', bg: 'rgba(239,68,68,0.1)', icon: '🔴', order: 0 };
    if (date <= in7)   return { label: 'Diese Woche', color: '#f59e0b', bg: 'rgba(245,158,11,0.1)', icon: '🟠', order: 1 };
    if (date <= in30)  return { label: 'Nächste 30 Tage', color: '#3b82f6', bg: 'rgba(59,130,246,0.1)', icon: '🔵', order: 2 };
    if (date <= in90)  return { label: 'Nächste 90 Tage', color: '#22c55e', bg: 'rgba(34,197,94,0.1)', icon: '🟢', order: 3 };
    return { label: 'Später', color: '#6b7280', bg: 'rgba(107,114,128,0.08)', icon: '⚪', order: 4 };
};

const TYPE_ICON = { Notebook: '💻', Monitor: '🖥️', Headset: '🎧', Other: '📦' };

const MaintenancePage = () => {
    const navigate = useNavigate();
    const [assets, setAssets]   = useState([]);
    const [loading, setLoading] = useState(true);
    const [filter, setFilter]   = useState('all');

    useEffect(() => {
        assetService.getAll()
            .then(data => setAssets(data.filter(a => a.next_maintenance_date)))
            .catch(() => toast.error('Fehler beim Laden der Assets'))
            .finally(() => setLoading(false));
    }, []);

    if (loading) return <div className="main-content"><LoadingSpinner /></div>;

    const sorted = [...assets].sort((a, b) =>
        (a.next_maintenance_date || '').localeCompare(b.next_maintenance_date || '')
    );

    const groups = {};
    sorted.forEach(asset => {
        const range = getRange(asset.next_maintenance_date);
        if (!range) return;
        if (filter !== 'all' && range.order !== Number(filter)) return;
        const key = range.label;
        if (!groups[key]) groups[key] = { ...range, assets: [] };
        groups[key].assets.push(asset);
    });

    const groupOrder = ['Überfällig', 'Diese Woche', 'Nächste 30 Tage', 'Nächste 90 Tage', 'Später'];
    const totalShown = Object.values(groups).reduce((s, g) => s + g.assets.length, 0);

    const filterOptions = [
        { value: 'all', label: 'Alle' },
        { value: '0', label: '🔴 Überfällig' },
        { value: '1', label: '🟠 Diese Woche' },
        { value: '2', label: '🔵 30 Tage' },
        { value: '3', label: '🟢 90 Tage' },
    ];

    return (
        <div className="main-content">
            <div className="container">
                {/* Header */}
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '24px' }}>
                    <div>
                        <h1 style={{ margin: 0, fontSize: '1.75rem', fontWeight: 800, color: 'var(--text-primary)' }}>
                            🔧 Wartungskalender
                        </h1>
                        <p style={{ margin: '4px 0 0', color: 'var(--text-secondary)', fontSize: '14px' }}>
                            {assets.length} Assets mit Wartungsterminen · {totalShown} angezeigt
                        </p>
                    </div>
                    <button className="btn btn-secondary" onClick={() => navigate('/assets')}>
                        Zur Asset-Übersicht
                    </button>
                </div>

                {/* Summary Cards */}
                <div className="dashboard-grid" style={{ marginBottom: '24px' }}>
                    {[
                        { label: 'Überfällig', count: assets.filter(a => a.next_maintenance_date < today).length, color: '#ef4444', icon: '🔴' },
                        { label: 'Diese Woche', count: assets.filter(a => a.next_maintenance_date >= today && a.next_maintenance_date <= in7).length, color: '#f59e0b', icon: '🟠' },
                        { label: 'Nächste 30 Tage', count: assets.filter(a => a.next_maintenance_date > in7 && a.next_maintenance_date <= in30).length, color: '#3b82f6', icon: '🔵' },
                        { label: 'Nächste 90 Tage', count: assets.filter(a => a.next_maintenance_date > in30 && a.next_maintenance_date <= in90).length, color: '#22c55e', icon: '🟢' },
                    ].map(s => (
                        <div key={s.label} className="stat-card" style={{ cursor: 'default', borderLeft: `4px solid ${s.color}` }}>
                            <div className="stat-icon">{s.icon}</div>
                            <div className="stat-content">
                                <div className="stat-value" style={{ color: s.color }}>{s.count}</div>
                                <div className="stat-label">{s.label}</div>
                            </div>
                        </div>
                    ))}
                </div>

                {/* Filter */}
                <div className="card" style={{ padding: '12px 16px', marginBottom: '20px', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                    {filterOptions.map(opt => (
                        <button key={opt.value}
                            className={`btn btn-small ${filter === opt.value ? 'btn-primary' : 'btn-secondary'}`}
                            onClick={() => setFilter(opt.value)}>
                            {opt.label}
                        </button>
                    ))}
                </div>

                {/* Groups */}
                {groupOrder.filter(g => groups[g]).map(groupName => {
                    const group = groups[groupName];
                    return (
                        <div key={groupName} style={{ marginBottom: '28px' }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '12px' }}>
                                <span style={{ fontSize: '16px' }}>{group.icon}</span>
                                <h2 style={{ margin: 0, fontSize: '13px', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: group.color }}>
                                    {group.label}
                                </h2>
                                <span style={{ fontSize: '12px', color: 'var(--text-muted)', fontWeight: 600 }}>
                                    ({group.assets.length})
                                </span>
                            </div>
                            <div className="card" style={{ padding: 0, overflow: 'hidden', border: `1px solid ${group.color}33` }}>
                                <table className="table" style={{ margin: 0 }}>
                                    <thead>
                                        <tr>
                                            <th>Asset</th>
                                            <th>Typ</th>
                                            <th>Seriennummer</th>
                                            <th>Zugewiesen an</th>
                                            <th>Letzte Wartung</th>
                                            <th>Nächste Prüfung</th>
                                            <th>Intervall</th>
                                            <th>Notizen</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {group.assets.map(asset => {
                                            const daysLeft = Math.ceil((new Date(asset.next_maintenance_date) - new Date()) / 86400000);
                                            return (
                                                <tr key={asset.id} style={{ cursor: 'pointer' }}
                                                    onClick={() => navigate('/assets')}>
                                                    <td>
                                                        <div style={{ fontWeight: 600, fontSize: '14px', color: 'var(--text-primary)' }}>
                                                            {TYPE_ICON[asset.type] || '📦'} {asset.name}
                                                        </div>
                                                    </td>
                                                    <td style={{ fontSize: '13px', color: 'var(--text-secondary)' }}>{asset.type}</td>
                                                    <td style={{ fontSize: '12px', fontFamily: 'monospace', color: 'var(--text-muted)' }}>{asset.serial_number}</td>
                                                    <td style={{ fontSize: '13px' }}>{asset.assigned_to_username || '—'}</td>
                                                    <td style={{ fontSize: '13px', color: 'var(--text-muted)' }}>
                                                        {asset.last_maintenance_date
                                                            ? new Date(asset.last_maintenance_date).toLocaleDateString('de-DE')
                                                            : '—'}
                                                    </td>
                                                    <td>
                                                        <div style={{ fontWeight: 700, color: group.color, fontSize: '14px' }}>
                                                            {new Date(asset.next_maintenance_date).toLocaleDateString('de-DE')}
                                                        </div>
                                                        <div style={{ fontSize: '11px', color: group.color, opacity: 0.8 }}>
                                                            {daysLeft < 0 ? `${Math.abs(daysLeft)} Tage überfällig` : daysLeft === 0 ? 'Heute!' : `in ${daysLeft} Tagen`}
                                                        </div>
                                                    </td>
                                                    <td style={{ fontSize: '13px', color: 'var(--text-muted)' }}>
                                                        {asset.maintenance_interval_months ? `alle ${asset.maintenance_interval_months} Monate` : '—'}
                                                    </td>
                                                    <td style={{ fontSize: '12px', color: 'var(--text-muted)', maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
                                                        title={asset.maintenance_notes || ''}>
                                                        {asset.maintenance_notes || '—'}
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    );
                })}

                {totalShown === 0 && (
                    <div className="card" style={{ textAlign: 'center', padding: '48px', color: 'var(--text-muted)' }}>
                        <div style={{ fontSize: '48px', marginBottom: '12px' }}>🎉</div>
                        <h3 style={{ margin: '0 0 8px', color: 'var(--text-secondary)' }}>Keine Wartungen fällig</h3>
                        <p style={{ margin: 0, fontSize: '14px' }}>Alle Prüftermine sind im grünen Bereich.</p>
                    </div>
                )}
            </div>
        </div>
    );
};

export default MaintenancePage;
