const { useState, useEffect } = React;

const STATUS_FLOW = [
    "Em orçamento",
    "Aguardando aprovação",
    "Orçamento aprovado",
    "Em execução",
    "Aguardando peça",
    "Serviço concluído",
    "Entregue",
];

function getBadgeClass(status) {
    switch(status) {
        case "Serviço concluído":    return "badge badge-green";
        case "Em execução":          return "badge badge-accent";
        case "Aguardando peça":      return "badge badge-red";
        case "Orçamento aprovado":   return "badge badge-orange";
        case "Aguardando aprovação": return "badge badge-blue";
        case "Entregue":             return "badge badge-default";
        default:                     return "badge badge-default";
    }
}

const FIELD_VALIDATORS = {
    client_name: (v) => window.validators.validatePersonName(v, { label: 'Nome do cliente' }),
    phone: (v) => window.validators.validatePhone(v, { required: false }),
    license_plate: (v) => window.validators.validateLicensePlate(v),
    vehicle_model: (v) => window.validators.validateFreeText(v, { label: 'Modelo do veículo', min: 2 }),
    service_type: (v) => window.validators.validateFreeText(v, { label: 'Tipo de serviço', min: 3 }),
    mechanic_id: (v) => window.validators.validatePositiveInteger(v, { label: 'Mecânico', required: false }),
};

