import { useEffect, useState } from "react";
import { LinkGroup } from "./App";
import type { ApiError, LinkInterface } from "./types";

export const CastesLinks = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [links, setLinks] = useState<LinkInterface[]>([]);
  const castesLinks = [
    { name: "GPAO", link: "http://gpao.lan" },
    { name: "Penpot", link: "https://penpot.castes-industrie.fr" },
    { name: "Schema", link: "http://schemas.castes-industrie.fr/" },
  ];

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

  const testConnection = async () => {
    try {
      const res = await fetch("http://gpao.lan", { method: "HEAD" });
      console.log(res);
      if (res.ok) {
        setLinks(castesLinks);
      }
      console.log("link", res);
    } catch (error: Error | ApiError | unknown) {
      console.log(error);
      if (error instanceof Error) {
        console.error(error.message);
      } else {
        setError((error as ApiError).error);
      }
    } finally {
      setLoading(false);
    }
  };
  return loading ? (
    <div>Chargement...</div>
  ) : (
    <>
      <div>Casty</div>
      {error && (
        <div className="text-white px-2 text-center py-1 mx-5 bg-red-500 rounded">
          {error}
        </div>
      )}
      <LinkGroup title="Castes" links={links} />
    </>
  );
};
