import React, { useState, useEffect } from 'react';

interface BadgeData {
  co2: number;
  score: number;
}

interface MeexrBadgeProps {
  siteUrl?: string;
}

const getIcon = (score: number): string => {
  if (score < 25) return "/assets/score_d.svg";
  if (score < 50) return "/assets/score_c.svg";
  if (score < 75) return "/assets/score_b.svg";
  return "/assets/score_a.svg";
};

const getColor = (score: number): string => {
  if (score < 25) return "#E5726B";
  if (score < 50) return "#F6A673";
  if (score < 75) return "#A19FE2";
  return "#68A17E";
};

const getLetter = (score: number): string => {
  if (score < 25) return "D";
  if (score < 50) return "C";
  if (score < 75) return "B";
  return "A";
};

const MeexrBadge: React.FC<MeexrBadgeProps> = ({ siteUrl = window.location.href }) => {
  const [data, setData] = useState<BadgeData | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const apiEndpoint = `https://api.meexr.fr/audits/badge-audit?brand=societech&nbVisits=1&website=${encodeURIComponent(siteUrl)}`;
        const response = await fetch(apiEndpoint);
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        console.error('Request failed:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [siteUrl]);

  if (isLoading) {
    return <div style={{ backgroundColor: "#F4F4F4", width: "fit-content", border: "2px solid black", padding: "1.5rem" }}>Loading...</div>;
  }

  if (!data) {
    return <div>No data available</div>;
  }

  return (
    <div style={{ backgroundColor: "#F4F4F4", width: "fit-content", border: "2px solid black" }}>
      <div style={{ display: "flex", flexDirection: "column", padding: "1.5rem", alignItems: "center" }}>
        <h4 style={{ fontSize: "14px", margin: 0, marginBottom: "10px", fontWeight: "normal" }}>Cette page émet</h4>
        <h4 style={{ fontSize: "18px", fontWeight: "bold", margin: 0 }}>{data.co2.toFixed(2)} g de CO2e par visite</h4>
      </div>
      <div style={{ display: "flex", flexDirection: "column", padding: "1.5rem", borderTop: "2px solid black", alignItems: "center" }}>
        <h4 style={{ fontSize: "0.875rem", margin: 0, fontWeight: "normal" }}>Le score Meexr du site est</h4>
        <div style={{ display: "flex", flexDirection: "row", marginTop: "8px" }}>
          <img src={getIcon(data.score)} alt="" style={{ margin: 0, height: "30px", width: "30px" }}/>
          <h2 style={{ fontSize: "30px", margin: 0, marginTop: "auto", marginRight: "8px", fontWeight: "bold", paddingLeft: "8px", color: getColor(data.score) }}>{getLetter(data.score)}</h2>
          <h1 style={{ fontWeight: "bold", margin: 0, marginTop: "auto", fontSize: "22px", marginBottom: "2px", color: getColor(data.score) }}>{data.score}</h1>
          <h1 style={{ fontSize: "13px", margin: 0, marginTop: "auto", fontWeight: "normal", marginBottom: "6px", color: getColor(data.score) }}>/100pts</h1>
        </div>
      </div>
    </div>
  );
};

export default MeexrBadge;



/*
import React, { useState, useEffect } from 'react';

const MeexrBadge = ({ siteUrl }) => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  const effectiveSiteUrl = siteUrl || (typeof window !== 'undefined' ? window.location.href : 'fallbackURL');

  const getIcone = (score) => {
    if (score < 25) {
      return "/assets/score_d.svg"
    }
    if (score < 50) {
      return "/assets/score_c.svg"
    }
    if (score < 75) {
      return "/assets/score_b.svg"
    }
    return "/assets/score_a.svg"
  }

  const getColor = (score) => {
    if (score < 25) {
      return "#E5726B"
    }
    if (score < 50) {
      return "#F6A673"
    }
    if (score < 75) {
      return "#A19FE2"
    }
    return "#68A17E"
  }

  const getLetter = (score) => {
    if (score < 25) {
      return "D"
    }
    if (score < 50) {
      return "C"
    }
    if (score < 75) {
      return "B"
    }
    return "A"
  }

  const sendRequest = async (url) => {
    const apiEndpoint = `https://api.meexr.fr/audits/badge-audit?brand=societech&nbVisits=1&website=${encodeURIComponent(url)}`;
    
    try {
      const response = await fetch(apiEndpoint);
      const newData = await response.json();
      setData(newData);
    } catch (error) {
      console.error('Request failed:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    sendRequest(effectiveSiteUrl);
  }, [effectiveSiteUrl]);

  if (isLoading || !data) {
    return <div style={{ backgroundColor: "#F4F4F4", width: "fit-content", border: "2px solid black", padding: "1.5rem" }}>Loading...</div>
  }

  return (
    <div style={{ backgroundColor: "#F4F4F4", width: "fit-content", border: "2px solid black" }}>
      <div style={{ display: "flex", flexDirection: "column", padding: "1.5rem", alignItems: "center" }}>
        <h4 style={{ fontSize: "14px", margin: 0, marginBottom: "10px", fontWeight: "normal" }}>Cette page émet</h4>
        <h4 style={{ fontSize: "18px", fontWeight: "bold", margin: 0 }}>{data.co2.toFixed(2)} g de CO2e par visite</h4>
      </div>
      <div style={{ display: "flex", flexDirection: "column", padding: "1.5rem", borderTop: "2px solid black", alignItems: "center" }}>
        <h4 style={{ fontSize: "0.875rem", margin: 0, fontWeight: "normal" }}>Le score Meexr du site est</h4>
        <div style={{ display: "flex", flexDirection: "row", marginTop: "8px" }}>
          <img src={getIcone(data.score)} alt="" style={{ margin: 0, height: "30px", width: "30px" }}/>
          <h2 style={{ fontSize: "30px", margin: 0, marginTop: "auto", marginRight: "8px", fontWeight: "bold", paddingLeft: "8px", color: getColor(data.score) }}>{getLetter(data.score)}</h2>
          <h1 style={{ fontWeight: "bold", margin: 0, marginTop: "auto", fontSize: "22px", marginBottom: "2px", color: getColor(data.score) }}>{data.score}</h1>
          <h1 style={{ fontSize: "13px", margin: 0, marginTop: "auto", fontWeight: "normal", marginBottom: "6px", color: getColor(data.score) }}>/100pts</h1>
        </div>
      </div>
    </div>
  );
};

export default MeexrBadge;
*/