// Vehicle editor — fields + photo manager.

const { useState: useStateE, useRef: useRefE } = React;

function PhotoManager({ photos, coverIndex, onChange }) {
  const fileInputRef = useRefE(null);

  const handleUpload = (e) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;
    const readers = files.map(
      (f) =>
        new Promise((resolve) => {
          const r = new FileReader();
          r.onload = (ev) => resolve(ev.target.result);
          r.readAsDataURL(f);
        })
    );
    Promise.all(readers).then((dataUrls) => {
      onChange({ photos: [...photos, ...dataUrls], coverIndex });
    });
    e.target.value = "";
  };

  const remove = (i) => {
    const next = photos.filter((_, idx) => idx !== i);
    let nextCover = coverIndex;
    if (i === coverIndex) nextCover = 0;
    else if (i < coverIndex) nextCover = coverIndex - 1;
    onChange({ photos: next, coverIndex: Math.min(nextCover, next.length - 1) });
  };

  const setCover = (i) => onChange({ photos, coverIndex: i });

  return (
    <div className="photo-manager">
      <div className="photo-grid">
        {photos.map((src, i) => (
          <div key={i} className={`photo-tile ${i === coverIndex ? "is-cover" : ""}`}>
            <img src={src} alt={`Photo ${i + 1}`} />
            <div className="photo-overlay">
              {i === coverIndex ? (
                <span className="photo-cover-badge">Cover</span>
              ) : (
                <button
                  type="button"
                  className="photo-action"
                  onClick={() => setCover(i)}
                >
                  Set as cover
                </button>
              )}
              <button
                type="button"
                className="photo-action danger"
                onClick={() => remove(i)}
                title="Delete"
              >
                Delete
              </button>
            </div>
            {i === coverIndex && <div className="cover-pin">★ Cover</div>}
          </div>
        ))}
        <button
          type="button"
          className="photo-tile add-tile"
          onClick={() => fileInputRef.current?.click()}
        >
          <span className="add-icon">+</span>
          <span>Upload photos</span>
        </button>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          multiple
          style={{ display: "none" }}
          onChange={handleUpload}
        />
      </div>
      <div className="photo-help">
        First photo is shown as the cover by default. Click "Set as cover" on any photo to feature it.
      </div>
    </div>
  );
}

