/* global React, Icons, Card, KPI, Topbar, Page, FARM_COORDS */
const { useState: fState, useEffect: fEffect, useRef: fRef } = React;

function hoursFromPayload(data) {
  const packs = [data?.engineHours, data?.hoursOfOperation].filter(Boolean);
  for (const pack of packs) {
    const values = pack?.values || (Array.isArray(pack) ? pack : [pack]);
    for (const item of values) {
      const v = item?.reading?.value ?? item?.value ?? item?.engineHours ?? item?.hours;
      if (v != null && Number.isFinite(Number(v))) return Number(v);
    }
  }
  return null;
}

function FleetTrack({ machineId, machineName, days, onDays }) {
  const elRef = fRef(null);
  const mapRef = fRef(null);
  const [points, setPoints] = fState([]);
  const [loading, setLoading] = fState(true);
  const [error, setError] = fState("");
  const [meta, setMeta] = fState({ distanceKm: 0, count: 0 });

  fEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError("");
      try {
        const res = await fetch(`/api/deere-fleet?view=locations&id=${encodeURIComponent(machineId)}&days=${days}`);
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || "Error de ubicación");
        if (!cancelled) {
          setPoints(data.points || []);
          setMeta({ distanceKm: data.distanceKm || 0, count: data.count || 0 });
        }
      } catch (e) {
        if (!cancelled) setError(e.message || "No se pudo cargar el track");
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [machineId, days]);

  fEffect(() => {
    if (!elRef.current || !window.L || !points.length) return;
    if (mapRef.current) {
      mapRef.current.remove();
      mapRef.current = null;
    }
    const map = window.L.map(elRef.current, {
      zoomControl: false,
      attributionControl: false,
      center: [points[0].lat, points[0].lng],
      zoom: 13,
    });
    window.L.tileLayer("https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", {
      maxZoom: 18,
    }).addTo(map);
    const latlngs = points.map((p) => [p.lat, p.lng]);
    const line = window.L.polyline(latlngs, { color: "#c6e84b", weight: 3 }).addTo(map);
    window.L.circleMarker(latlngs[latlngs.length - 1], { radius: 7, color: "#2d3122", fillColor: "#c6e84b", fillOpacity: 1, weight: 2 }).addTo(map);
    map.fitBounds(line.getBounds().pad(0.2));
    mapRef.current = map;
    setTimeout(() => map.invalidateSize(), 80);
    return () => {
      map.remove();
      mapRef.current = null;
    };
  }, [points]);

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
        <div style={{ fontSize: 13.5, color: "var(--muted)" }}>Track GPS · {machineName}</div>
        <select value={days} onChange={(e) => onDays(Number(e.target.value))}
          style={{ fontFamily: "Onest", fontSize: 12.5, border: "1px solid rgba(0,0,0,0.08)", background: "#f5f5ef", borderRadius: 10, padding: "6px 10px" }}>
          <option value={1}>1 día</option>
          <option value={3}>3 días</option>
          <option value={7}>7 días</option>
          <option value={14}>14 días</option>
        </select>
      </div>
      {loading && <div style={{ fontSize: 13.5, color: "var(--muted)", padding: "28px 0", textAlign: "center" }}>Cargando puntos…</div>}
      {error && <div style={{ fontSize: 13.5, color: "#c0492f" }}>{error}</div>}
      {!loading && !error && points.length === 0 && (
        <div style={{ fontSize: 13.5, color: "var(--muted)", padding: "20px 0" }}>
          Sin GPS en este período. En sandbox muchas máquinas no tienen JDLink.
        </div>
      )}
      <div ref={elRef} style={{ height: points.length ? 280 : 0, borderRadius: 16, overflow: "hidden" }} />
      {points.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10, marginTop: 12 }}>
          <div><div style={{ fontSize: 11.5, color: "var(--muted)" }}>Puntos</div><b>{meta.count}</b></div>
          <div><div style={{ fontSize: 11.5, color: "var(--muted)" }}>Distancia est.</div><b>{meta.distanceKm} km</b></div>
          <div><div style={{ fontSize: 11.5, color: "var(--muted)" }}>ha/h</div><span style={{ fontSize: 12.5, color: "var(--muted)" }}>Field Ops (ag1) después</span></div>
        </div>
      )}
    </div>
  );
}

