import { useToastStore } from "@/store/useToastStore";
import { getLogs, clearLogs } from "@/api/modules/logs";
import { BrushCleaning, Loader, RefreshCw } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Button, Card } from "@/components/ui";

export default function AppLogs() {
  const [logs, setLogs] = useState("");
  const [loading, setLoading] = useState(false);
  const { success, error } = useToastStore();

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const resp = await getLogs();
      const text =
        resp && typeof resp === "object" && "text" in resp
          ? resp.text
          : String(resp ?? "");
      setLogs(text);
    } catch (e) {
      error(`Failed to load logs ${e?.message ?? String(e)}`);
      setLogs(""); // Clear logs on error
    } finally {
      setLoading(false);
    }
  }, [error]);

  async function handleClearLogs() {
    setLoading(true);
    try {
      await clearLogs();
      success("Logs", "Application logs have been cleared successfully.");
      await load();
    } catch (e) {
      error(`Failed to clear logs ${e?.message ?? String(e)}`);
      setLoading(false);
    }
  }

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

  return (
    <Card
      title="Application Logs"
      className="bg-base-200"
      headerClass="p-4"
      bodyClass="border-t-1 p-0"
      actions={
        <>
          <Button
            onClick={load}
            className="btn btn-info btn-sm"
            disabled={loading}
          >
            {loading ? (
              <Loader className="animate-spin" size={16} />
            ) : (
              <RefreshCw size={16} />
            )}
          </Button>
          <Button
            onClick={handleClearLogs}
            className="btn btn-error btn-sm"
            disabled={loading}
          >
            <BrushCleaning size={16} />
          </Button>
        </>
      }
    >
      <pre className="bg-base-300 p-2 rounded overflow-auto text-xs whitespace-pre-wrap max-h-[calc(100vh-20rem)]">
        {logs || "(no logs yet)"}
      </pre>
    </Card>
  );
}
