import React, { useEffect, useRef, useState } from "react"
import {
  Environment,
  initialize,
  Offer,
  PRODUCT_TYPE,
  setPassportCloseCallback,
  showOfferByCode,
  showPromotionOffersByCodes,
  startServiceInstanceFlow,
  UserProfile
} from "credify-web-sdk"
import styled from "styled-components"
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 { getMarketApiUrl, setMarketEnvironment } from "../../config"
import {
  CredifyCheckbox,
  CredifyImage,
  Header,
  LoginButton,
  LoginText,
  OffersWrapper,
  ServiceInstanceWrapper,
  UICustomizationText,
  Wrapper
} from "./styled"
import Slider from "react-slick"
import { NextArrow, PrevArrow } from "../../components/Arrow"
import { TEST_THEME_DEFAULT } from "./type"
import { getOffers } from "../../apis"
import { GetOffersRequest } from "../../types/common"
import { decamelize } from "@credify/crypto"

const MARKET_NAME = "HouseCare"

const CurentText = styled.p`
  font-family: Oswald;
  font-style: normal;
  font-weight: 500;
  font-size: 30px;
  line-height: 140%;
  text-align: center;
  color: #ffffff;
`
const IdWrapper = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 10px;
  p {
    margin: 0;
  }
`
const IdInput = styled.input`
  height: 30px;
  width: 80px;
  margin-left: 10px;
  font-size: 25px;
`
const FetchInput = styled.input`
  margin-left: 10px;
  height: 30px;