function CreateForm({ mechanics, onClose, onCreated }) {
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);
    const [errors, setErrors] = useState({});
    const [form, setForm] = useState({
        client_name: '', phone: '', license_plate: '',
        vehicle_model: '', service_type: '', mechanic_id: '',
    });

    const XSS_GUARDED_FIELDS = ['vehicle_model', 'service_type'];

    const set = (field, val) => {
        setForm(prev => ({ ...prev, [field]: val }));
        if (XSS_GUARDED_FIELDS.includes(field)) {
            setErrors(prev => ({ ...prev, [field]: window.validators.validateNoXssChars(val) }));
            return;
        }
        if (errors[field]) setErrors(prev => ({ ...prev, [field]: null }));
    };

    const handleBlur = (field) => {
        const message = FIELD_VALIDATORS[field](form[field]);
        setErrors(prev => ({ ...prev, [field]: message }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError(null);

        const fieldErrors = window.validators.validateVehicleForm(form);
        setErrors(fieldErrors);
        if (Object.keys(fieldErrors).length > 0) {
            setError("Corrija os campos destacados antes de continuar.");
            return;
        }

        setSaving(true);
        try {
            const payload = { ...form };
            if (!payload.mechanic_id) delete payload.mechanic_id;
            await window.api.createVehicle(payload);
            onCreated();
        } catch(err) {
            setError(err.message || "Erro inesperado.");
            setSaving(false);
        }
    };

    const inputClass = (field) => `input${errors[field] ? ' input-invalid' : ''}`;

    return (
        <form onSubmit={handleSubmit} noValidate style={{ display: 'contents' }}>
            <div className="modal-header">
                <div>
                    <h2 style={{ fontSize: '1.25rem', margin: 0 }}>Novo Veículo</h2>
                    <p className="text-secondary text-sm" style={{ marginTop: '4px' }}>
                        Registrar entrada de veículo na oficina
                    </p>
                </div>
                <button type="button" className="modal-close" onClick={onClose}>&#x2715;</button>
            </div>

            <div className="modal-body">
                {error && (
                    <div style={{
                        padding: '12px 16px', borderRadius: 'var(--radius)', background: 'var(--red-glow)',
                        border: '1px solid var(--red)', color: 'var(--red)', fontSize: '0.875rem'
                    }}>{error}</div>
                )}

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
                    <div className="input-group" style={{ gridColumn: '1 / -1' }}>
                        <label className="input-label">Nome do Cliente *</label>
                        <input className={inputClass('client_name')} placeholder="Ex: João da Silva" value={form.client_name}
                            onChange={e => set('client_name', e.target.value)} onBlur={() => handleBlur('client_name')}
                            required minLength={2} maxLength={100} pattern="[A-Za-zÀ-ÖØ-öø-ÿ][A-Za-zÀ-ÖØ-öø-ÿ\s'.-]*"
                            title="Informe um nome válido, contendo apenas letras" />
                        {errors.client_name && <span className="input-error-msg">{errors.client_name}</span>}
                    </div>

                    <div className="input-group">
                        <label className="input-label">Telefone</label>
                        <input className={inputClass('phone')} placeholder="(11) 99999-9999" value={form.phone}
                            onChange={e => set('phone', e.target.value)} onBlur={() => handleBlur('phone')}
                            maxLength={20} pattern="\(\d{2}\)\s?\d{4,5}-\d{4}" title="Use o formato (11) 99999-9999" />
                        {errors.phone && <span className="input-error-msg">{errors.phone}</span>}
                    </div>

                    <div className="input-group">
                        <label className="input-label">Placa *</label>
                        <input className={`${inputClass('license_plate')} font-mono`} placeholder="ABC-1234" value={form.license_plate}
                            onChange={e => set('license_plate', window.validators.formatLicensePlateInput(e.target.value))}
                            onBlur={() => handleBlur('license_plate')}
                            required maxLength={8} pattern="[A-Za-z]{3}-?\d[A-Za-z0-9]\d{2}" title="Use o formato ABC-1234 ou ABC1D23"
                            style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }} />
                        {errors.license_plate && <span className="input-error-msg">{errors.license_plate}</span>}
                    </div>

                    <div className="input-group" style={{ gridColumn: '1 / -1' }}>
                        <label className="input-label">Modelo do Veículo *</label>
                        <input className={inputClass('vehicle_model')} placeholder="Ex: Toyota Corolla 2022" value={form.vehicle_model}
                            onChange={e => set('vehicle_model', e.target.value)} onBlur={() => handleBlur('vehicle_model')}
                            required minLength={2} maxLength={100} pattern="[^<>]*"
                            title="Informe o modelo do veículo (os caracteres < e > não são permitidos)" />
                        {errors.vehicle_model && <span className="input-error-msg">{errors.vehicle_model}</span>}
                    </div>

                    <div className="input-group" style={{ gridColumn: '1 / -1' }}>
                        <label className="input-label">Tipo de Serviço *</label>
                        <input className={inputClass('service_type')} placeholder="Ex: Troca de óleo + revisão geral" value={form.service_type}
                            onChange={e => set('service_type', e.target.value)} onBlur={() => handleBlur('service_type')}
                            required minLength={3} maxLength={255} pattern="[^<>]*"
                            title="Descreva o serviço a ser realizado (os caracteres < e > não são permitidos)" />
                        {errors.service_type && <span className="input-error-msg">{errors.service_type}</span>}
                    </div>

                    <div className="input-group" style={{ gridColumn: '1 / -1' }}>
                        <label className="input-label">Mecânico Responsável</label>
                        <select className="input" value={form.mechanic_id} onChange={e => set('mechanic_id', e.target.value)}>
                            <option value="">— Não atribuído —</option>
                            {mechanics.map(m => (
                                <option key={m.id} value={m.id}>{m.name}</option>
                            ))}
                        </select>
                    </div>
                </div>
            </div>

            <div className="modal-footer">
                <button type="button" className="btn btn-secondary" onClick={onClose}>Cancelar</button>
                <button type="submit" className="btn btn-primary" disabled={saving}>
                    {saving ? 'Salvando...' : 'Registrar Veículo'}
                </button>
            </div>
        </form>
    );
}

const EDIT_FIELD_VALIDATORS = {
    client_name: (v) => window.validators.validatePersonName(v, { label: 'Nome do cliente' }),
    phone: (v) => window.validators.validatePhone(v, { required: false }),
    service_type: (v) => window.validators.validateFreeText(v, { label: 'Tipo de serviço', min: 3 }),
};

