import React, { useEffect, useState } from "react"
import {
  Environment,
  initialize,
  showOfferByCode,
  Offer,
  proxyLogin,
  loadUserCredential,
  setPassportCloseCallback,
  UserProfile,
  getEvaluatedOffers,
} from "credify-web-sdk"
import CredifyLogo from "../../resources/credify-group-logo-title.svg"
import FullScreenLoading from "../../components/FullSceenLoading"
import { OfferItem } from "../../components/OfferItem"
import { useLocation } from "react-router-dom"
import {
  Wrapper,
  Header,
  OffersWrapper,
  LoginButton,
  LoginText,
  CredifyImage,
} from "./styled"
import Slider from "react-slick"
import "slick-carousel/slick/slick.css"
import "slick-carousel/slick/slick-theme.css"
import { NextArrow, PrevArrow } from "../../components/Arrow"
import { TEST_THEME_DEFAULT } from "./type"

const MARKET_NAME = "BaseVN"
const DEFAULT_API_KEY =
  "rij0VXCGahTHQgYWhyw0m1UkS4ouObSrXyiGKSdbXmEjmNru0ek16OgxAqEJEzn3"
const DEFAULT_MARKET_ID = "afa9083e-f064-4d05-a532-c7cf5b98a3f6"

function ProxyPage() {
  const [user, setUser] = useState<UserProfile>()
  const [offers, setOffers] = useState<Offer[]>()
  const [isLoading, setLoading] = useState<boolean>(false)
  const location = useLocation()

  const settings = {
    slidesToShow: 3,
    slidesToScroll: 1,
    infinite: false,
    responsive: [
      {
        breakpoint: 1600,
        settings: {
          infinite: true,
          slidesToShow: 2,
          slidesToScroll: 1,
        },
      },
      {
        breakpoint: 980,
        settings: {
          infinite: true,
          slidesToShow: 1,
          slidesToScroll: 1,
        },
      },
    ],
    nextArrow: <NextArrow />,
    prevArrow: <PrevArrow />,
  }

  useEffect(() => {
    const urlSearch = new URLSearchParams(location.search)
    const env = urlSearch.get("env")
    const apiKey = urlSearch.get("apiKey") || DEFAULT_API_KEY
    const marketId = urlSearch.get("marketId") || DEFAULT_MARKET_ID
    const useUICustomization = urlSearch.get("ui-customization")
    initialize(
      env as Environment,
      apiKey,
      marketId,
      useUICustomization ? TEST_THEME_DEFAULT : undefined
    )
    setPassportCloseCallback(() => {
      getOffersData()
    })
    getOffersData()
  }, [])

  async function getOffersData() {
    console.log("Market Data is loading....")
    const userData = loadUserCredential()
    setLoading(true)
    const data = await getEvaluatedOffers("", {
      phoneNumber: userData?.phoneNumber,
      countryCode: userData?.countryCode,
    })
    setOffers(data.offers)
    if (userData) {
      userData.credifyId = data.credifyId
      setUser(userData)
    }
    setLoading(false)
    console.log("Market Data finished loading....")
  }

  function loginCB() {
    proxyLogin(() => {
      getOffersData()
    })
  }

  return (
    <Wrapper>
      <Header>Offer list for you from {MARKET_NAME.toUpperCase()}</Header>
      <OffersWrapper>
        <Slider {...settings}>
          {offers?.map((item) => (
            <div>
              <OfferItem
                key={item.id}
                data={item}
                onOfferClick={() => {
                  if (item.code) {
                      showOfferByCode({
                        offerCode: item.code,
                        profile: user,
                      },
                      undefined,
                    );
                  }
                }}
              />
            </div>
          ))}
        </Slider>
      </OffersWrapper>
      {!user && (
        <LoginButton onClick={loginCB}>
          <LoginText>Login to redeem offer</LoginText>
        </LoginButton>
      )}
      <CredifyImage src={CredifyLogo} />
      <FullScreenLoading active={isLoading} text={``} />
    </Wrapper>
  )
}

export { ProxyPage }
