import React, { useState, useEffect } from 'react';
import assetService from '../../services/assetService';
import { useAuth } from '../../context/AuthContext';
import { toast } from 'react-toastify';
import ProduktionAssetWizard from './ProduktionAssetWizard';
import { calculateAfa, formatEuro, getDefaultUsefulLife } from '../../utils/afaUtils';

const AssetModal = ({ asset, onClose, onSaved }) => {
    const { isTechniker } = useAuth();
    const isProduktion = isTechniker();
    const [assetTypes, setAssetTypes] = useState([]);

    useEffect(() => {
        assetService.getTypes().then(setAssetTypes).catch(() => {});
    }, []);

    const [formData, setFormData] = useState({
        name: '',
        type: '',
        department: 'IT',
        serial_number: '',
        model: '',
        status: 'verfuegbar',
        purchase_date: '',
        description: '',
        teamviewer_id: '',
        last_maintenance_date: '',
        next_maintenance_date: '',
        maintenance_interval_months: '',
        maintenance_notes: '',
        inventory_number: '',
        purchase_price: '',
        useful_life_years: '',
        residual_value: '',
        os: '',
        ip_address: '',
        manufacturer: '',
    });
    const [loading, setLoading] = useState(false);
    const [syncing, setSyncing] = useState(false);
    const [showAfa, setShowAfa] = useState(false);

    useEffect(() => {
        if (asset) {
            setFormData({
                name: asset.name || '',
                type: asset.type || 'Notebook',
                department: asset.department || 'IT',
                serial_number: asset.serial_number || '',
                model: asset.model || '',
                status: asset.status || 'verfuegbar',
                purchase_date: asset.purchase_date || '',
                description: asset.description || '',
                teamviewer_id: asset.teamviewer_id || '',
                last_maintenance_date: asset.last_maintenance_date || '',
                next_maintenance_date: asset.next_maintenance_date || '',
                maintenance_interval_months: asset.maintenance_interval_months || '',
                maintenance_notes: asset.maintenance_notes || '',
                inventory_number: asset.inventory_number || '',
                purchase_price: asset.purchase_price || '',
                useful_life_years: asset.useful_life_years || '',
                residual_value: asset.residual_value || '',
                os: asset.os || '',
                ip_address: asset.ip_address || '',
                manufacturer: asset.manufacturer || '',
            });
            // Abschnitt aufklappen wenn Felder vorhanden
            if (asset.purchase_price || asset.inventory_number) setShowAfa(true);
        }
    }, [asset]); // eslint-disable-line react-hooks/exhaustive-deps

    // Produktion-Rolle bekommt den Wizard
    if (isProduktion) {
        return <ProduktionAssetWizard asset={asset} onClose={onClose} onSaved={onSaved} />;
    }

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            if (asset) {
                await assetService.update(asset.id, formData);
                toast.success('Asset erfolgreich aktualisiert');
            } else {
                await assetService.create(formData);
                toast.success('Asset erfolgreich erstellt');
            }
            onSaved();
        } catch (error) {
            toast.error(error.message || 'Fehler beim Speichern');
        } finally {
            setLoading(false);
        }
    };

    const set = (field) => (e) => setFormData({ ...formData, [field]: e.target.value });

    const handleSyncAgent = async () => {
        setSyncing(true);
        try {
            const res = await assetService.syncFromAgent(asset.id);
            const updated = res.data;
            setFormData(prev => ({
                ...prev,
                serial_number: updated.serial_number || prev.serial_number,
                os: updated.os || prev.os || '',
                ip_address: updated.ip_address || prev.ip_address || '',
                manufacturer: updated.manufacturer || prev.manufacturer || '',
            }));
            toast.success(`Agent-Daten übernommen (${res.synced_from})`);
        } catch (err) {
            toast.error(err.response?.data?.message || 'Kein Agent gefunden — Hostname muss mit Asset-Name übereinstimmen');
        } finally {
            setSyncing(false);
        }
    };

    // AfA-Vorschau berechnen
    const afaPreview = calculateAfa(
        formData.purchase_price,
        formData.useful_life_years,
        formData.residual_value,
        formData.purchase_date
    );

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h2 className="modal-title">
                        {asset ? 'Asset bearbeiten' : 'Neues Asset'}
                    </h2>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        {asset && (
                            <button
                                type="button"
                                onClick={handleSyncAgent}
                                disabled={syncing}
                                title="Daten vom IT Nexus Agent übernehmen"
                                style={{
                                    display: 'flex', alignItems: 'center', gap: 6,
                                    background: syncing ? 'var(--bg-secondary)' : 'rgba(13,148,136,0.12)',
                                    border: '1px solid var(--cereda-primary)',
                                    borderRadius: 6, color: 'var(--cereda-primary)',
                                    fontSize: 12, fontWeight: 600, cursor: syncing ? 'not-allowed' : 'pointer',
                                    padding: '5px 10px',
                                }}
                            >
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="13" height="13" strokeLinecap="round" strokeLinejoin="round" style={{ animation: syncing ? 'spin 1s linear infinite' : 'none' }}>
                                    <path d="M21 12a9 9 0 1 1-9-9c2.5 0 4.78 1 6.43 2.57L21 8"/><path d="M21 3v5h-5"/>
                                </svg>
                                {syncing ? 'Synchronisiere…' : 'Agent sync'}
                            </button>
                        )}
                        <button className="modal-close" onClick={onClose}>×</button>
                    </div>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="form-group">
                        <label className="form-label">Name*</label>
                        <input type="text" className="form-input" value={formData.name} onChange={set('name')} required />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Typ*</label>
                        <select className="form-select" value={formData.type} onChange={set('type')} required>
                            <option value="">— Typ wählen —</option>
                            {assetTypes.map(t => <option key={t.id} value={t.name}>{t.name}</option>)}
                        </select>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Bereich*</label>
                        <select className="form-select" value={formData.department} onChange={set('department')}>
                            <option value="IT">IT</option>
                            <option value="Produktion">Produktion</option>
                            <option value="Techniker">Techniker</option>
                        </select>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Seriennummer*</label>
                        <input type="text" className="form-input" value={formData.serial_number} onChange={set('serial_number')} required />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Modell</label>
                        <input type="text" className="form-input" value={formData.model} onChange={set('model')} />
                    </div>

                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                        <div className="form-group">
                            <label className="form-label">Hersteller</label>
                            <input type="text" className="form-input" placeholder="z.B. HP, Dell, Lenovo" value={formData.manufacturer} onChange={set('manufacturer')} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Betriebssystem</label>
                            <input type="text" className="form-input" placeholder="z.B. Windows 11 Pro" value={formData.os} onChange={set('os')} />
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">IP-Adresse</label>
                        <input type="text" className="form-input" placeholder="z.B. 192.168.0.42" value={formData.ip_address} onChange={set('ip_address')} />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Status*</label>
                        <select className="form-select" value={formData.status} onChange={set('status')} required>
                            <option value="verfuegbar">Verfügbar</option>
                            <option value="zugewiesen">Zugewiesen</option>
                            <option value="inaktiv">Inaktiv</option>
                            <option value="beschaedigt">Beschädigt</option>
                        </select>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Kaufdatum</label>
                        <input type="date" className="form-input" value={formData.purchase_date} onChange={set('purchase_date')} />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Beschreibung</label>
                        <textarea className="form-textarea" rows="3" value={formData.description} onChange={set('description')} />
                    </div>

                    <div className="form-group">
                        <label className="form-label">TeamViewer ID</label>
                        <input type="text" className="form-input" placeholder="z.B. 123456789" value={formData.teamviewer_id} onChange={set('teamviewer_id')} />
                    </div>

                    <div style={{ borderTop: '1px solid var(--border-color)', margin: '16px 0 12px', paddingTop: '12px' }}>
                        <p className="form-label" style={{ marginBottom: '12px', color: 'var(--text-muted)', fontSize: '12px', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                            Wartung &amp; Prüfung
                        </p>
                    </div>

                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                        <div className="form-group">
                            <label className="form-label">Letzte Wartung</label>
                            <input type="date" className="form-input" value={formData.last_maintenance_date} onChange={set('last_maintenance_date')} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Nächste Prüfung</label>
                            <input type="date" className="form-input" value={formData.next_maintenance_date} onChange={set('next_maintenance_date')} />
                        </div>
                    </div>

                    <div className="form-group">
                        <label className="form-label">Intervall (Monate)</label>
                        <input type="number" className="form-input" min="1" max="120" placeholder="z.B. 12" value={formData.maintenance_interval_months} onChange={set('maintenance_interval_months')} />
                    </div>

                    <div className="form-group">
                        <label className="form-label">Wartungsnotizen</label>
                        <textarea className="form-textarea" rows="2" placeholder="z.B. VDE-Prüfung, nächste UVV-Prüfung fällig..." value={formData.maintenance_notes} onChange={set('maintenance_notes')} />
                    </div>

                    {/* Anlagevermögen */}
                    <div style={{ borderTop: '1px solid var(--border-color)', margin: '16px 0 0' }}>
                        <button
                            type="button"
                            onClick={() => setShowAfa(p => !p)}
                            style={{
                                display: 'flex', alignItems: 'center', gap: '6px',
                                background: 'none', border: 'none', cursor: 'pointer',
                                color: 'var(--text-muted)', fontSize: '12px',
                                textTransform: 'uppercase', letterSpacing: '0.05em',
                                fontWeight: 600, padding: '12px 0',
                            }}
                        >
                            <span style={{ fontSize: '10px', transition: 'transform 0.15s', transform: showAfa ? 'rotate(90deg)' : 'rotate(0deg)' }}>▶</span>
                            Anlagevermögen (optional)
                        </button>
                    </div>

                    {showAfa && (
                        <div style={{ marginBottom: '8px' }}>
                            <div className="form-group">
                                <label className="form-label">Inventarnummer</label>
                                <input
                                    type="text"
                                    className="form-input"
                                    placeholder={asset ? '' : 'wird automatisch vergeben (ANL-XXXX)'}
                                    value={formData.inventory_number}
                                    onChange={set('inventory_number')}
                                />
                                {!asset && !formData.inventory_number && (
                                    <span style={{ fontSize: '11px', color: 'var(--text-muted)', marginTop: '4px', display: 'block' }}>
                                        Leer lassen → automatisch als ANL-XXXX vergeben
                                    </span>
                                )}
                            </div>

                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
                                <div className="form-group">
                                    <label className="form-label">Anschaffungswert (€)</label>
                                    <input
                                        type="number"
                                        className="form-input"
                                        min="0"
                                        step="0.01"
                                        placeholder="z.B. 1200.00"
                                        value={formData.purchase_price}
                                        onChange={set('purchase_price')}
                                    />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Nutzungsdauer (Jahre)</label>
                                    <input
                                        type="number"
                                        className="form-input"
                                        min="1"
                                        max="50"
                                        placeholder={`Standard: ${getDefaultUsefulLife(formData.type)} J`}
                                        value={formData.useful_life_years}
                                        onChange={set('useful_life_years')}
                                    />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Restwert (€)</label>
                                    <input
                                        type="number"
                                        className="form-input"
                                        min="0"
                                        step="0.01"
                                        placeholder="0,00"
                                        value={formData.residual_value}
                                        onChange={set('residual_value')}
                                    />
                                </div>
                            </div>

                            {/* AfA-Vorschau */}
                            {afaPreview && (
                                <div style={{
                                    background: 'var(--bg-secondary)',
                                    border: '1px solid var(--border-color)',
                                    borderRadius: '8px',
                                    padding: '10px 14px',
                                    display: 'grid',
                                    gridTemplateColumns: '1fr 1fr 1fr',
                                    gap: '12px',
                                    marginBottom: '8px',
                                }}>
                                    <div>
                                        <div style={{ fontSize: '11px', color: 'var(--text-muted)', marginBottom: '2px' }}>AfA/Jahr</div>
                                        <div style={{ fontWeight: 600, fontSize: '14px' }}>{formatEuro(afaPreview.annualDepreciation)}</div>
                                    </div>
                                    <div>
                                        <div style={{ fontSize: '11px', color: 'var(--text-muted)', marginBottom: '2px' }}>Buchwert heute</div>
                                        <div style={{ fontWeight: 600, fontSize: '14px', color: 'var(--cereda-primary)' }}>{formatEuro(afaPreview.currentBookValue)}</div>
                                    </div>
                                    <div>
                                        <div style={{ fontSize: '11px', color: 'var(--text-muted)', marginBottom: '2px' }}>Abgeschrieben am</div>
                                        <div style={{ fontWeight: 600, fontSize: '14px', color: afaPreview.isFullyDepreciated ? '#6b7280' : '#16a34a' }}>
                                            {afaPreview.fullyDepreciatedDate.toLocaleDateString('de-DE')}
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    <div className="card-footer">
                        <button type="button" onClick={onClose} className="btn btn-secondary" disabled={loading}>
                            Abbrechen
                        </button>
                        <button type="submit" className="btn btn-primary" disabled={loading}>
                            {loading ? 'Speichern...' : 'Speichern'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default AssetModal;
