text: /* eslint-disable react-hooks/exhaustive-deps */
  import axios from "axios";
  import NavBar2 from "../components/NavBar2";
  import { useEffect, useState } from "react";
  import { logoutAdmin, loginAdmin, addtoBasket } from "../actions/index";
  import Footer from "../components/Footer";
  import { connect } from "react-redux";
  import { Link } from "react-router-dom";
  import LogoBeyaz from "../styles/Logobeyaz.jpg";
  import Warning from "../components/PaymnetWarning";
  
  const mapStateToProps = (state) => {
    const {
      email,
      password,
      password_confirmation,
      uid,
      client,
      access_token,
    } = state.createAdminReducer.admin;
  
    const { items_ids, user_id } = state.createBasketReducer.basket;
  
    const { isLoggedIn } = state.createAdminReducer;
  
    return {
      email,
      password,
      password_confirmation,
      isLoggedIn,
      uid,
      client,
      access_token,
      items_ids,
      user_id,
    };
  };
  
  const mapDispatchToProps = (dispatch) => ({
    loginAdminFromComponent: (admin) => dispatch(loginAdmin(admin)),
    logoutAdminFromComponent: (admin) => dispatch(logoutAdmin(admin)),
    addtoBasketFromComponent: (basket) => dispatch(addtoBasket(basket)),
  });
  
  const Item = (props) => {
    const [Item, setItem] = useState([]);
    let responseVar = null;
  
    const [userId, setUserId] = useState(null);
    const [itemId, setItemId] = useState([]);
    const [Image, setImage] = useState([]);
    const [selectedImage, setSelectedImage] = useState(null);
    const [selectedIndex, setSelectedIndex] = useState(0);
  
    const checkLoginStatus = () => {
      if (JSON.parse(localStorage.getItem("eycUser"))) {
        axios
          .get("https://eyc-api.herokuapp.com/v1/auth_user/validate_token", {
            headers: {
              uid: JSON.parse(localStorage.getItem("eycUser")).myUid,
              client: JSON.parse(localStorage.getItem("eycUser")).myClient,
              "access-token": JSON.parse(localStorage.getItem("eycUser"))
                .myAccessToken,
            },
          })
          .then((response) => {
            setUserId(response.data.data.id);
            if (response.data.success && !props.isLoggedIn) {
              props.loginAdminFromComponent({
                admin: {
                  email: response.data.data.email,
                  password: props.password,
                  id: JSON.parse(localStorage.getItem("eycUser")).myResponse.id,
                },
              });
            }
          })
          .catch((error) => {
            console.log(error);
          });
      }
    };
  
    const getItem = () => {
      axios
        .get(`https://eyc-api.herokuapp.com/items/${props.match.params.id}`, {})
        .then((response) => {
          if (response.status === 200) {
            setItem(response.data);
            setItemId(response.data.id);
            setImage(response.data.image);
          }
        });
    };
  
    useEffect(() => {
      getItem();
      checkLoginStatus();
    }, []);
  
    const handleLogOut = () => {
      axios
        .delete("https://eyc-api.herokuapp.com/v1/auth_user/sign_out", {
          headers: {
            uid: JSON.parse(localStorage.getItem("eycUser")).myUid,
            client: JSON.parse(localStorage.getItem("eycUser")).myClient,
            "access-token": JSON.parse(localStorage.getItem("eycUser"))
              .myAccessToken,
          },
        })
        .then(() => props.logoutAdminFromComponent())
        .then(() => props.history.push("/"))
        .catch((error) => {
          responseVar = error.response.statusText;
          setTimeout(() => {
            alert(responseVar);
          }, 500);
        });
    };
  
    const discountCreator = (element) => {
      if (
        element.discount_percentage === null ||
        element.discount_percentage === 0
      ) {
        return null;
      }
      return <span className="span">-{element.discount_percentage} %</span>;
    };
  
    const handleAddToBasket = () => {
      props.addtoBasketFromComponent({
        basket: {
          user_id: userId,
          items_ids: itemId,
          value: Item.value,
        },
      });
    };
  
    const buttonCreator = (item) => {
      if (props.isLoggedIn) {
        if (item.stock_amount > 0) {
          return (
            <button
          className="btn btn-success"
          onClick={() => handleAddToBasket()}
        >
          Sepete Ekle
        </button>
          )
        } else if (item.stock_amount <= 0) {
         return (
          <button
          className="btn btn-success disabled"
        >
          Sepete Ekle
        </button>
         )
        }
     } else {
        return (
          <p className="font-weight-bold text-danger">
          Alışveriş yapmak için giriş yapınız!
        </p>
        )
     }
    }
    let ImageKey = -1;
    return (
      <div className="text-center h-100 d-flex flex-column">
        <NavBar2 />
        <Warning />
        <div>
          <Link to="/">
            <img src={LogoBeyaz} alt="logo" className="logo-2" />
          </Link>
        </div>
        {Image.length > 1 ? (
          <div className="d-flex flex-wrap justify-content-center align-items-center">
            {" "}
            <div className="col-md-1 col-3 mx-3 card shadow-lg py-4">
              {Image.map((oneImage, index) => {
                const myClassName =
                  index === selectedIndex
                    ? "img-fluid rounded mb-3 normal-opacity"
                    : "img-fluid rounded mb-3 decreased-opacity";
                ImageKey += 1;
                return (
                  <img
                    name={ImageKey}
                    key={ImageKey}
                    src={oneImage}
                    alt={Item.group}
                    className={myClassName}
                    onClick={(event) => {
                      console.log(event.target.name);
                      setSelectedImage(event.target.src);
                      setSelectedIndex(index);
                    }}
                  />
                );
              })}
            </div>
            <div className="col-7 col-md-4 card p-4 shadow-lg mb-4 h-100">
              {discountCreator(Item)}
              {selectedImage === null ? (
                <img
                  src={Image[0]}
                  alt={Item.group}
                  className="img-fluid rounded"
                />
              ) : (
                <img
                  src={selectedImage}
                  alt={Item.group}
                  className="img-fluid rounded"
                />
              )}{" "}
              <div>{Item.name}</div>
              
            </div>
            <div className="col-md-3 col-12 mx-auto mt-2">
              <p>
                <b>Açıklama: {Item.details}</b>
              </p>
              <p>
                <b>Fiyat: {Item.value} ₺</b>
              </p>
              <p>
                <b>Kalan son {Item.stock_amount} adet ürün</b>
              </p>
              {Item.size ? 
              <p>
              <b>Beden: {Item.size}</b>
            </p>: null}
            </div>
            <div className="col-md-3 col-8 mx-auto mb-2">
                {buttonCreator(Item)}
              </div>
          </div>
        ) : (
          <div className="col-md-8 col-10 mx-auto py-4 d-flex flex-wrap align-items-center">
            <div className="card shadow-lg p-3 col-md-5 col-12">
              {discountCreator(Item)}
              <img src={Image} alt={Item.group} className="img-fluid rounded" />
              <div>{Item.name}</div>
            </div>
            <div className="col-md-3 col-12 mx-auto mt-2">
              <p>
                <b>Açıklama: {Item.details}</b>
              </p>
              <p>
                <b>Fiyat: {Item.value} ₺</b>
              </p>
              <p>
                <b>Kalan son {Item.stock_amount} adet ürün</b>
              </p>
              {Item.size ? 
              <p>
              <b>Beden: {Item.size}</b>
            </p>: null}
            </div>
            <div className="col-md-3 col-8 mx-auto">
              {props.isLoggedIn ? (
                <button
                  className="btn btn-success"
                  onClick={() => handleAddToBasket()}
                >
                  Sepete Ekle
                </button>
              ) : (
                <p className="font-weight-bold text-danger">
                  Alışveriş yapmak için giriş yapınız!
                </p>
              )}
            </div>
          </div>
        )}
        <div className="mb-3">
          {props.isLoggedIn ? (
            <button
              type="button"
              className="button btn btn-danger"
              onClick={handleLogOut}
            >
              Çıkış
            </button>
          ) : null}
        </div>
        <Footer />
      </div>
    );
  };
  
  export default connect(mapStateToProps, mapDispatchToProps)(Item);
  