function MachineRow({ machine }) {
  const [panel, setPanel] = fState(null);
  const [loading, setLoading] = fState(false);
  const [hours, setHours] = fState(null);
  const [alerts, setAlerts] = fState(null);
  const [error, setError] = fState("");
  const [days, setDays] = fState(7);
  const id = machine.id;

  async function load(kind) {
    setPanel(kind);
    setError("");
    if (kind === "track") return;
    setLoading(true);
    try {
      const res = await fetch(`/api/deere-fleet?view=${kind}&id=${encodeURIComponent(id)}`);
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Error");
      if (kind === "hours") setHours(data);
      if (kind === "alerts") setAlerts(data);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }

  const hoursVal = hoursFromPayload(hours);
  const alertList = Array.isArray(alerts?.alerts) ? alerts.alerts : [];

  return (
    <Card>
      <div style={{ display: "flex", justifyContent: "space-between", gap: 14, alignItems: "flex-start" }}>
        <div style={{ display: "flex", gap: 12, minWidth: 0 }}>
          <div style={{ width: 42, height: 42, borderRadius: 12, background: "#eceede", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}>
            <Icons.truck size={20} />
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 16, fontWeight: 700 }}>{machine.name}</div>
            <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 3 }}>
              {machine.make}{machine.model ? ` · ${machine.model}` : ""}{machine.category ? ` · ${machine.category}` : ""}
            </div>
            {machine.serialNumber && <div style={{ fontSize: 11.5, color: "var(--muted-2)", marginTop: 2 }}>SN {machine.serialNumber}</div>}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 14 }}>
        <button className="pill" onClick={() => load("hours")} style={{ border: "none", cursor: "pointer", fontFamily: "Onest", fontWeight: 600, fontSize: 12.5, padding: "8px 12px" }}>
          <Icons.clock size={14} /> Horas motor
        </button>
        <button className="pill" onClick={() => load("alerts")} style={{ border: "none", cursor: "pointer", fontFamily: "Onest", fontWeight: 600, fontSize: 12.5, padding: "8px 12px" }}>
          <Icons.alert size={14} /> Alertas
        </button>
        <button className="pill" onClick={() => load("track")} style={{ border: "none", cursor: "pointer", fontFamily: "Onest", fontWeight: 600, fontSize: 12.5, padding: "8px 12px" }}>
          <Icons.map size={14} /> Track / campo
        </button>
      </div>

      {panel && (
        <div style={{ marginTop: 16, paddingTop: 14, borderTop: "1px solid rgba(0,0,0,0.06)" }}>
          {loading && <div style={{ fontSize: 13.5, color: "var(--muted)" }}>Cargando…</div>}
          {error && <div style={{ fontSize: 13.5, color: "#c0492f" }}>{error}</div>}
          {panel === "hours" && !loading && hours && (
            hoursVal != null ? (
              <div>
                <div style={{ fontSize: 12, color: "var(--muted)" }}>Engine hours</div>
                <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.02em" }}>{hoursVal.toLocaleString("es-AR")} <span style={{ fontSize: 14, color: "var(--muted)" }}>h</span></div>
                {(hours.engineHoursError || hours.hoursOfOpError) && (
                  <div style={{ fontSize: 12, color: "#b58a16", marginTop: 6 }}>{hours.engineHoursError || hours.hoursOfOpError}</div>
                )}
              </div>
            ) : (
              <div style={{ fontSize: 13.5, color: "var(--muted)" }}>Sin horas. Hace falta JDLink y scope eq1.</div>
            )
          )}
          {panel === "alerts" && !loading && (
            alertList.length === 0 ? (
              <div style={{ fontSize: 13.5, color: "var(--muted)" }}>Sin alertas activas (o no disponibles en sandbox).</div>
            ) : alertList.map((a, i) => (
              <div key={i} style={{ padding: "10px 0", borderBottom: "1px solid rgba(0,0,0,0.05)" }}>
                <div style={{ fontWeight: 700, fontSize: 13.5 }}>{a.code || a.alertCode || a.name || `Alerta ${i + 1}`}</div>
                <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 3 }}>{a.description || a.message || ""}</div>
              </div>
            ))
          )}
          {panel === "track" && id && (
            <FleetTrack machineId={id} machineName={machine.name} days={days} onDays={setDays} />
          )}
        </div>
      )}
    </Card>
  );
}

