import { useCallback, useEffect, useState } from "react";
import type { FC, ChangeEvent } from "react";
import { traceApi } from "../../api/traceApi";
import styles from "./TopBar.module.css";

interface TopBarProps {
  onTraceSelect: (traceId: string) => void;
}

export const TopBar: FC<TopBarProps> = ({ onTraceSelect }) => {
  const [statusFilter, setStatusFilter] = useState<"running" | "completed" | "failed" | "">("");
  const [title, setTitle] = useState("流程图可视化系统");
  const [loading, setLoading] = useState(false);

  const loadTraces = useCallback(
    async (status?: string) => {
      setLoading(true);
      try {
        const data = await traceApi.fetchTraces({
          status: status || undefined,
          limit: 20,
        });
        const firstTrace = data.traces[0];
        if (firstTrace) {
          setTitle(firstTrace.task);
          onTraceSelect(firstTrace.trace_id);
        } else {
          setTitle("流程图可视化系统");
          onTraceSelect("");
        }
      } catch (error) {
        console.error("Failed to load traces:", error);
      } finally {
        setLoading(false);
      }
    },
    [onTraceSelect],
  );

  const handleStatusChange = (status: string) => {
    const value = status as "running" | "completed" | "failed" | "";
    setStatusFilter(value);
    loadTraces(value);
  };

  useEffect(() => {
    loadTraces();
  }, [loadTraces]);

  return (
    <header className={styles.topbar}>
      <div className={styles.title}>
        <h1>{title}</h1>
      </div>
      <div className={styles.filters}>
        <select
          value={statusFilter}
          onChange={(e: ChangeEvent<HTMLSelectElement>) => handleStatusChange(e.target.value)}
          className={styles.select}
          disabled={loading}
        >
          <option value="">全部状态</option>
          <option value="running">运行中</option>
          <option value="completed">已完成</option>
          <option value="failed">失败</option>
        </select>
        {/* <button
          onClick={() => loadTraces(statusFilter)}
          className={styles.button}
          disabled={loading}
        >
          {loading ? "加载中..." : "刷新"}
        </button> */}
      </div>
    </header>
  );
};
