import React, { useState, useEffect } from 'react';
import axios from 'axios';

const DefectReportPage = () => {
    const [serial, setSerial]       = useState('');
    const [assetName, setAssetName] = useState('');
    const [submitted, setSubmitted] = useState(false);
    const [loading, setLoading]     = useState(false);
    const [formData, setFormData]   = useState({
        title: '',
        description: '',
        requester_name: '',
        requester_email: '',
    });

    useEffect(() => {
        const params = new URLSearchParams(window.location.search);
        const sn = params.get('serial') || '';
        setSerial(sn);
        if (sn) {
            setFormData(f => ({ ...f, title: `Defektmeldung: ${sn}` }));
            axios.get(`/api/assets/serial/${encodeURIComponent(sn)}`)
                .then(r => {
                    const a = r.data?.data;
                    if (a?.name) {
                        setAssetName(a.name);
                        setFormData(f => ({ ...f, title: `Defektmeldung: ${a.name}` }));
                    }
                })
                .catch(() => {});
        }
    }, []);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        try {
            await axios.post('/api/tickets/public', {
                ...formData,
                serial_number: serial,
                category: 'Hardware',
                priority: 'mittel',
            });
            setSubmitted(true);
        } catch {
            alert('Fehler beim Senden. Bitte versuchen Sie es erneut.');
        } finally {
            setLoading(false);
        }
    };

    const inputStyle = {
        width: '100%', padding: '10px 12px',
        border: '1px solid #d1d5db', borderRadius: '8px',
        fontSize: '0.9375rem', boxSizing: 'border-box',
        outline: 'none', fontFamily: 'inherit',
    };
    const labelStyle = {
        display: 'block', fontSize: '0.875rem',
        fontWeight: 600, color: '#374151', marginBottom: '6px',
    };

    if (submitted) {
        return (
            <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f8fafc', padding: '20px' }}>
                <div style={{ textAlign: 'center', maxWidth: '420px' }}>
                    <div style={{ fontSize: '4rem', marginBottom: '16px' }}>✅</div>
                    <h1 style={{ color: '#1a1a2e', fontSize: '1.75rem', margin: '0 0 12px' }}>Meldung eingegangen!</h1>
                    <p style={{ color: '#6b7280', lineHeight: 1.6 }}>
                        Ihr IT-Support hat die Defektmeldung erhalten und wird sich schnellstmöglich um das Problem kümmern.
                    </p>
                    <p style={{ color: '#9ca3af', fontSize: '0.875rem', marginTop: '24px' }}>
                        Sie können dieses Fenster jetzt schließen.
                    </p>
                </div>
            </div>
        );
    }

    return (
        <div style={{ minHeight: '100vh', background: '#f8fafc', padding: '20px', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: '60px' }}>
            <div style={{ width: '100%', maxWidth: '520px' }}>
                {/* Header */}
                <div style={{ textAlign: 'center', marginBottom: '32px' }}>
                    <div style={{ fontSize: '2.5rem', marginBottom: '8px' }}>🔧</div>
                    <h1 style={{ color: '#1a1a2e', fontSize: '1.5rem', margin: '0 0 8px', fontFamily: 'sans-serif' }}>Defektmeldung</h1>
                    {assetName && (
                        <p style={{ color: '#6b7280', margin: 0, fontFamily: 'sans-serif' }}>
                            Gerät: <strong>{assetName}</strong>
                        </p>
                    )}
                    {serial && !assetName && (
                        <p style={{ color: '#9ca3af', margin: 0, fontSize: '0.875rem', fontFamily: 'sans-serif' }}>
                            Seriennummer: {serial}
                        </p>
                    )}
                </div>

                {/* Form Card */}
                <div style={{ background: 'white', borderRadius: '12px', padding: '28px', boxShadow: '0 1px 4px rgba(0,0,0,0.1)', fontFamily: 'sans-serif' }}>
                    <form onSubmit={handleSubmit}>
                        <div style={{ marginBottom: '16px' }}>
                            <label style={labelStyle}>Problem-Beschreibung *</label>
                            <input
                                type="text"
                                required
                                value={formData.title}
                                onChange={e => setFormData({ ...formData, title: e.target.value })}
                                placeholder="Kurze Beschreibung des Defekts"
                                style={inputStyle}
                                autoFocus
                            />
                        </div>

                        <div style={{ marginBottom: '16px' }}>
                            <label style={labelStyle}>Details (optional)</label>
                            <textarea
                                value={formData.description}
                                onChange={e => setFormData({ ...formData, description: e.target.value })}
                                placeholder="Was ist genau passiert? Wann? Fehlermeldungen?"
                                rows={4}
                                style={{ ...inputStyle, resize: 'vertical' }}
                            />
                        </div>

                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '24px' }}>
                            <div>
                                <label style={labelStyle}>Ihr Name</label>
                                <input
                                    type="text"
                                    value={formData.requester_name}
                                    onChange={e => setFormData({ ...formData, requester_name: e.target.value })}
                                    placeholder="Max Mustermann"
                                    style={inputStyle}
                                />
                            </div>
                            <div>
                                <label style={labelStyle}>E-Mail (optional)</label>
                                <input
                                    type="email"
                                    value={formData.requester_email}
                                    onChange={e => setFormData({ ...formData, requester_email: e.target.value })}
                                    placeholder="max@beispiel.de"
                                    style={inputStyle}
                                />
                            </div>
                        </div>

                        <button
                            type="submit"
                            disabled={loading}
                            style={{
                                width: '100%', padding: '13px',
                                background: loading ? '#9ca3af' : '#0d9488',
                                color: 'white', border: 'none', borderRadius: '8px',
                                fontSize: '1rem', fontWeight: 600,
                                cursor: loading ? 'not-allowed' : 'pointer',
                                fontFamily: 'inherit',
                            }}
                        >
                            {loading ? 'Wird gesendet…' : '📨 Defekt melden'}
                        </button>
                    </form>
                </div>

                <p style={{ textAlign: 'center', color: '#9ca3af', fontSize: '0.75rem', marginTop: '20px', fontFamily: 'sans-serif' }}>
                    Powered by IT Nexus · Cereda Systems GmbH
                </p>
            </div>
        </div>
    );
};

export default DefectReportPage;
