import { useQuery } from "@tanstack/react-query";
import { useCallback, useState } from "react";

import type { HistoryResponse, TargetStatus } from "../../shared/api";

import { subtractHours } from "../utils/time";
import { fetchJson, useDashboard, useTargetMetrics } from "./use-queries";

const detailQueryKeys = {
  history: (targetId: string, from: string, to: string, page: number) => ["history", targetId, from, to, page] as const,
};

export function useTargetDetail() {
  const [selectedTargetId, setSelectedTargetId] = useState<null | string>(null);
  const [timeFrom, setTimeFrom] = useState("");
  const [timeTo, setTimeTo] = useState("");
  const [historyPage, setHistoryPage] = useState(1);
  const [activeTab, setActiveTab] = useState<string>("overview");

  const { data: dashboardData } = useDashboard(false);
  const selectedTarget =
    selectedTargetId !== null
      ? (dashboardData?.targets.find((target) => target.id === selectedTargetId) ?? null)
      : null;

  const metrics = useTargetMetrics(selectedTargetId, timeFrom, timeTo, "1h");

  const history = useQuery({
    enabled: selectedTargetId !== null && !!timeFrom && !!timeTo && activeTab === "history",
    queryFn: () => {
      if (selectedTargetId === null) throw new Error("未选择目标");
      return fetchJson<HistoryResponse>(
        `/api/targets/${selectedTargetId}/history?from=${encodeURIComponent(timeFrom)}&to=${encodeURIComponent(timeTo)}&page=${historyPage}&pageSize=20`,
      );
    },
    queryKey:
      selectedTargetId !== null && timeFrom && timeTo
        ? detailQueryKeys.history(selectedTargetId, timeFrom, timeTo, historyPage)
        : ["history", "disabled"],
  });

  const openDrawer = useCallback((target: TargetStatus) => {
    setSelectedTargetId(target.id);
    const now = new Date();
    const from = subtractHours(now, 24);
    setTimeFrom(from.toISOString());
    setTimeTo(now.toISOString());
    setHistoryPage(1);
    setActiveTab("overview");
  }, []);

  const closeDrawer = useCallback(() => {
    setSelectedTargetId(null);
    setActiveTab("overview");
  }, []);

  const handleTimeChange = useCallback((from: string, to: string) => {
    setTimeFrom(from);
    setTimeTo(to);
    setHistoryPage(1);
  }, []);

  const handlePageChange = useCallback((page: number) => {
    setHistoryPage(page);
  }, []);

  const handleTabChange = useCallback((tab: string) => {
    setActiveTab(tab);
  }, []);

  return {
    activeTab,
    closeDrawer,
    handlePageChange,
    handleTabChange,
    handleTimeChange,
    historyData: history.data ?? { items: [], page: 1, pageSize: 20, total: 0 },
    historyLoading: history.isLoading,
    metricsData: metrics.data ?? null,
    metricsLoading: metrics.isLoading,
    openDrawer,
    selectedTarget,
    timeFrom,
    timeTo,
  };
}
