// src/pages/OCPP.jsx
import React, { useState, useEffect } from 'react';
import { get, post } from '../api';
import PageLayout from '../components/PageLayout';

const OCPP = () => {
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);

  const [config, setConfig] = useState({
    url: '',
    chargeBoxId: '',
    certificate: '',
    privateKey: '',
  });
  const [msg, setMsg] = useState('');

  useEffect(() => {
    const load = async () => {
      try {
        const data = await get('/api/v1/ocpp');
        setStatus(data);
      } catch {
        // ignore errors
      }
      try {
        const cfg = await get('/api/v1/config/ocpp');
        setConfig(cfg);
      } catch {}
      setLoading(false);
    };
    load();
  }, []);

  const save = async () => {
    setMsg('');
    try {
      await post('/api/v1/config/ocpp', config);
      setMsg('Configuração gravada com sucesso!');
    } catch {
      setMsg('Erro ao gravar configuração.');
    }
  };

  return (
    <PageLayout title="OCPP">
      {loading ? (
        <p>A carregar...</p>
      ) : (
        <>
          {status && (
            <div>
              <p>Versão: {status.ocpp_version}</p>
              <p>Status: {status.status}</p>
            </div>
          )}

          {msg && <div className="message">{msg}</div>}
          <form className="form" onSubmit={e => { e.preventDefault(); save(); }}>
            <div className="form-group">
              <label htmlFor="ocpp-url">Servidor:</label>
              <input
                id="ocpp-url"
                type="text"
                value={config.url}
                onChange={e => setConfig({ ...config, url: e.target.value })}
              />
            </div>

            <div className="form-group">
              <label htmlFor="ocpp-id">Charge Box ID:</label>
              <input
                id="ocpp-id"
                type="text"
                value={config.chargeBoxId}
                onChange={e => setConfig({ ...config, chargeBoxId: e.target.value })}
              />
            </div>

            <div className="form-group">
              <label htmlFor="ocpp-cert">Certificado:</label>
              <textarea
                id="ocpp-cert"
                value={config.certificate}
                onChange={e => setConfig({ ...config, certificate: e.target.value })}
              />
            </div>

            <div className="form-group">
              <label htmlFor="ocpp-key">Chave Privada:</label>
              <textarea
                id="ocpp-key"
                value={config.privateKey}
                onChange={e => setConfig({ ...config, privateKey: e.target.value })}
              />
            </div>

            <div className="button-grid">
              <button type="submit">Guardar</button>
            </div>
          </form>
        </>
      )}
    </PageLayout>
  );
};

export default OCPP;
