import { useState } from "preact/hooks";
import type { Trip, Place } from "../../lib/types";
import type { UserLocation } from "../../lib/use-location";
import { haversineKm } from "../../lib/geo";
import { PlaceCard } from "../shared/PlaceCard";
import { getCategory } from "../../lib/categories";

export function OnRoadTab({ trip, location }: { trip: Trip; location: UserLocation | null }) {
  const [expandedIdx, setExpandedIdx] = useState<number | null>(null);

  const legOrder = (place: Place): number => {
    const leg = (place.details?.leg as string || "").toLowerCase();
    if (leg.includes("departure")) return 0;
    if (leg.includes("outbound")) return 1;
    if (leg.includes("return")) return 2;
    return 3;
  };

  const sortByRoute = (places: Place[]): Place[] =>
    [...places].sort((a, b) => {
      const la = legOrder(a);
      const lb = legOrder(b);
      if (la !== lb) return la - lb;
      const ma = (a.details?.mileFromStart as number) ?? 9999;
      const mb = (b.details?.mileFromStart as number) ?? 9999;
      return ma - mb;
    });

  const sortByDistance = (places: Place[]): Place[] => {
    if (!location) return places;
    return [...places].sort((a, b) => {
      const da = haversineKm({ lat: location.lat, lng: location.lng }, { lat: a.lat, lng: a.lng });
      const db = haversineKm({ lat: location.lat, lng: location.lng }, { lat: b.lat, lng: b.lng });
      return da - db;
    });
  };

  const fuelStops = sortByRoute(trip.places.filter(p => p.category === "fuel"));
  const restStops = sortByDistance(trip.places.filter(p => p.category === "rest-stop"));
  const cellCoverage = trip.safety.cellCoverage || [];

  const nextFuelIdx = (() => {
    if (!location || fuelStops.length === 0) return 0;
    for (let i = 0; i < fuelStops.length - 1; i++) {
      const distHere = haversineKm(
        { lat: location.lat, lng: location.lng },
        { lat: fuelStops[i].lat, lng: fuelStops[i].lng }
      );
      const distNext = haversineKm(
        { lat: location.lat, lng: location.lng },
        { lat: fuelStops[i + 1].lat, lng: fuelStops[i + 1].lng }
      );
      if (distHere <= distNext) return i;
    }
    return fuelStops.length - 1;
  })();

  const allStops = [...fuelStops, ...restStops];

  return (
    <div class="onroad-tab">
      {fuelStops.length > 0 && (
        <div class="onroad-section">
          <div class="itin-section-label">
            {getCategory("fuel").icon} Fuel Stations
          </div>
          <div class="onroad-cards">
            {fuelStops.map((place, i) => (
              <PlaceCard
                key={place.name}
                place={place}
                expanded={expandedIdx === i}
                onToggle={() => setExpandedIdx(expandedIdx === i ? null : i)}
                location={location}
                passed={nextFuelIdx >= 0 && i < nextFuelIdx}
                next={nextFuelIdx >= 0 && i === nextFuelIdx}
              />
            ))}
          </div>
        </div>
      )}

      {restStops.length > 0 && (
        <div class="onroad-section">
          <div class="itin-section-label">
            {getCategory("rest-stop").icon} Rest Stops {location && "(nearest first)"}
          </div>
          <div class="onroad-cards">
            {restStops.map((place, i) => {
              const idx = fuelStops.length + i;
              return (
                <PlaceCard
                  key={place.name}
                  place={place}
                  expanded={expandedIdx === idx}
                  onToggle={() => setExpandedIdx(expandedIdx === idx ? null : idx)}
                  location={location}
                />
              );
            })}
          </div>
        </div>
      )}

      {cellCoverage.length > 0 && (
        <div class="onroad-section">
          <div class="itin-section-label">Cell Service Along Route</div>
          <div class="cell-coverage-card">
            {cellCoverage.map((seg, i) => (
              <div key={i} class="cell-row">
                <span class="cell-segment">{seg.segment}</span>
                <span class={`cell-status cell-${seg.status}`}>
                  {seg.status === "full" ? "FULL" : seg.status === "spotty" ? "SPOTTY" : "NO SERVICE"}
                </span>
              </div>
            ))}
          </div>
        </div>
      )}

      <div class="onroad-section">
        <div class="itin-section-label">Drive Segments</div>
        {trip.days.map((day, di) => (
          day.drives.length > 0 && (
            <div key={di} class="drive-section">
              <div class="drive-day-label">{day.label}</div>
              {day.drives.map((drive, i) => (
                <div key={i} class="drive-segment-card">
                  <div class="drive-segment-route">{drive.from} <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;vertical-align:middle"><path d="M5 12h14M12 5l7 7-7 7"/></svg> {drive.to}</div>
                  <div class="drive-segment-info">
                    {drive.distance && <span class="drive-stat">{drive.distance}</span>}
                    {drive.duration && <span class="drive-stat">{drive.duration}</span>}
                  </div>
                  {drive.costs && drive.costs.length > 0 && (
                    <div class="drive-costs">
                      {drive.costs.map((c, ci) => (
                        <div key={ci} class="drive-cost-row">
                          <span>{c.item}</span>
                          <span>{c.amount}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )
        ))}
      </div>

      {allStops.length === 0 && cellCoverage.length === 0 && (
        <div class="empty-state">No road info available yet.</div>
      )}
    </div>
  );
}