function DetailView({ vehicle, mechanics, onClose, onUpdated, onDeleted }) {
    const [deleting, setDeleting] = useState(false);

    const [editForm, setEditForm] = useState({
        client_name: vehicle.client_name || '',
        phone: vehicle.phone || '',
        service_type: vehicle.service_type || '',
    });
    const [editErrors, setEditErrors] = useState({});
    const [saving, setSaving] = useState(false);
    const [saveError, setSaveError] = useState(null);

    const setEdit = (field, val) => {
        setEditForm(prev => ({ ...prev, [field]: val }));
        if (editErrors[field]) setEditErrors(prev => ({ ...prev, [field]: null }));
    };

    const handleEditBlur = (field) => {
        setEditErrors(prev => ({ ...prev, [field]: EDIT_FIELD_VALIDATORS[field](editForm[field]) }));
    };

    const handleSave = async () => {
        setSaveError(null);

        const fieldErrors = {};
        Object.keys(EDIT_FIELD_VALIDATORS).forEach(field => {
            const message = EDIT_FIELD_VALIDATORS[field](editForm[field]);
            if (message) fieldErrors[field] = message;
        });
        setEditErrors(fieldErrors);
        if (Object.keys(fieldErrors).length > 0) {
            setSaveError("Corrija os campos destacados antes de salvar.");
            return;
        }

        setSaving(true);
        try {
            await window.api.updateVehicle(vehicle.id, {
                client_name: editForm.client_name.trim(),
                phone: editForm.phone.trim(),
                service_type: editForm.service_type.trim(),
            });
            onClose(true); 
        } catch (err) {
            setSaveError(err.message || "Erro ao salvar alterações.");
            setSaving(false);
        }
    };

    const editInputClass = (field) => `input${editErrors[field] ? ' input-invalid' : ''}`;

    const handleChecklist = async (itemId, isDone) => {
        await window.api.updateChecklist(itemId, isDone);
        onUpdated(vehicle.id);
    };

    const handleStatus = async (newStatus) => {
        await window.api.updateVehicle(vehicle.id, { status: newStatus });
        onUpdated(vehicle.id);
    };

    const handleMechanicChange = async (newMechanicId) => {
        const val = newMechanicId ? parseInt(newMechanicId) : null;
        await window.api.updateVehicle(vehicle.id, { mechanic_id: val });
        onUpdated(vehicle.id);
    };

    const handleDelete = async () => {
        if (!confirm(`Remover ${vehicle.vehicle_model} (${vehicle.license_plate})?`)) return;
        setDeleting(true);
        try {
            await window.api.deleteVehicle(vehicle.id);
            onDeleted(vehicle.id); 
            onClose(false);
        } catch { setDeleting(false); }
    };

    const currentIdx = STATUS_FLOW.indexOf(vehicle.status);
    const nextStatus = currentIdx < STATUS_FLOW.length - 1 ? STATUS_FLOW[currentIdx + 1] : null;
    const prevStatus = currentIdx > 0 ? STATUS_FLOW[currentIdx - 1] : null;

    const completedItems = vehicle.checklists.filter(i => i.is_done).length;
    const totalItems = vehicle.checklists.length;

    return (
        <>
            <div className="modal-header">
                <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '8px' }}>
                        <h2 style={{ fontSize: '1.375rem', margin: 0 }}>{vehicle.vehicle_model}</h2>
                        <span className={getBadgeClass(vehicle.status)}>{vehicle.status}</span>
                    </div>
                    <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>
                        <span style={{ fontFamily: 'var(--font-mono)', background: 'var(--surface-2)',
                            border: '1px solid var(--border)', padding: '2px 10px', borderRadius: '4px',
                            fontSize: '0.875rem', letterSpacing: '0.1em', fontWeight: 700 }}>
                            {vehicle.license_plate}
                        </span>
                        <span className="text-secondary text-sm">
                            #{String(vehicle.id).padStart(4,'0')} · {vehicle.client_name}
                        </span>
                    </div>
                </div>
                <button className="modal-close" onClick={() => onClose(false)}>&#x2715;</button>
            </div>

            <div className="modal-body">
                {saveError && (
                    <div style={{
                        padding: '12px 16px', borderRadius: 'var(--radius)', background: 'var(--red-glow)',
                        border: '1px solid var(--red)', color: 'var(--red)', fontSize: '0.875rem'
                    }}>{saveError}</div>
                )}

                {/* Meta info */}
                <div style={{
                    display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px',
                    background: 'var(--surface-2)', borderRadius: 'var(--radius)',
                    border: '1px solid var(--border)', padding: '16px', alignItems: 'start'
                }}>
                    <div>
                        <p className="input-label" style={{ marginBottom: '2px' }}>Serviço</p>
                        <input className={editInputClass('service_type')} style={{ padding: '6px 10px', fontSize: '0.875rem' }}
                            value={editForm.service_type} onChange={e => setEdit('service_type', e.target.value)}
                            onBlur={() => handleEditBlur('service_type')} maxLength={255} pattern="[^<>]*"
                            title="Os caracteres < e > não são permitidos" />
                        {editErrors.service_type && <span className="input-error-msg">{editErrors.service_type}</span>}
                    </div>
                    <div>
                        <p className="input-label" style={{ marginBottom: '2px' }}>Mecânico</p>
                        <select
                            className="input"
                            style={{ padding: '6px 10px', fontSize: '0.875rem' }}
                            value={vehicle.mechanic?.id || ""}
                            onChange={(e) => handleMechanicChange(e.target.value)}
                        >
                            <option value="">Não atribuído</option>
                            {mechanics.map(m => (
                                <option key={m.id} value={m.id}>{m.name}</option>
                            ))}
                        </select>
                    </div>
                    <div>
                        <p className="input-label" style={{ marginBottom: '2px' }}>Cliente</p>
                        <input className={editInputClass('client_name')} style={{ padding: '6px 10px', fontSize: '0.875rem' }}
                            value={editForm.client_name} onChange={e => setEdit('client_name', e.target.value)}
                            onBlur={() => handleEditBlur('client_name')} maxLength={100} />
                        {editErrors.client_name && <span className="input-error-msg">{editErrors.client_name}</span>}
                    </div>
                    <div>
                        <p className="input-label" style={{ marginBottom: '2px' }}>Telefone</p>
                        <input className={editInputClass('phone')} style={{ padding: '6px 10px', fontSize: '0.875rem' }}
                            value={editForm.phone} onChange={e => setEdit('phone', e.target.value)}
                            onBlur={() => handleEditBlur('phone')} maxLength={20} placeholder="(11) 99999-9999" />
                        {editErrors.phone && <span className="input-error-msg">{editErrors.phone}</span>}
                    </div>
                </div>

                {/* Status actions */}
                <div>
                    <p className="input-label" style={{ marginBottom: '12px' }}>Avançar Status</p>
                    <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
                        {prevStatus && (
                            <button className="btn btn-secondary btn-sm" onClick={() => handleStatus(prevStatus)}>
                                ← {prevStatus}
                            </button>
                        )}
                        {nextStatus && (
                            <button className="btn btn-primary btn-sm" onClick={() => handleStatus(nextStatus)}>
                                {nextStatus} →
                            </button>
                        )}
                        {!nextStatus && vehicle.status !== "Entregue" && (
                            <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                                <span className="badge badge-green" style={{ fontSize: '0.875rem', padding: '8px 16px' }}>
                                    ✓ Serviço Concluído
                                </span>
                                <button className="btn btn-secondary btn-sm" onClick={() => handleStatus("Entregue")}>
                                    Arquivar (Entregar Veículo)
                                </button>
                            </div>
                        )}
                        {vehicle.status === "Entregue" && (
                            <span className="badge badge-default" style={{ fontSize: '0.875rem', padding: '8px 16px' }}>
                                📦 Veículo Entregue (Arquivado)
                            </span>
                        )}
                    </div>
                </div>

                {/* Checklist */}
                <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                        <p className="input-label">Checklist do Mecânico</p>
                        <span className="text-sm text-secondary">
                            {completedItems}/{totalItems} itens
                        </span>
                    </div>

                    {/* Progress bar */}
                    <div style={{ height: '4px', background: 'var(--surface-2)', borderRadius: '2px', marginBottom: '16px', overflow: 'hidden' }}>
                        <div style={{
                            height: '100%', borderRadius: '2px',
                            width: totalItems ? `${(completedItems/totalItems)*100}%` : '0%',
                            background: completedItems === totalItems ? 'var(--green)' : 'var(--accent)',
                            transition: 'width 0.3s ease'
                        }} />
                    </div>

                    <ul style={{ listStyle: 'none', padding: 0, display: 'flex', flexDirection: 'column', gap: '4px' }}>
                        {vehicle.checklists.map(item => (
                            <li key={item.id} style={{
                                display: 'flex', alignItems: 'center', gap: '10px',
                                padding: '10px 12px', borderRadius: 'var(--radius-sm)',
                                background: item.is_done ? 'transparent' : 'var(--surface-2)',
                                border: '1px solid', borderColor: item.is_done ? 'transparent' : 'var(--border)',
                                transition: 'all 0.2s', cursor: 'pointer'
                            }} onClick={() => handleChecklist(item.id, !item.is_done)}>
                                <div style={{
                                    width: '18px', height: '18px', borderRadius: '4px', flexShrink: 0,
                                    border: `2px solid ${item.is_done ? 'var(--green)' : 'var(--border-light)'}`,
                                    background: item.is_done ? 'var(--green)' : 'transparent',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    transition: 'all 0.2s'
                                }}>
                                    {item.is_done && <span style={{ color: '#000', fontSize: '11px', fontWeight: 700 }}>✓</span>}
                                </div>
                                <span style={{
                                    fontSize: '0.875rem',
                                    textDecoration: item.is_done ? 'line-through' : 'none',
                                    color: item.is_done ? 'var(--text-muted)' : 'var(--text-primary)'
                                }}>{item.name}</span>
                            </li>
                        ))}
                    </ul>
                </div>
            </div>

            <div className="modal-footer">
                <button className="btn btn-danger btn-sm" onClick={handleDelete} disabled={deleting || saving}
                    style={{ marginRight: 'auto' }}>
                    {deleting ? 'Removendo...' : 'Excluir Veículo'}
                </button>
                <button className="btn btn-secondary" onClick={() => onClose(false)} disabled={saving}>Fechar</button>
                <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
                    {saving ? 'Salvando...' : 'Salvar Alterações'}
                </button>
            </div>
        </>
    );
}

