import React, { useState, useEffect, useMemo } from 'react';
import assetService from '../services/assetService';
import { calculateAfa, formatEuro } from '../utils/afaUtils';

const AnlagevermoegenPage = () => {
    const [assets, setAssets] = useState([]);
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState('');

    useEffect(() => {
        assetService.getAll()
            .then(data => setAssets(data || []))
            .catch(() => setAssets([]))
            .finally(() => setLoading(false));
    }, []);

    // Nur Assets mit Kaufpreis > 0
    const anlagen = useMemo(() => {
        return assets
            .filter(a => a.purchase_price > 0)
            .map(a => ({
                ...a,
                afa: calculateAfa(a.purchase_price, a.useful_life_years, a.residual_value, a.purchase_date),
            }));
    }, [assets]);

    const filtered = useMemo(() => {
        if (!search.trim()) return anlagen;
        const q = search.toLowerCase();
        return anlagen.filter(a =>
            (a.name || '').toLowerCase().includes(q) ||
            (a.inventory_number || '').toLowerCase().includes(q) ||
            (a.serial_number || '').toLowerCase().includes(q) ||
            (a.model || '').toLowerCase().includes(q)
        );
    }, [anlagen, search]);

    // Summenwerte
    const totals = useMemo(() => {
        let totalPurchase = 0, totalBookValue = 0, totalCumulative = 0;
        anlagen.forEach(a => {
            totalPurchase += a.purchase_price || 0;
            if (a.afa) {
                totalBookValue += a.afa.currentBookValue;
                totalCumulative += a.afa.cumulativeDepreciation;
            } else {
                totalBookValue += a.purchase_price || 0;
            }
        });
        return { totalPurchase, totalBookValue, totalCumulative };
    }, [anlagen]);

    const handleExportCsv = () => {
        const today = new Date().toISOString().split('T')[0];
        const headers = ['Inv.-Nr.', 'Name', 'Typ', 'Bereich', 'Seriennummer', 'Kaufdatum',
            'Anschaffungswert (€)', 'Nutzungsdauer (J)', 'AfA/Jahr (€)', 'Restwert (€)',
            'Buchwert heute (€)', 'Kum. AfA (€)', 'Abgeschrieben am', 'Status'];

        const rows = filtered.map(a => {
            const afa = a.afa;
            return [
                a.inventory_number || '',
                a.name || '',
                a.type || '',
                a.department || '',
                a.serial_number || '',
                a.purchase_date || '',
                (a.purchase_price || 0).toFixed(2).replace('.', ','),
                a.useful_life_years || '',
                afa ? afa.annualDepreciation.toFixed(2).replace('.', ',') : '',
                (a.residual_value || 0).toFixed(2).replace('.', ','),
                afa ? afa.currentBookValue.toFixed(2).replace('.', ',') : (a.purchase_price || 0).toFixed(2).replace('.', ','),
                afa ? afa.cumulativeDepreciation.toFixed(2).replace('.', ',') : '0,00',
                afa ? afa.fullyDepreciatedDate.toLocaleDateString('de-DE') : '',
                afa ? (afa.isFullyDepreciated ? 'Abgeschrieben' : 'Aktiv') : 'Aktiv',
            ].map(v => `"${String(v).replace(/"/g, '""')}"`).join(';');
        });

        const csv = '\uFEFF' + [headers.map(h => `"${h}"`).join(';'), ...rows].join('\r\n');
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `anlagevermoegen_${today}.csv`;
        a.click();
        URL.revokeObjectURL(url);
    };

    if (loading) {
        return (
            <div className="page-container">
                <div style={{ textAlign: 'center', padding: '60px', color: 'var(--text-muted)' }}>
                    Lade Anlagevermögen…
                </div>
            </div>
        );
    }

    return (
        <div className="page-container">
            {/* Header */}
            <div className="page-header" style={{ marginBottom: '24px' }}>
                <div>
                    <h1 className="page-title">Anlagevermögen</h1>
                    <p className="page-subtitle">AfA-Tracking für Inventar mit Kaufpreisen</p>
                </div>
                <button
                    onClick={handleExportCsv}
                    className="btn btn-secondary"
                    disabled={filtered.length === 0}
                >
                    CSV exportieren
                </button>
            </div>

            {/* Kacheln */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px', marginBottom: '24px' }}>
                <div className="card" style={{ padding: '20px' }}>
                    <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginBottom: '6px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                        Gesamtanschaffungswert
                    </div>
                    <div style={{ fontSize: '24px', fontWeight: 700, color: 'var(--text-primary)' }}>
                        {formatEuro(totals.totalPurchase)}
                    </div>
                    <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: '4px' }}>
                        {anlagen.length} Anlage{anlagen.length !== 1 ? 'n' : ''}
                    </div>
                </div>
                <div className="card" style={{ padding: '20px' }}>
                    <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginBottom: '6px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                        Buchwert heute
                    </div>
                    <div style={{ fontSize: '24px', fontWeight: 700, color: 'var(--cereda-primary)' }}>
                        {formatEuro(totals.totalBookValue)}
                    </div>
                    <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: '4px' }}>
                        Aktueller Zeitwert
                    </div>
                </div>
                <div className="card" style={{ padding: '20px' }}>
                    <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginBottom: '6px', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.5px' }}>
                        Kumulierte AfA
                    </div>
                    <div style={{ fontSize: '24px', fontWeight: 700, color: '#ef4444' }}>
                        {formatEuro(totals.totalCumulative)}
                    </div>
                    <div style={{ fontSize: '12px', color: 'var(--text-muted)', marginTop: '4px' }}>
                        Bereits abgeschrieben
                    </div>
                </div>
            </div>

            {/* Suchfeld */}
            <div style={{ marginBottom: '16px' }}>
                <input
                    type="text"
                    className="form-input"
                    placeholder="🔍  Suche nach Name, Inv.-Nr., Seriennummer, Modell…"
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                />
            </div>

            {/* Tabelle */}
            <div className="card">
                {filtered.length === 0 ? (
                    <div style={{ padding: '48px', textAlign: 'center', color: 'var(--text-muted)' }}>
                        {anlagen.length === 0
                            ? 'Keine Assets mit Kaufpreis vorhanden. Trage Anschaffungswerte in den Asset-Einstellungen ein.'
                            : 'Keine Ergebnisse für diese Suche.'}
                    </div>
                ) : (
                    <div style={{ overflowX: 'auto' }}>
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>Inv.-Nr.</th>
                                    <th>Name</th>
                                    <th>Typ</th>
                                    <th>Bereich</th>
                                    <th>Kaufdatum</th>
                                    <th style={{ textAlign: 'right' }}>Anschaffungs&shy;wert</th>
                                    <th style={{ textAlign: 'center' }}>ND (J)</th>
                                    <th style={{ textAlign: 'right' }}>AfA/Jahr</th>
                                    <th style={{ textAlign: 'right' }}>Buchwert heute</th>
                                    <th>Abgeschrieben am</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                {filtered.map(a => {
                                    const afa = a.afa;
                                    const depDate = afa ? afa.fullyDepreciatedDate : null;
                                    const isFuture = depDate && !afa.isFullyDepreciated;
                                    return (
                                        <tr key={a.id}>
                                            <td>
                                                <span style={{ fontFamily: 'monospace', fontWeight: 600, fontSize: '13px', color: 'var(--cereda-primary)' }}>
                                                    {a.inventory_number || '–'}
                                                </span>
                                            </td>
                                            <td style={{ fontWeight: 500 }}>{a.name}</td>
                                            <td>{a.type}</td>
                                            <td>{a.department}</td>
                                            <td>{a.purchase_date ? new Date(a.purchase_date).toLocaleDateString('de-DE') : '–'}</td>
                                            <td style={{ textAlign: 'right' }}>{formatEuro(a.purchase_price)}</td>
                                            <td style={{ textAlign: 'center' }}>{a.useful_life_years || '–'}</td>
                                            <td style={{ textAlign: 'right' }}>{afa ? formatEuro(afa.annualDepreciation) : '–'}</td>
                                            <td style={{ textAlign: 'right', fontWeight: 600 }}>
                                                {afa ? formatEuro(afa.currentBookValue) : formatEuro(a.purchase_price)}
                                            </td>
                                            <td style={{ color: isFuture ? '#16a34a' : 'var(--text-muted)', fontWeight: isFuture ? 500 : 400 }}>
                                                {depDate ? depDate.toLocaleDateString('de-DE') : '–'}
                                            </td>
                                            <td>
                                                {afa ? (
                                                    <span style={{
                                                        display: 'inline-block',
                                                        padding: '2px 8px',
                                                        borderRadius: '6px',
                                                        fontSize: '11px',
                                                        fontWeight: 600,
                                                        background: afa.isFullyDepreciated ? 'rgba(107,114,128,0.12)' : 'rgba(22,163,74,0.12)',
                                                        color: afa.isFullyDepreciated ? '#6b7280' : '#16a34a',
                                                    }}>
                                                        {afa.isFullyDepreciated ? 'Abgeschrieben' : 'Aktiv'}
                                                    </span>
                                                ) : (
                                                    <span style={{ color: 'var(--text-muted)', fontSize: '12px' }}>Keine AfA</span>
                                                )}
                                            </td>
                                        </tr>
                                    );
                                })}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>
        </div>
    );
};

export default AnlagevermoegenPage;
