/**
 * @format
 */

import React, {useRef, useState} from 'react'
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  Image,
  Stack,
  Box,
  Text,
  RadioGroup,
  Radio,
  Checkbox
} from '@chakra-ui/react'
import {Env} from '../../types/env'
import './VantageModalCss.css'
import { PGButton } from '../UIcomponents'

declare global {
  interface Window {
    env: Env
  }
}

const VantageModal = () => {
  const [isOpen, setIsOpen] = useState(false)
  const [isCover1, setCover1] = useState(true)
  const [isCover2, setCover2] = useState(false)
  const [isCover3, setCover3] = useState(false)
  const [queryString, setQueryString] = useState('')
  const [selectedCover, setSelectedCover] = useState('cover1')
  const downloadRef = useRef(null)
  const checkedValues: Array<any> = []
  const onClickCover1 = () => {
    setCover1(true)
    setCover2(false)
    setCover3(false)
    setSelectedCover('cover1')
    updateQueryString()
  }
  const onClickCover2 = () => {
    setCover1(false)
    setCover2(true)
    setCover3(false)
    setSelectedCover('cover2')
    updateQueryString()
  }
  const onClickCover3 = () => {
    setCover1(false)
    setCover2(false)
    setCover3(true)
    setSelectedCover('cover3')
    updateQueryString()
  }
  // useEffect(() => {
  //   console.log({queryString, selectedCover})
  // }, [isCover1, isCover2, isCover3, selectedCover, queryString])

  const openModal = () => {
    setIsOpen(true)
  }

  const closeModal = () => {
    setIsOpen(false)
  }

  const updateQueryString = () => {
    const queryString2 = objToQueryString({
      selectedCover,
      selectedSections: checkedValues
    })
    setQueryString(queryString2)
  }

  const triggerAPICall = () => {
    if (downloadRef && downloadRef.current) {
      // const downloadAnchor = downloadRef.current as HTMLInputElement
      // Commenting this for later use, to trigger click action
      // downloadAnchor.click()
    }

    setIsOpen(false)
  }

  const onPageSelect = (event: any) => {
    const indexOfSelectedPage = checkedValues.indexOf(event.target.value)

    if (indexOfSelectedPage !== -1) {
      checkedValues.splice(indexOfSelectedPage, 1)
    } else {
      checkedValues.push(event.target.value)
    }

    updateQueryString()
  }

  const objToQueryString = (obj: any) => {
    const keyValuePairs = []
    for (const key in obj) {
      if (key !== null) {
        keyValuePairs.push(
          `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
        )
      }
    }
    console.log(`keyValuePairs are ${keyValuePairs}`)

    return keyValuePairs.join('&')
  }

  return (
    <>
      <PGButton clickHandler={openModal}>Open Modal</PGButton>

      <Modal closeOnOverlayClick={false} isOpen={isOpen} onClose={closeModal}>
        <ModalOverlay />
        <ModalContent style={{maxWidth: '75%'}}>
          <ModalHeader>Download Report</ModalHeader>
          <ModalCloseButton />
          <ModalBody pb={6}>
            <Text className="model-sub-title">
              Choose the Pages to Download
            </Text>
            <Box py="2">
              <Stack direction={['column', 'row']}>
                <Checkbox
                  colorScheme="blue"
                  className="vantageCheck"
                  onChange={onPageSelect}
                  value="sales"
                >
                  Sales
                </Checkbox>
                <Checkbox
                  colorScheme="blue"
                  onChange={onPageSelect}
                  value="rental"
                >
                  Rental
                </Checkbox>
                <Checkbox
                  colorScheme="blue"
                  onChange={onPageSelect}
                  value="trend"
                >
                  Trend
                </Checkbox>
                <Checkbox
                  colorScheme="blue"
                  onChange={onPageSelect}
                  value="new_development"
                >
                  New Development
                </Checkbox>
                <Checkbox
                  colorScheme="blue"
                  onChange={onPageSelect}
                  value="demographic"
                >
                  Demographic
                </Checkbox>
                <Checkbox
                  colorScheme="blue"
                  onChange={onPageSelect}
                  value="rental_demand"
                >
                  Rental Demand
                </Checkbox>
              </Stack>
            </Box>
            <Text className="model-sub-title">Choose the Front Page Cover</Text>
            <Box py="2">
              <RadioGroup value={selectedCover} onChange={setSelectedCover}>
                <Stack direction="row" style={{textAlign: 'center'}}>
                  <Box
                    onClick={onClickCover1}
                    className={
                      isCover1
                        ? 'selected-cover cover-wrapper'
                        : 'cover-wrapper'
                    }
                    boxSize="30%"
                    py="2"
                  >
                    <Image
                      boxSize="100%"
                      objectFit="cover"
                      src="https://drive.google.com/uc?export=view&id=1t735kEXYJemZa9ZdPKplWUBhN3IAJorK"
                      alt="Dan Abramov"
                    />
                    <Radio
                      className="cover-radio"
                      onChange={onClickCover1}
                      value="cover1"
                    >
                      Cover 1
                    </Radio>
                  </Box>
                  <Box
                    onClick={onClickCover2}
                    className={
                      isCover2
                        ? 'selected-cover cover-wrapper'
                        : 'cover-wrapper'
                    }
                    boxSize="30%"
                    py="2"
                  >
                    <Image
                      boxSize="100%"
                      objectFit="cover"
                      src="https://drive.google.com/uc?export=view&id=16Gir03iuLbHZXOR-6xA0wTVn2nwdKUwj"
                      alt="Dan Abramov"
                    />
                    <Radio
                      className="cover-radio"
                      onChange={onClickCover2}
                      value="cover2"
                    >
                      Cover 2
                    </Radio>
                  </Box>
                  <Box
                    onClick={onClickCover3}
                    className={
                      isCover3
                        ? 'selected-cover cover-wrapper'
                        : 'cover-wrapper'
                    }
                    boxSize="30%"
                    py="2"
                  >
                    <Image
                      boxSize="100%"
                      objectFit="cover"
                      src="https://drive.google.com/uc?export=view&id=11XH8NwXEC1JORX2AgvLlFLH3LOQzngp-"
                      alt="Dan Abramov"
                    />
                    <Radio
                      className="cover-radio"
                      onChange={onClickCover3}
                      value="cover3"
                    >
                      Cover 3
                    </Radio>
                  </Box>
                </Stack>
              </RadioGroup>
            </Box>
          </ModalBody>

          <ModalFooter style={{justifyContent: 'flex-start'}}>
            <PGButton clickHandler={triggerAPICall} variant="primary">Download</PGButton>
            <a
              ref={downloadRef}
              style={{visibility: 'hidden'}}
              href={`http://localhost:3000/file?${queryString}`}
            >
              D
            </a>
            <PGButton variant="ghost" clickHandler={closeModal}>Cancel </PGButton>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  )
}

export default VantageModal
