import { useState, useEffect } from "preact/hooks";
import type { Trip } from "../lib/types";
import { downloadTripOffline, isOfflineReady, clearOfflineData, type DownloadProgress } from "../lib/offline";

export function OfflineButton({ trip }: { trip: Trip }) {
  const [ready, setReady] = useState<boolean | null>(null);
  const [online, setOnline] = useState(navigator.onLine);
  const [downloading, setDownloading] = useState(false);
  const [progress, setProgress] = useState<DownloadProgress | null>(null);
  const [result, setResult] = useState<string | null>(null);

  useEffect(() => {
    isOfflineReady(trip.id).then(setReady);
    const goOnline = () => setOnline(true);
    const goOffline = () => setOnline(false);
    window.addEventListener("online", goOnline);
    window.addEventListener("offline", goOffline);
    return () => {
      window.removeEventListener("online", goOnline);
      window.removeEventListener("offline", goOffline);
    };
  }, [trip.id]);

  const download = async () => {
    setDownloading(true);
    setResult(null);
    try {
      const r = await downloadTripOffline(trip, setProgress);
      setReady(true);
      setResult(`Cached ${r.tileCount} map tiles. Ready for offline.`);
    } catch (e: any) {
      setResult(`Error: ${e.message}`);
    }
    setDownloading(false);
    setProgress(null);
  };

  const clear = async () => {
    await clearOfflineData();
    setReady(false);
    setResult(null);
  };

  if (ready === null) return null;

  return (
    <div class="offline-bar">
      {downloading && progress ? (
        <div class="offline-progress">
          <div class="offline-progress-label">
            {progress.phase === "data" ? "Saving trip data..." :
             progress.phase === "assets" ? `Caching page assets (${progress.done}/${progress.total})` :
             `Caching map tiles (${progress.done}/${progress.total})`}
          </div>
          <div class="offline-progress-track">
            <div
              class="offline-progress-fill"
              style={{ width: `${Math.round((progress.done / Math.max(progress.total, 1)) * 100)}%` }}
            />
          </div>
        </div>
      ) : (
        <div class="offline-actions">
          {ready ? (
            <>
              <span class="offline-ready">{online ? "Offline ready" : "Offline mode"}</span>
              {online && <button class="offline-btn offline-refresh" onClick={download}>Refresh</button>}
              {online && <button class="offline-btn offline-clear" onClick={clear}>Clear</button>}
            </>
          ) : online ? (
            <button class="offline-btn offline-download" onClick={download}>
              Download for Offline
            </button>
          ) : null}
        </div>
      )}
      {result && <div class="offline-result">{result}</div>}
    </div>
  );
}
