import React, { useState, useEffect } from 'react';
import {
  RestaurantListHeader,
  RestaurantCard,
  RestaurantBlankCard,
  RestaurantListSkeleton,
} from './Restaurant-list';
import styled from 'styled-components';
import { fetchAPI } from 'utils/fetchAPI';
import { RESTAURANTS } from 'containers/App/urls';
import { USER_INFO_KEY } from 'containers/App/constants';
import { getSearchParamValueByParams } from 'utils/searchParams';
import { useHistory } from 'react-router-dom';
import { MOBILE_BREAK_POINT, TABLET_BREAK_POINT } from 'styles/constants';

const RestaurantListWrapper = styled.div`
  padding: 20px;
  .list {
    display: flex;
    flex-wrap: wrap;
    padding-left: 0;
    .card {
      list-style: none;
      flex: 0 0 33.333333%;
      padding: 10px;
    }
  }
  .default-menu {
    border: 1px solid #c7c7c7;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    text-align: center;
    padding-top: 5px;
    margin-right: 15px;
  }
  @media only screen and (max-width: ${TABLET_BREAK_POINT}px) {
    .list {
      .card {
        flex: 0 0 50%;
      }
    }
  }
  @media only screen and (max-width: ${MOBILE_BREAK_POINT}px) {
    .list {
      .card {
        flex: 0 0 100%;
      }
    }
  }
`;

export function RestaurantList(props) {
  const [loading, setLoading] = useState(true);
  const [restaurantList, setRestaurantList] = useState([]);
  const history = useHistory();
  const userInfoString = localStorage.getItem(USER_INFO_KEY);
  const userInfo = JSON.parse(userInfoString!);
  const { merchantId } = userInfo.profile!;
  const getRestaurants = async (searchText?: string) => {
    try {
      const url = searchText
        ? `${RESTAURANTS}?merchantId=${merchantId}&searchText=${searchText}`
        : `${RESTAURANTS}?merchantId=${merchantId}`;
      const response = await fetchAPI({
        method: 'GET',
        url,
      });
      if (response) {
        setRestaurantList(response);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const defaultSearchText = getSearchParamValueByParams(
      history.location.search,
      'searchText',
    );
    getRestaurants(defaultSearchText);
  }, []);

  return (
    <RestaurantListWrapper>
      <RestaurantListHeader getRestaurants={getRestaurants} />
      <div className="list">
        <div className="card">
          <RestaurantBlankCard getRestaurants={getRestaurants} />
        </div>
        {!loading ? (
          restaurantList.reverse().map(restaurant => (
            <div className="card">
              <RestaurantCard
                restaurant={restaurant}
                getRestaurants={getRestaurants}
              />
            </div>
          ))
        ) : (
          <>{RestaurantListSkeleton()}</>
        )}
      </div>
    </RestaurantListWrapper>
  );
}