function VehicleModal({ vehicleId, isOpen, onClose, onUpdated, onDeleted }) {
    const [vehicle, setVehicle] = useState(null);
    const [mechanics, setMechanics] = useState([]);
    const [loading, setLoading] = useState(false);
    const [loadError, setLoadError] = useState(null);

    useEffect(() => {
        window.api.getMechanics().then(setMechanics).catch(() => {});
    }, []);

    const isCreate = vehicleId === 'new';

    useEffect(() => {
        if (isOpen && vehicleId && !isCreate) {
            setLoading(true);
            setVehicle(null);
            setLoadError(null);
            window.api.getVehicle(vehicleId)
                .then(data => { setVehicle(data); setLoading(false); })
                .catch(err => { setLoadError(err.message || "Veículo não encontrado."); setLoading(false); });
        }
        if (!isOpen) { setVehicle(null); setLoading(false); setLoadError(null); }
    }, [isOpen, vehicleId]);

    const handleClose = (didMutate) => {
        if (didMutate) onUpdated();
        onClose();
    };

    const handleDeleted = (id) => {
        onDeleted(id); 
    };

    const handleRefresh = (id) => {
        window.api.getVehicle(id).then(setVehicle).catch(() => {});
        onUpdated();
    };

    if (!isOpen) return null;

    return (
        <div className="modal-overlay" onClick={() => handleClose(false)}>
            <div className="modal-content" onClick={e => e.stopPropagation()}>
                {isCreate ? (
                    <CreateForm
                        mechanics={mechanics}
                        onClose={() => handleClose(false)}
                        onCreated={() => { onUpdated(); onClose(); }}
                    />
                ) : loadError ? (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '12px', alignItems: 'center', justifyContent: 'center', flex: 1, padding: '32px', textAlign: 'center' }}>
                        <p style={{ color: 'var(--red)' }}>{loadError}</p>
                        <p className="text-secondary text-sm">Este veículo pode já ter sido removido. Feche e atualize a lista.</p>
                        <button type="button" className="btn btn-secondary" onClick={() => handleClose(true)}>Fechar</button>
                    </div>
                ) : loading || !vehicle ? (
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 1, color: 'var(--text-secondary)' }}>
                        Carregando detalhes...
                    </div>
                ) : (
                    <DetailView vehicle={vehicle} mechanics={mechanics} onClose={handleClose} onUpdated={handleRefresh} onDeleted={handleDeleted} />
                )}
            </div>
        </div>
    );
}

window.VehicleModal = VehicleModal;
