import React, { useEffect, useCallback } from "react";
import { useState } from "react";

function debounce(func, delay) {
  let timeoutId;
  return (...args) => {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func(...args);
    }, delay);
  };
}
export default function Card() {
  const [Try, setTry] = useState();
  const [usd, setUsd] = useState(100);
  const [eur, setEur] = useState();
  const [gbp, setGbp] = useState();
  const [jpy, setJpy] = useState();
  const [currentInput, setcurrentInput] = useState();
  const [history, sethistory] = useState([]);

  const fetchData = async (changedCurrency) => {
    const body = changedCurrency || {
      TRY: Try,
      USD: usd,
      EUR: eur,
      GBP: gbp,
      JPY: jpy,
    };
    let options = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    };

    const request = await fetch(`${process.env.API_URL}/currency`, options);

    const response = await request.json();
    const historyAsJson = localStorage.getItem("history");
    const historyTemp = historyAsJson ? JSON.parse(historyAsJson) : [];

    if (historyTemp.length < 3) {
      historyTemp.push(response.items);
    } else {
      historyTemp[2] = response.items;
    }
    localStorage.setItem("history", JSON.stringify(historyTemp));
    sethistory(historyTemp);

    return response;
  };

  const onChange = async (e) => {
    const value = e.target.value;
    if (e.target.value === "") {
      setEur("");
      setUsd("");
      setTry("");
      setGbp("");
      setJpy("");
      return;
    }
    setcurrentInput(e);
    switch (e.target.name) {
      case "TRY":
        setTry(value);
        break;
      case "USD":
        setUsd(value);
        break;
      case "GBP":
        setGbp(value);
        break;
      case "JPY":
        setJpy(value);
        break;
      case "EUR":
        setEur(value);
    }
  };

  const handleInputChange = useCallback(
    debounce(async (e) => {
      if (e?.target.valueAsNumber) {
        const response = await fetchData({
          [e?.target.name]: e?.target.valueAsNumber,
        });

        switch (e?.target.name) {
          case "TRY":
            setUsd(response.items.USD);
            setEur(response.items.EUR);
            setGbp(response.items.GBP);
            setJpy(response.items.JPY);
            break;
          case "USD":
            setTry(response.items.TRY);
            setEur(response.items.EUR);
            setGbp(response.items.GBP);
            setJpy(response.items.JPY);
            break;
          case "GBP":
            setTry(response.items.TRY);
            setEur(response.items.EUR);
            setUsd(response.items.USD);
            setJpy(response.items.JPY);
            break;
          case "JPY":
            setTry(response.items.TRY);
            setEur(response.items.EUR);
            setUsd(response.items.USD);
            setGbp(response.items.GBP);
            break;
          case "EUR":
            setUsd(response.items.USD);
            setTry(response.items.TRY);
            setJpy(response.items.JPY);
            setGbp(response.items.GBP);
        }
      }
    }, 500),
    []
  );

  useEffect(() => {
    if (currentInput) handleInputChange(currentInput);
  }, [currentInput]);

  // const getCurrency = async () => {
  //   try {

  //     const request = await fetch(
  //       `${process.env.API_URL}/getPopulerCurrency`,
  //       {
  //         method: "GET",
  //         headers: {
  //           "Content-Type": "application/json",
  //         },
  //       }
  //     );
  //     const response = await request.json();
  //     setData(response.item)

  //   } catch (err) {
  //     console.log("Error:", err);
  //   }
  // }

  // useEffect(() => {
  //   setTimeout(() => {
  //     getCurrency()
  //   }, 1000);

  // }, [])

  useEffect(() => {
    fetchData().then((res) => {
      setEur(res.items.EUR);
      setJpy(res.items.JPY);
      setTry(res.items.TRY);
      setGbp(res.items.GBP);
    });
  }, []);

  return (
    <div className=" relative bg-white  hover:shadow-xl transition-all shadow-md rounded ">
      <div className="text-lg font-bold p-3">Döviz Çevirici</div>
      <div>
        <form className="w-full max-w-sm">
          <div className="md:flex md:items-center mb-3">
            <div className="md:w-1/3">
              <label className="block   text-blue-500 font-base  md:mb-0 p-3">
                ₺
              </label>
            </div>
            <div className="md:w-2/3  mr-8">
              <input
                className="appearance-none border-2 border-black rounded w-full py-2 px-4  leading-tight focus:outline-none"
                type="number"
                step="0.01"
                id="TRY"
                name="TRY"
                value={Try}
                onChange={onChange}
              />
            </div>
          </div>
          <div className="md:flex md:items-center mb-3 ">
            <div className="md:w-1/3">
              <label className="block   text-blue-500 font-base  md:mb-0 p-3">
                $
              </label>
            </div>
            <div className="md:w-2/3 mr-8">
              <input
                className="appearance-none border-2  border-black rounded w-full py-2 px-4  leading-tight focus:outline-none"
                type="number"
                step="0.01"
                id="USD"
                name="USD"
                value={usd}
                onChange={onChange}
              />
            </div>
          </div>
          <div className="md:flex md:items-center mb-3">
            <div className="md:w-1/3">
              <label className="block   text-blue-500 font-base  md:mb-0 p-3">
                €
              </label>
            </div>
            <div className="md:w-2/3 mr-8">
              <input
                className="appearance-none border-2  border-black rounded w-full py-2 px-4  leading-tight focus:outline-none"
                type="number"
                step="0.01"
                id="EUR"
                name="EUR"
                value={eur}
                onChange={onChange}
              />
            </div>
          </div>

          <div className="md:flex md:items-center mb-3">
            <div className="md:w-1/3">
              <label className="block   text-blue-500 font-base  md:mb-0 p-3">
                £
              </label>
            </div>
            <div className="md:w-2/3 mr-8">
              <input
                className="appearance-none border-2  border-black rounded w-full py-2 px-4  leading-tight focus:outline-none"
                type="number"
                step="0.01"
                id="GBP"
                name="GBP"
                value={gbp}
                onChange={onChange}
              />
            </div>
          </div>

          <div className="md:flex md:items-center mb-3">
            <div className="md:w-1/3">
              <label className="block   text-blue-500 font-base  md:mb-0 p-3">
                ¥
              </label>
            </div>
            <div className="md:w-2/3 mr-8">
              <input
                className="appearance-none border-2  border-black rounded w-full py-2 px-4  leading-tight focus:outline-none"
                type="number"
                step="0.01"
                id="JPY"
                name="JPY"
                value={jpy}
                onChange={onChange}
              />
            </div>
          </div>
          <br />
        </form>

        <div className="text-lg font-bold p-3">Popüler Aramalar</div>
        <ul className="max-full  divide-y divide-gray-200 dark:divide-gray-700  p-3">
          {history?.map((res, key) => {
            return (
              <li
                key={key}
                className="inline-flex items-center gap-x-2 py-3 text-sm font-medium text-gray-800 dark:text-white"
              >
                {Object?.entries(res)
                  .map(([key, val]) => `${val} ${key}`)
                  .join(" = ")}
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  );
}