function VehicleEditor({ vehicle, onSave, onCancel, onDelete, isNew }) {
  const { VEHICLE_TYPES, TRANSMISSIONS } = window.RENTAL_DATA;
  const [draft, setDraft] = useStateE(() => ({ ...vehicle }));
  const [errors, setErrors] = useStateE({});

  const update = (patch) => setDraft((d) => ({ ...d, ...patch }));

  const handleSave = () => {
    const errs = {};
    if (!draft.make?.trim()) errs.make = "Required";
    if (!draft.model?.trim()) errs.model = "Required";
    if (!draft.year || draft.year < 1980 || draft.year > 2030) errs.year = "1980–2030";
    if (!draft.price || draft.price <= 0) errs.price = "Must be > 0";
    if (!draft.passengers || draft.passengers < 1) errs.passengers = "Must be ≥ 1";
    if (draft.suitcases == null || draft.suitcases < 0) errs.suitcases = "Must be ≥ 0";
    setErrors(errs);
    if (Object.keys(errs).length === 0) onSave(draft);
  };

  return (
    <div className="editor">
      <div className="editor-section">
        <h3 className="editor-section-title">Basic information</h3>
        <div className="form-row">
          <div className="form-field" style={{ flex: "0 0 110px" }}>
            <label className="form-label">Year</label>
            <input
              type="number"
              className={`form-input ${errors.year ? "has-error" : ""}`}
              value={draft.year}
              onChange={(e) => update({ year: parseInt(e.target.value) || "" })}
            />
            {errors.year && <div className="form-error">{errors.year}</div>}
          </div>
          <div className="form-field">
            <label className="form-label">Make</label>
            <input
              type="text"
              className={`form-input ${errors.make ? "has-error" : ""}`}
              value={draft.make}
              onChange={(e) => update({ make: e.target.value })}
              placeholder="e.g. Toyota"
            />
            {errors.make && <div className="form-error">{errors.make}</div>}
          </div>
          <div className="form-field">
            <label className="form-label">Model</label>
            <input
              type="text"
              className={`form-input ${errors.model ? "has-error" : ""}`}
              value={draft.model}
              onChange={(e) => update({ model: e.target.value })}
              placeholder="e.g. Corolla"
            />
            {errors.model && <div className="form-error">{errors.model}</div>}
          </div>
        </div>

        <div className="form-row">
          <div className="form-field">
            <label className="form-label">Type</label>
            <select
              className="form-input"
              value={draft.type}
              onChange={(e) => update({ type: e.target.value })}
            >
              {VEHICLE_TYPES.map((t) => (
                <option key={t} value={t}>{t}</option>
              ))}
            </select>
          </div>
          <div className="form-field">
            <label className="form-label">Transmission</label>
            <div className="segmented">
              {TRANSMISSIONS.map((t) => (
                <button
                  key={t}
                  type="button"
                  className={`seg-btn ${draft.transmission === t ? "active" : ""}`}
                  onClick={() => update({ transmission: t })}
                >
                  {t}
                </button>
              ))}
            </div>
          </div>
          <div className="form-field" style={{ flex: "0 0 140px" }}>
            <label className="form-label">License plate</label>
            <input
              type="text"
              className="form-input"
              value={draft.plate || ""}
              onChange={(e) => update({ plate: e.target.value })}
            />
          </div>
        </div>

        <div className="form-row">
          <div className="form-field" style={{ flex: "0 0 160px" }}>
            <label className="form-label">Price / day</label>
            <div className="input-with-suffix">
              <span className="input-prefix">$</span>
              <input
                type="number"
                className={`form-input ${errors.price ? "has-error" : ""}`}
                value={draft.price}
                onChange={(e) => update({ price: parseFloat(e.target.value) || "" })}
              />
              <span className="input-suffix">XCD</span>
            </div>
            {errors.price && <div className="form-error">{errors.price}</div>}
          </div>
          <div className="form-field" style={{ flex: "0 0 130px" }}>
            <label className="form-label">Passengers</label>
            <input
              type="number"
              className={`form-input ${errors.passengers ? "has-error" : ""}`}
              value={draft.passengers}
              onChange={(e) => update({ passengers: parseInt(e.target.value) || "" })}
            />
            {errors.passengers && <div className="form-error">{errors.passengers}</div>}
          </div>
          <div className="form-field" style={{ flex: "0 0 130px" }}>
            <label className="form-label">Suitcases</label>
            <input
              type="number"
              className={`form-input ${errors.suitcases ? "has-error" : ""}`}
              value={draft.suitcases}
              onChange={(e) => update({ suitcases: parseInt(e.target.value) || 0 })}
            />
            {errors.suitcases && <div className="form-error">{errors.suitcases}</div>}
          </div>
          <div className="form-field">
            <label className="form-label">Status</label>
            <select
              className="form-input"
              value={draft.status || "Available"}
              onChange={(e) => update({ status: e.target.value })}
            >
              <option>Available</option>
              <option>Maintenance</option>
              <option>Retired</option>
            </select>
          </div>
        </div>

        <div className="form-row">
          <div className="form-field" style={{ flex: 1 }}>
            <label className="form-label">Description</label>
            <textarea
              className="form-input"
              rows={5}
              value={draft.description || ""}
              onChange={(e) => update({ description: e.target.value })}
              placeholder="Notes about features, condition, ideal use, anything customer-facing…"
            />
          </div>
        </div>
      </div>

      <div className="editor-section">
        <h3 className="editor-section-title">Photos</h3>
        <PhotoManager
          photos={draft.photos || []}
          coverIndex={draft.coverIndex || 0}
          onChange={({ photos, coverIndex }) => update({ photos, coverIndex })}
        />
      </div>

      <div className="editor-actions">
        {!isNew && (
          <button
            type="button"
            className="btn-link-danger"
            onClick={() => {
              if (confirm(`Delete ${draft.year} ${draft.make} ${draft.model}? This can't be undone.`)) {
                onDelete();
              }
            }}
          >
            Delete vehicle
          </button>
        )}
        <div className="editor-actions-right">
          <button type="button" className="btn-ghost" onClick={onCancel}>Cancel</button>
          <button type="button" className="btn-primary" onClick={handleSave}>
            {isNew ? "Add vehicle" : "Save changes"}
          </button>
        </div>
      </div>
    </div>
  );
}

window.VehicleEditor = VehicleEditor;