`
const DEFAULT_API_KEY =
  "7kx6vx9p9gZmqrtvHjRTOiSXMkAfZB3s5u3yjLehQHQCtjWrjAk9XlQHR2IOqpuR"
const DEFAULT_MARKET_ID= "8af0e885-a06c-4508-8d17-03e4fa1ea526"

function NormalPage() {
  const [user, setUser] = useState<UserProfile>()
  const [offers, setOffers] = useState<Offer[]>()
  const [isLoading, setLoading] = useState<boolean>(false)
  const [idText, setIdText] = useState<string>("")
  const [useIntentOffer, setUseIntentOffer] = useState<boolean>(true)
  const location = useLocation()
  const inputRef = useRef(null)

  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
    )
    // Demo Market environment
    setMarketEnvironment(env as Environment)
    loadData()
  }, [])

  useEffect(() => {
    setPassportCloseCallback(() => {
      loadData()
    })
  }, [user])

  async function loadData() {
    console.log("Market Data is loading....")
    setLoading(true)
    const userProfile = await getUserProfile()
    await getOffersData({
      localId: `${userProfile.id}`,
      phoneNumber: userProfile.phoneNumber,
      countryCode: userProfile.countryCode,
      credifyId: userProfile.credifyId,
    })
    setLoading(false)
    console.log("Market Data finish loading....")
  }

  async function getUserProfile(): Promise<UserProfile> {
    //@ts-ignore
    const demoUserUrl = `${getMarketApiUrl()}/${MARKET_NAME}/demo-user?id=${inputRef?.current?.value.toString()}`

    console.log({ demoUserUrl })
    const res = await fetch(demoUserUrl)
    const _user = await res.json()
    const userProfile: UserProfile = {
      id: `${_user.id}`,
      firstName: _user.firstName,
      lastName: _user.lastName,
      middleName: _user.middleName,
      fullName: _user.fullName,
      phoneNumber: _user.phoneNumber,
      countryCode: _user.phoneCountryCode,
      email: _user.email,
      credifyId: _user.credifyId,
    }
    console.log({ userProfile })
    setUser(userProfile)
    setIdText(_user.id)
    return userProfile
  }

  async function getOffersData(request: GetOffersRequest) {
    // TODO need to set access token when the BE requires in the future
    const result = await getOffers(MARKET_NAME, "", request)

    if (result?.success && result.data) {
      setOffers(result.data.offers || [])
    }
  }


  async function pushClaimCB(
    externalId: string,
    resolve: (isSuccess: boolean) => void
  ) {
    console.log("Push claim token......")
    try {
      const res = await pushClaim(user!.id!, externalId)
      console.log({ res })
      resolve(true)
    } catch (error) {
      resolve(false)
    }
  }

  async function pushClaim(localId: string, credifyId: string) {
    const body = {
      id: localId,
      credify_id: credifyId,
    }
    try {
      const pushClaimUrl = `${getMarketApiUrl()}/${MARKET_NAME}/push-claims`
      console.log({ pushClaimUrl })
      const res = await fetch(pushClaimUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(body),
      })
      return res.json()
    } catch (error) {
      throw error
    }
  }

  function randomUser() {
    setIdText("")
    setTimeout(() => {
      loadData()
    }, 300)
  }

  const goToServiceInstance = (
    e: React.MouseEvent<HTMLButtonElement, MouseEvent>
  ) => {
    e.preventDefault()
    startServiceInstanceFlow(MARKET_NAME, user, [
      PRODUCT_TYPE.CONSUMER_FINANCING__UNSECURED_LOAN__BNPL,
    ])
  }

  const createIntent = async (offerCode: string, user: UserProfile) => {
    const body = {
      type: "OFFER",
      offer: {
        offerCode: offerCode
      },
      user: {
        id: user.id,
        firstName: user.firstName,
        lastName: user.lastName,
        middleName: user.middleName,
        name: user.fullName,
        phone: {
          phoneNumber: user.phoneNumber,
          countryCode: user.countryCode
        },
        email: user.email,
        credifyId: user.credifyId,
        entityId: user.entityId,
      }
    }

    try {
      const createIntentUrl = `${getMarketApiUrl()}/${MARKET_NAME}/intents`
      const res = await fetch(createIntentUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(decamelize(body)),
      })
      return res.json()
    } catch (error) {
      throw error
    }
  }

  const handleOfferClicked = async (offerCode: string, user: UserProfile) => {
    if (!useIntentOffer) {
      showOfferByCode(
        {
          offerCode: offerCode,
          profile: user,
        },
        pushClaimCB
      )
      return;
    }

    const result = await createIntent(offerCode, user);
    if(result.appUrl) {
      window.location.href = result.appUrl;
    }
  }

  return (
    <Wrapper>
      <Header>
        Offere list for you from {MARKET_NAME.toUpperCase()} [Normal Market
        mode]
      </Header>
      <OffersWrapper>
        <Slider {...settings}>
          {offers?.map((item) => (
            <div>
              <OfferItem
                key={item.id}
                data={item}
                onOfferClick={() => {
                  if (item.code && user) {
                    handleOfferClicked(item.code, user);
                  }
                }}
              />
            </div>
          ))}
        </Slider>
      </OffersWrapper>
      <LoginButton onClick={randomUser}>
        <LoginText>Random user</LoginText>
      </LoginButton>
      <IdWrapper>
        <CurentText>UserId: </CurentText>
        <IdInput
          ref={inputRef}
          value={idText.toString()}
          onChange={(e) => setIdText(e.target.value)}
        />
        <FetchInput type="button" value="FETCH" onClick={loadData} />
      </IdWrapper>
      <div>
        <CredifyCheckbox type="checkbox" id="uiCustomization" />
        <UICustomizationText htmlFor="uiCustomization">
          UI Customization
        </UICustomizationText>
      </div>
      <div>
        <CredifyCheckbox type="checkbox" id="useIntentOffer" checked={useIntentOffer} onChange={(event) => setUseIntentOffer(event.target.checked)} />
        <UICustomizationText htmlFor="useIntentOffer">
          Use intent offer
        </UICustomizationText>
      </div>
      <ServiceInstanceWrapper>
        <button onClick={goToServiceInstance}>Service instance</button>
      </ServiceInstanceWrapper>
      <button
        onClick={() => {
          showPromotionOffersByCodes(
            {
              offerCodes: (offers || []).filter((item) => !!item.code).map((item) => item.code!),
              profile: user,
            },
            pushClaimCB
          )
        }}
      >
        Promotion offer flow
      </button>
      <CredifyImage src={CredifyLogo} />
      <FullScreenLoading active={isLoading} text={``} />
    </Wrapper>
  )
}

export { NormalPage }
