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

const InspectionSection = ({ assetId, onUpdated }) => {
    const [inspections, setInspections] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showForm, setShowForm] = useState(false);
    const [saving, setSaving] = useState(false);
    const [form, setForm] = useState({
        inspection_date: new Date().toISOString().split('T')[0],
        result: 'bestanden',
        notes: '',
        next_due_date: '',
    });

    useEffect(() => { load(); }, [assetId]); // eslint-disable-line

    const load = async () => {
        try {
            const data = await assetService.getInspections(assetId);
            setInspections(data);
        } catch (_) {}
        finally { setLoading(false); }
    };

    const setF = (field) => (e) => setForm({ ...form, [field]: e.target.value });

    const handleSubmit = async () => {
        setSaving(true);
        try {
            await assetService.createInspection(assetId, form);
            toast.success('Prüfung eingetragen');
            setShowForm(false);
            setForm({ inspection_date: new Date().toISOString().split('T')[0], result: 'bestanden', notes: '', next_due_date: '' });
            load();
            if (onUpdated) onUpdated();
        } catch (e) {
            toast.error(e.message || 'Fehler');
        } finally {
            setSaving(false);
        }
    };

    return (
        <div style={{ marginTop: 24 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <h3 style={{ fontSize: 14, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', margin: 0 }}>
                    Prüfprotokoll
                </h3>
                <button className="btn btn-primary" style={{ padding: '6px 14px', fontSize: 13 }} onClick={() => setShowForm(!showForm)}>
                    + Prüfung eintragen
                </button>
            </div>

            {showForm && (
                <div style={{ background: 'var(--bg-card, #1e293b)', border: '1px solid var(--border-color)', borderRadius: 10, padding: 16, marginBottom: 16 }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                        <div className="form-group">
                            <label className="form-label">Prüfdatum*</label>
                            <input type="date" className="form-input" value={form.inspection_date} onChange={setF('inspection_date')} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Ergebnis*</label>
                            <select className="form-select" value={form.result} onChange={setF('result')}>
                                <option value="bestanden">✅ Bestanden</option>
                                <option value="nicht_bestanden">❌ Nicht bestanden</option>
                            </select>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="form-label">Nächste Fälligkeit</label>
                        <input type="date" className="form-input" value={form.next_due_date} onChange={setF('next_due_date')} />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Notizen</label>
                        <textarea className="form-textarea" rows="2" value={form.notes} onChange={setF('notes')} placeholder="z.B. VDE-Prüfung bestanden, Kabel erneuert..." />
                    </div>
                    <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                        <button className="btn btn-secondary" onClick={() => setShowForm(false)} disabled={saving}>Abbrechen</button>
                        <button className="btn btn-primary" onClick={handleSubmit} disabled={saving}>{saving ? 'Speichern...' : 'Speichern'}</button>
                    </div>
                </div>
            )}

            {loading ? (
                <p style={{ color: 'var(--text-muted)', fontSize: 13 }}>Laden...</p>
            ) : inspections.length === 0 ? (
                <p style={{ color: 'var(--text-muted)', fontSize: 13, fontStyle: 'italic' }}>Noch keine Prüfungen eingetragen.</p>
            ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {inspections.map(ins => (
                        <div key={ins.id} style={{
                            display: 'flex', gap: 12, alignItems: 'flex-start',
                            padding: '10px 14px', borderRadius: 8,
                            background: 'var(--bg-card, #1e293b)',
                            border: `1px solid ${ins.result === 'bestanden' ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)'}`,
                        }}>
                            <span style={{ fontSize: 18, marginTop: 1 }}>{ins.result === 'bestanden' ? '✅' : '❌'}</span>
                            <div style={{ flex: 1 }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 2 }}>
                                    <span style={{ fontWeight: 600, fontSize: 13, color: 'var(--text-primary)' }}>
                                        {ins.result === 'bestanden' ? 'Bestanden' : 'Nicht bestanden'}
                                    </span>
                                    <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{ins.inspection_date}</span>
                                </div>
                                {ins.notes && <p style={{ fontSize: 12, color: 'var(--text-muted)', margin: '2px 0' }}>{ins.notes}</p>}
                                <p style={{ fontSize: 11, color: 'var(--text-muted)', margin: 0 }}>
                                    Durchgeführt von: {ins.inspector_name || 'Unbekannt'}
                                    {ins.next_due_date && ` · Nächste Prüfung: ${ins.next_due_date}`}
                                </p>
                            </div>
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

export default InspectionSection;