function FleetTab() {
  const [data, setData] = fState(null);
  const [error, setError] = fState("");
  const [q, setQ] = fState("");

  fEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch("/api/deere-fleet?view=fleet");
        const json = await res.json();
        if (!res.ok) throw new Error(json.error || "No se pudo leer la flota");
        if (!cancelled) {
          setData(json);
          window.__JD_FLEET = json;
        }
      } catch (e) {
        if (!cancelled) setError(e.message);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const equipment = (data?.equipment || []).filter((m) => {
    const s = q.trim().toLowerCase();
    if (!s) return true;
    return `${m.name} ${m.model} ${m.category} ${m.serialNumber}`.toLowerCase().includes(s);
  });
  const orgs = data?.organizations || [];
  const connected = !!data?.connected;
  const connectHref = "/api/deere?connect=1";

  return (
    <Page>
      <Topbar
        title="Flota"
        subtitle={connected ? "John Deere Operations Center · JDLink" : "Demo Córdoba · conectá Operations Center para JDLink real"}
        range={connected ? "Conectado" : "Demo"}
        onSearch={setQ}
        searchPlaceholder="Buscar máquina…"
      />

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 18 }}>
        <KPI icon={Icons.truck} label="Máquinas" value={String(data?.equipment?.length ?? "—")} />
        <KPI icon={Icons.layers} label="Organizaciones" value={String(orgs.length || "—")} />
        <KPI icon={Icons.alert} label="Estado" value={connected ? "JD" : "Demo"} />
        <KPI icon={Icons.map} label="Campo" value="Quebracho" />
      </div>

      {!connected && (
        <Card style={{ marginBottom: 18 }} title="Conectar John Deere" sub="El Client ID es de PampaGo. El productor entra con su Operations Center."
          action={<a href={connectHref} className="btn-lime" style={{ textDecoration: "none", padding: "10px 16px", borderRadius: 999, fontSize: 13.5, fontWeight: 700 }}>Conectar Operations Center</a>}>
          <p style={{ fontSize: 14, color: "var(--muted)", lineHeight: 1.5, maxWidth: 640 }}>
            Esta pestaña vive en Harvest. El login vuelve a <code>jd.pampago.xyz/callback</code>.
            Marketplace (pampago.xyz) no entra todavía: primero horas, alertas y GPS acá.
          </p>
        </Card>
      )}

      {data?.connectionsUrl && (
        <Card style={{ marginBottom: 18 }} title="Falta elegir organizaciones" sub="John Deere pide que habilites qué orgs ve PampaGo."
          action={<a href={data.connectionsUrl} className="btn-lime" style={{ textDecoration: "none", padding: "10px 16px", borderRadius: 999, fontSize: 13.5, fontWeight: 700 }}>Seleccionar orgs</a>} />
      )}

      {error && <Card style={{ marginBottom: 18 }}><div style={{ color: "#c0492f" }}>{error}</div></Card>}

      {orgs.length > 0 && (
        <Card title="Organizaciones" sub={`${orgs.length} en esta sesión`} style={{ marginBottom: 18 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {orgs.map((o) => (
              <div key={o.id} style={{ background: "#eceede", borderRadius: 14, padding: "12px 14px" }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{o.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 3 }}>{o.type} · {o.id}</div>
              </div>
            ))}
          </div>
        </Card>
      )}

      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {equipment.map((m) => <MachineRow key={m.id} machine={m} />)}
        {data && equipment.length === 0 && (
          <Card>
            <div style={{ fontSize: 14, color: "var(--muted)" }}>
              No hay máquinas. En sandbox a menudo no hay JDLink; con una cuenta real de Operations Center sí aparecen.
            </div>
          </Card>
        )}
      </div>
    </Page>
  );
}

window.FleetTab = FleetTab;
