import { useState } from "react";
import { Link } from "react-router-dom";
import { manualPoll, updateTracker, removeTracker } from "../../lib/api";
import type { WatchedTracker } from "../../lib/types";
import ConfirmModal from "../ui/ConfirmModal";
import { buttonClass, cardContentClass } from "../ui/primitives";

interface Props {
  trackers: WatchedTracker[];
  projectId: string;
  onRefresh: () => void;
}

export default function TrackerList({ trackers, projectId, onRefresh }: Props) {
  const [pollingIds, setPollingIds] = useState<string[]>([]);
  const [trackerToRemove, setTrackerToRemove] = useState<WatchedTracker | null>(null);

  async function handlePollNow(tracker: WatchedTracker) {
    if (tracker.status !== "valid") {
      return;
    }
    try {
      setPollingIds((prev) => [...prev, tracker.id]);
      await manualPoll(tracker.id);
      onRefresh();
    } catch (err) {
      console.error("Poll failed:", err);
    } finally {
      setPollingIds((prev) => prev.filter((id) => id !== tracker.id));
    }
  }

  async function handleToggleEnabled(tracker: WatchedTracker) {
    try {
      await updateTracker(
        tracker.id,
        tracker.tracker_id,
        tracker.tracker_label,
        tracker.polling_interval,
        tracker.analyst_agent_id ?? "",
        tracker.developer_agent_id ?? "",
        tracker.reviewer_agent_id ?? "",
        tracker.filters,
        !tracker.enabled
      );
      onRefresh();
    } catch (err) {
      console.error("Update failed:", err);
    }
  }

  async function handleConfirmRemove() {
    if (!trackerToRemove) return;
    const tracker = trackerToRemove;
    setTrackerToRemove(null);
    try {
      await removeTracker(tracker.id);
      onRefresh();
    } catch (err) {
      console.error("Remove failed:", err);
    }
  }

  return (
    <div className="space-y-3">
      {trackers.length === 0 && (
        <div className="text-sm text-gray-400">No trackers configured.</div>
      )}

      {trackers.map((tracker) => (
        <div
          key={tracker.id}
          className={`flex items-center justify-between gap-4 ${cardContentClass}`}
        >
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <span className="font-medium text-sm">{tracker.tracker_label}</span>
              <span className="text-xs text-gray-400">#{tracker.tracker_id}</span>
              <span
                className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                  tracker.status === "invalid"
                    ? "bg-red-100 text-red-700"
                    : tracker.enabled
                    ? "bg-green-100 text-green-700"
                    : "bg-gray-100 text-gray-500"
                }`}
              >
                {tracker.status === "invalid" ? "Invalid" : tracker.enabled ? "Active" : "Paused"}
              </span>
            </div>
            <div className="text-xs text-gray-400 mt-1">
              {tracker.last_polled_at
                ? `Last poll: ${new Date(tracker.last_polled_at).toLocaleString()}`
                : "Never polled"}
            </div>
          </div>

          <div className="flex items-center gap-2 shrink-0">
            <button
              type="button"
              onClick={() => handlePollNow(tracker)}
              disabled={pollingIds.includes(tracker.id) || tracker.status !== "valid"}
              className={buttonClass({ variant: "primary", size: "xs" })}
            >
              {pollingIds.includes(tracker.id) ? "Polling..." : "Poll now"}
            </button>
            <Link
              to={`/projects/${projectId}/trackers/${tracker.id}/edit`}
              className={buttonClass({ variant: "secondary", size: "xs" })}
            >
              Edit
            </Link>
            <button
              type="button"
              onClick={() => handleToggleEnabled(tracker)}
              disabled={tracker.status !== "valid"}
              className={buttonClass({ variant: "secondary", size: "xs" })}
            >
              {tracker.enabled ? "Pause" : "Resume"}
            </button>
            <button
              type="button"
              onClick={() => setTrackerToRemove(tracker)}
              className={buttonClass({ variant: "dangerSoft", size: "xs" })}
            >
              Remove
            </button>
          </div>
        </div>
      ))}

      <Link
        to={`/projects/${projectId}/trackers/new`}
        className={buttonClass({ variant: "primary" })}
      >
        Add tracker
      </Link>

      <ConfirmModal
        isOpen={trackerToRemove !== null}
        onCancel={() => setTrackerToRemove(null)}
        onConfirm={() => void handleConfirmRemove()}
      />
    </div>
  );
}
