import React, { useEffect } from "react";
import { useAppStore } from "../../store/useAppStore";
import { api } from "../../api/client";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/Card";
import { Badge } from "../ui/Badge";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faCircleExclamation,
  faCircleInfo,
  faList,
  faTriangleExclamation,
} from "@fortawesome/free-solid-svg-icons";

export const LogsPanel = () => {
  const logs = useAppStore((s) => s.logs);
  const setLogs = useAppStore((s) => s.setLogs);
  const selectedHash = useAppStore((s) => s.selectedHash);
  const jobs = useAppStore((s) => s.jobs);
  const job = jobs.find((j) => j.torrentHash === selectedHash);
  const filtered = job ? logs.filter((log) => log.jobId === job.id) : logs;
  useEffect(() => {
    const loadLogs = async () => {
      if (!job) {
        setLogs([]);
        return;
      }
      try {
        const response = await api.get(`/api/loop/logs/${job.id}`);
        setLogs(response.data.logs ?? []);
      } catch (error) {
        setLogs([]);
      }
    };
    loadLogs();
  }, [job?.id, setLogs]);


  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FontAwesomeIcon icon={faList} className="text-slate-400" />
          Logs
        </CardTitle>
        <Badge variant="default">Live</Badge>
      </CardHeader>
      <CardContent>
        <div className="max-h-56 space-y-2 overflow-auto text-xs">
          {[...filtered].reverse().map((log, idx) => (
            <div
              key={`${log.createdAt}-${idx}`}
              className="rounded-md border border-slate-200 bg-white px-2 py-1"
            >
              <div className="flex items-center gap-2">
                <span className="flex items-center gap-2 font-semibold">
                  <FontAwesomeIcon
                    icon={
                      log.level === "ERROR"
                        ? faTriangleExclamation
                        : log.level === "WARN"
                        ? faCircleExclamation
                        : faCircleInfo
                    }
                    className={
                      log.level === "ERROR"
                        ? "text-rose-500"
                        : log.level === "WARN"
                        ? "text-amber-500"
                        : "text-slate-400"
                    }
                  />
                  {log.level}
                </span>
                <span className="text-slate-400">{log.createdAt}</span>
              </div>
              <div>{log.message}</div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
};
