import { useEffect, useMemo, useState } from "react";
import { ActivityIndicator, Button, Text, View } from "react-native";
import { createSilentCronXClient, type JobRecord, type TriggerJobRequest } from "silent-cronx";

const API_BASE_URL = "http://localhost:4517";

type OfflineItem = {
  route: string;
  request: TriggerJobRequest;
};

export function SilentCronXJobScreen() {
  const client = useMemo(() => createSilentCronXClient({ baseUrl: API_BASE_URL }), []);
  const [loading, setLoading] = useState(false);
  const [jobId, setJobId] = useState<string | null>(null);
  const [job, setJob] = useState<JobRecord | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [offlineQueue, setOfflineQueue] = useState<OfflineItem[]>([]);

  async function triggerReport() {
    const request: TriggerJobRequest = {
      payload: { reportType: "mobile-daily" },
      priority: 10,
    };
    setLoading(true);
    setError(null);
    try {
      const response = await client.triggerJob("report", request);
      setJobId(response.jobId);
    } catch (caught) {
      setOfflineQueue((items) => [...items, { route: "report", request }]);
      setError(caught instanceof Error ? caught.message : "Saved locally and will retry from this screen");
    } finally {
      setLoading(false);
    }
  }

  async function flushOfflineQueue() {
    const pending = [...offlineQueue];
    setOfflineQueue([]);
    for (const item of pending) {
      try {
        const response = await client.triggerJob(item.route, item.request);
        setJobId(response.jobId);
      } catch {
        setOfflineQueue((items) => [...items, item]);
      }
    }
  }

  useEffect(() => {
    if (!jobId) return;
    const timer = setInterval(() => {
      void client.getJob(jobId).then(setJob);
    }, 1000);
    return () => clearInterval(timer);
  }, [client, jobId]);

  return (
    <View>
      <Button title="Start SilentCronX Job" onPress={triggerReport} disabled={loading} />
      <Button title="Retry Offline Jobs" onPress={flushOfflineQueue} disabled={offlineQueue.length === 0} />
      {loading ? <ActivityIndicator /> : null}
      {jobId ? <Text>Job queued: {jobId}</Text> : null}
      {job?.progress ? <Text>Progress: {job.progress.percent ?? 0}% {job.progress.message ?? ""}</Text> : null}
      {job ? <Text>Status: {job.status}</Text> : null}
      {offlineQueue.length > 0 ? <Text>Offline queue: {offlineQueue.length}</Text> : null}
      {error ? <Text>{error}</Text> : null}
    </View>
  );
}
