import React, { useState } from 'react';
import assetService from '../../services/assetService';
import { toast } from 'react-toastify';
import { getDefaultUsefulLife } from '../../utils/afaUtils';

const TEMPLATES = [
    {
        type: 'Maschine',
        icon: '⚙️',
        label: 'Maschine',
        description: 'CNC, Presse, Förderanlage, ...',
    },
    {
        type: 'Werkzeug',
        icon: '🔧',
        label: 'Werkzeug',
        description: 'Akkuschrauber, Bohrer, Messgerät, ...',
    },
    {
        type: 'Sonstiges',
        icon: '📦',
        label: 'Sonstiges',
        description: 'Alles weitere',
    },
];

const STEPS = ['Vorlage', 'Details', 'Wartung'];

const empty = {
    name: '',
    type: '',
    department: 'Produktion',
    serial_number: '',
    model: '',
    status: 'verfuegbar',
    purchase_date: '',
    description: '',
    last_maintenance_date: '',
    next_maintenance_date: '',
    maintenance_interval_months: '',
    maintenance_notes: '',
    inventory_number: '',
    purchase_price: '',
    useful_life_years: '',
    residual_value: '',
};

const ProduktionAssetWizard = ({ asset, onClose, onSaved }) => {
    const isEdit = !!asset;
    const [step, setStep] = useState(isEdit ? 1 : 0);
    const [formData, setFormData] = useState(
        isEdit
            ? {
                  name: asset.name || '',
                  type: asset.type || 'Maschine',
                  department: asset.department || 'Produktion',
                  serial_number: asset.serial_number || '',
                  model: asset.model || '',
                  status: asset.status || 'verfuegbar',
                  purchase_date: asset.purchase_date || '',
                  description: asset.description || '',
                  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 || '',
              }
            : empty
    );
    const [loading, setLoading] = useState(false);

    const set = (field) => (e) => {
        const updated = { ...formData, [field]: e.target.value };
        // Auto-calculate next due date
        if ((field === 'last_maintenance_date' || field === 'maintenance_interval_months')) {
            const last = updated.last_maintenance_date;
            const interval = parseInt(updated.maintenance_interval_months);
            if (last && interval > 0) {
                const d = new Date(last);
                d.setMonth(d.getMonth() + interval);
                updated.next_maintenance_date = d.toISOString().split('T')[0];
            }
        }
        setFormData(updated);
    };

    const selectTemplate = (type) => {
        setFormData({ ...formData, type });
        setStep(1);
    };

    const handleSubmit = async () => {
        if (!formData.name.trim()) {
            toast.error('Bitte einen Namen eingeben');
            return;
        }
        setLoading(true);
        try {
            if (isEdit) {
                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);
        }
    };

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 520 }}>
                <div className="modal-header">
                    <h2 className="modal-title">
                        {isEdit ? 'Asset bearbeiten' : 'Neues Asset'}
                    </h2>
                    <button className="modal-close" onClick={onClose}>×</button>
                </div>

                {/* Step indicator */}
                <div style={{ display: 'flex', gap: 0, margin: '0 24px 20px', borderRadius: 8, overflow: 'hidden', border: '1px solid var(--border-color)' }}>
                    {STEPS.map((label, i) => (
                        <div
                            key={i}
                            style={{
                                flex: 1,
                                padding: '8px 4px',
                                textAlign: 'center',
                                fontSize: 12,
                                fontWeight: step === i ? 700 : 400,
                                background: step === i ? 'var(--accent-color, #0d9488)' : i < step ? 'var(--accent-muted, #0d948822)' : 'transparent',
                                color: step === i ? '#fff' : i < step ? 'var(--accent-color, #0d9488)' : 'var(--text-muted)',
                                transition: 'all 0.2s',
                            }}
                        >
                            {i < step ? '✓ ' : `${i + 1}. `}{label}
                        </div>
                    ))}
                </div>

                <div style={{ padding: '0 24px 24px' }}>

                    {/* STEP 0 – Vorlage wählen */}
                    {step === 0 && (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                            <p style={{ color: 'var(--text-muted)', fontSize: 13, marginBottom: 4 }}>
                                Wähle eine Vorlage für das neue Asset:
                            </p>
                            {TEMPLATES.map((tpl) => (
                                <button
                                    key={tpl.type}
                                    type="button"
                                    onClick={() => selectTemplate(tpl.type)}
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: 16,
                                        padding: '16px 20px',
                                        border: '1px solid var(--border-color)',
                                        borderRadius: 10,
                                        background: 'var(--bg-card, #1e293b)',
                                        cursor: 'pointer',
                                        textAlign: 'left',
                                        transition: 'border-color 0.15s, background 0.15s',
                                    }}
                                    onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent-color, #0d9488)'}
                                    onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border-color)'}
                                >
                                    <span style={{ fontSize: 32 }}>{tpl.icon}</span>
                                    <div>
                                        <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--text-primary)' }}>{tpl.label}</div>
                                        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>{tpl.description}</div>
                                    </div>
                                </button>
                            ))}
                        </div>
                    )}

                    {/* STEP 1 – Details */}
                    {step === 1 && (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                            <div className="form-group">
                                <label className="form-label">Typ</label>
                                <select className="form-select" value={formData.type} onChange={set('type')}>
                                    <option value="Maschine">⚙️ Maschine</option>
                                    <option value="Werkzeug">🔧 Werkzeug</option>
                                    <option value="Sonstiges">📦 Sonstiges</option>
                                </select>
                            </div>
                            <div className="form-group">
                                <label className="form-label">Name*</label>
                                <input type="text" className="form-input" value={formData.name} onChange={set('name')} autoFocus placeholder="z.B. Akkuschrauber Bosch GSR 18V" />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Bereich*</label>
                                <select className="form-select" value={formData.department} onChange={set('department')}>
                                    <option value="Produktion">Produktion</option>
                                    <option value="Techniker">Techniker</option>
                                </select>
                            </div>
                            <div className="form-group">
                                <label className="form-label">Modell</label>
                                <input type="text" className="form-input" value={formData.model} onChange={set('model')} placeholder="z.B. GSR 18V-55" />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Seriennummer <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>(optional)</span></label>
                                <input type="text" className="form-input" value={formData.serial_number} onChange={set('serial_number')} placeholder="Wird automatisch vergeben wenn leer" />
                            </div>
                            <div className="form-group">
                                <label className="form-label">Status*</label>
                                <select className="form-select" value={formData.status} onChange={set('status')}>
                                    <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="2" value={formData.description} onChange={set('description')} />
                            </div>
                        </div>
                    )}

                    {/* STEP 2 – Wartung & Prüfung */}
                    {step === 2 && (
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                            <p style={{ color: 'var(--text-muted)', fontSize: 13, marginBottom: 8 }}>
                                Wartungs- und Prüfinformationen (optional)
                            </p>
                            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                                <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')} />
                                    {formData.last_maintenance_date && formData.maintenance_interval_months && (
                                        <p style={{ fontSize: 11, color: 'var(--accent-color, #0d9488)', marginTop: 4 }}>
                                            Automatisch berechnet aus letzter Wartung + Intervall
                                        </p>
                                    )}
                                </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="3" placeholder="z.B. VDE-Prüfung, UVV-Prüfung fällig..." value={formData.maintenance_notes} onChange={set('maintenance_notes')} />
                            </div>

                            {/* Anlagevermögen */}
                            <div style={{ borderTop: '1px solid var(--border-color)', marginTop: 12, paddingTop: 12 }}>
                                <p style={{ color: 'var(--text-muted)', fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10 }}>
                                    Anlagevermögen (optional)
                                </p>
                                <div className="form-group">
                                    <label className="form-label">Inventarnummer</label>
                                    <input
                                        type="text"
                                        className="form-input"
                                        placeholder={isEdit ? '' : 'wird automatisch vergeben (ANL-XXXX)'}
                                        value={formData.inventory_number}
                                        onChange={set('inventory_number')}
                                    />
                                </div>
                                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
                                    <div className="form-group">
                                        <label className="form-label">Anschaffungswert (€)</label>
                                        <input type="number" className="form-input" min="0" step="0.01" placeholder="z.B. 2500.00" value={formData.purchase_price} onChange={set('purchase_price')} />
                                    </div>
                                    <div className="form-group">
                                        <label className="form-label">Nutzungsdauer (J)</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>
                            </div>
                        </div>
                    )}

                    {/* Navigation */}
                    <div className="card-footer" style={{ marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--border-color)' }}>
                        {step > 0 && (
                            <button type="button" className="btn btn-secondary" onClick={() => setStep(step - 1)} disabled={loading}>
                                Zurück
                            </button>
                        )}
                        {step === 0 && (
                            <button type="button" className="btn btn-secondary" onClick={onClose}>
                                Abbrechen
                            </button>
                        )}
                        {step < 2 && step > 0 && (
                            <button
                                type="button"
                                className="btn btn-primary"
                                onClick={() => setStep(step + 1)}
                                disabled={!formData.name.trim()}
                            >
                                Weiter
                            </button>
                        )}
                        {step === 2 && (
                            <button type="button" className="btn btn-primary" onClick={handleSubmit} disabled={loading}>
                                {loading ? 'Speichern...' : 'Speichern'}
                            </button>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default ProduktionAssetWizard;
