/**
 * @format
 */

import React, {ReactNode, useMemo, useState} from 'react'
import {Box, Heading, Button, Text, Divider, HStack} from '@chakra-ui/react'

import MOCK_DATA from '../MOCK_DATA.json'
import {
  ButtonWithIcon,
  FormComponent
} from '../components/UIcomponents'
import logo from '../assets/mocks/images/pg_logo.png'
import VantageDatePicker from '../components/VantageDatePicker/VantageDatePicker'
import {SelectDropdown} from '../components/SelectDropDown/SelectDropdown'
import VantageModal from '../components/VantageModal/VantageModal'
const initialDropDownOptions = [
  {value: '1', name: 'One'},
  {value: '2', name: 'Two'},
  {value: '3', name: 'Three'},
  {value: '4', name: 'Four'}
]

import {ModalWindow} from '../components/Modal/Modal'
import {unifiedSearchFilterData} from '../assets/mocks/formData'
// import {
//   MedianChartPSF,
//   MedianChartTransactionPrice
// } from '../components/ChartsComponents'
import {CheckBoxDrowpdown} from '../components/CheckBoxDropDown/CheckBoxDropDown'
import {buildingTypesInitial, TimePeriods} from '../types/types'
import {ActionsDropDown} from '../components/ActionDropDown/ActionDropDown'
import {
  ChartWrapper,
  TimeFilterButtons
} from '../components/Charts/ChartElemets'
import {ScatterChartComponent} from '../components/Charts/ScatterChart'
import {
  chartData_monthly,
  chartData_quarterly,
  chartDate_yearly
} from '../assets/mocks/chartData'
import {LineChartComponent} from '../components/Charts/LineChart'
import {VantageDataTable} from '../components/VantageDataTable'
import {VantagePieChart} from '../components/ChartsComponents'

const Block = ({heading, children}: {heading: string; children: ReactNode}) => (
  <>
    <Box p="8">
      <Heading mb="4">{heading}</Heading>
      <Divider />
      <Box m="4">{children}</Box>
    </Box>
  </>
)

const KitchenSink = () => {
  const data = useMemo(() => MOCK_DATA, [])

  const endDate: Date = new Date()
  const newStartDate: Date = new Date()
  newStartDate.setDate(newStartDate.getDate() + 5)
  const startDate: Date = new Date(newStartDate)
  const [selectedOption, setSelectedOption] = useState(
    initialDropDownOptions[0]
  )
  const [isModalOpen1, setIsModalOpen1] = useState(false)
  const [isModalOpen2, setIsModalOpen2] = useState(false)
  const [isModalOpen3, setIsModalOpen3] = useState(false)
  const [isModalOpen4, setIsModalOpen4] = useState(false)

  const [searchInputValue, setSearchInputValue] = useState('')
  const [selectedOptions, setSelectedOptions] =
    useState<any>(buildingTypesInitial)
  const [optionList, setOptionList] = useState<any>(buildingTypesInitial)
  const [selectAll, setSelectAll] = useState(true)
  const handleSelectAll = (e: any) => {
    setSelectAll(e)

    if (!selectAll) {
      setSelectedOptions(buildingTypesInitial)
    } else {
      setSelectedOptions([])
    }
  }

  const search = (e: any) => {
    const value = e.target.value.toLowerCase()
    setSearchInputValue(value)

    if (searchInputValue === '') {
      setOptionList(buildingTypesInitial)
    } else {
      const results = buildingTypesInitial.filter(item =>
        item.name.toLowerCase().includes(value)
      )
      setOptionList(results)
    }
  }

  const handleCheckBox = (e: any) => {
    const selections = [...selectedOptions]
    const value = e.target.value

    const index = selections.findIndex((item: {value: any}) => {
      if (item.value === value) {
        return true
      }

      return false
    })

    if (index > -1) {
      selections.splice(index, 1)
    } else {
      selections.push(buildingTypesInitial.find(item => item.value === value))
    }

    if (selections.length === buildingTypesInitial.length) {
      setSelectAll(true)
    } else {
      setSelectAll(false)
    }

    setSelectedOptions(selections)
  }

  // More filters functions

  const moreFiltersOnSubmit = (
    e: React.FormEvent<EventTarget>,
    formData: any
  ) => {
    console.log('submitted', e, formData)
  }
  const dateChangedFunc = (val: any) => {
    console.log(val)
  }
  const itemAction = (_e: any, index: any) => {
    const newState = buttonsState.map((item, i) => {
      if (index === i) {
        return {
          ...item,
          isActive: true
        }
      }

      return {
        ...item,
        isActive: false
      }
    })

    setButtonsState(newState)
    setCurrentTimePeriod(newState[index].children)

    if (newState[index].children === TimePeriods.Montly) {
      setCurrrentChartData(chartData_monthly)
    } else if (newState[index].children === TimePeriods.Quarterly) {
      setCurrrentChartData(chartData_quarterly)
    } else if (newState[index].children === TimePeriods.Yearly) {
      setCurrrentChartData(chartDate_yearly)
    }
  }

  const logItemAction = () => console.log('menu item action called')
  const timeFilterButtonProps = [
    {children: 'Montly', clickHandler: itemAction, isActive: false},
    {children: 'Quarterly', clickHandler: itemAction, isActive: false},
    {children: 'Yearly', clickHandler: itemAction, isActive: false}
  ]

  const [buttonsState, setButtonsState] = useState(timeFilterButtonProps)

  const dropdownActions = [
    {itemDesc: 'Action 1', itemAcion: logItemAction},
    {itemDesc: 'Action 2', itemAcion: logItemAction}
  ]

  const [currentChartData, setCurrrentChartData] =
    useState<any>(chartData_monthly)
  const [currentTimePeriod, setCurrentTimePeriod] = useState<any>(
    TimePeriods.Montly
  )
  // PGButton(props -> Chk) > ChakraButton(Chakra - props) > HTMLButton (CSS)

  return (
    <>
      <Block heading="DataTable">
        <VantageDataTable data={data} />
      </Block>
      <Block heading="Chart main components">
        <Box>
          <ActionsDropDown actions={dropdownActions} />
        </Box>
        <Box>
          <TimeFilterButtons buttons={timeFilterButtonProps} />
        </Box>
        <Box mt={20}>
          <ChartWrapper
            heading={'Scatter Chart'}
            timeFilterButtons={buttonsState}
            dropDownActions={dropdownActions}
            showActionButtons
            showTimePeriodFilters
          >
            <ScatterChartComponent
              data={currentChartData}
              currentTimePeriod={currentTimePeriod}
              xAxisLabeL="Date"
              yAxisLabeL="Price(RM)"
            />
          </ChartWrapper>
        </Box>
        <Box mt={20}>
          <ChartWrapper
            heading={'Scatter Chart'}
            timeFilterButtons={buttonsState}
            dropDownActions={dropdownActions}
            showActionButtons
            showTimePeriodFilters
          >
            <LineChartComponent
              data={currentChartData}
              currentTimePeriod={currentTimePeriod}
              xAxisLabeL="Date"
              yAxisLabeL="Price(RM)"
            />
          </ChartWrapper>
        </Box>
      </Block>
      <Block heading="Modal">
        <HStack spacing={4}>
          <Button onClick={() => setIsModalOpen1(true)}>Open Modal</Button>
          <Button onClick={() => setIsModalOpen2(true)}>Open Modal 2</Button>
          <Button onClick={() => setIsModalOpen3(true)}>Open Modal 3</Button>
        </HStack>
        <ModalWindow
          onClose={() => setIsModalOpen1(false)}
          isOpen={isModalOpen1}
          title={'Modal title text'}
          cancelButtonText={'Close'}
          cancelButtonVariant={'primary'}
          mainContentAlignment={'center'}
        >
          <Text>Some long lorem ipsum yellow sun</Text>
        </ModalWindow>
        <ModalWindow
          onClose={() => setIsModalOpen2(false)}
          isOpen={isModalOpen2}
          cancelButtonText={'Close without applying'}
          mainContentAlignment={'flex-start'}
          footerContentAlignment={'center'}
          hasPrimarybutton
          primaryButtonText={'Appply'}
          bgColor={'grey.50'}
        >
          <Text textAlign={'center'}>
            Your changes will be lost. Apply changes before closing?
          </Text>
        </ModalWindow>
        <ModalWindow
          onClose={() => setIsModalOpen3(false)}
          isOpen={isModalOpen3}
          title={'Modal title text'}
          cancelButtonText={'Clear all'}
          mainContentAlignment={'center'}
          hasPrimarybutton
          primaryButtonText={'Apply'}
          spreadButtons
        >
          <Text>Sonar sad - duplicate text smash</Text>
        </ModalWindow>
        <ModalWindow
          onClose={() => setIsModalOpen4(false)}
          isOpen={isModalOpen4}
          title={'Modal title text'}
          mainContentAlignment={'center'}
        >
          <Text>Removing duplicate text since Sonar isn't happy</Text>
        </ModalWindow>
      </Block>
      <Block heading="Dropdowns">
        <Box m={5} w={300}>
          <SelectDropdown
            optionList={initialDropDownOptions}
            dropdownWidth={300}
            selectedOption={selectedOption}
            onMenuItemClick={index =>
              setSelectedOption(initialDropDownOptions[index])
            }
          />
        </Box>
        <Box m={5} w={300}>
          <CheckBoxDrowpdown
            optionList={optionList}
            dropdownWidth={300}
            selectAll={selectAll}
            selectedOptions={selectedOptions}
            searchInputValue={searchInputValue}
            setSearchInputValue={search}
            handleSelectAll={handleSelectAll}
            onChange={handleCheckBox}
          />
        </Box>
      </Block>
      <Block heading="Heading and Text">
        <Heading variant="size18">Heading 18</Heading>
        <Heading variant="size16">Heading 16</Heading>
        <Heading variant="size12">Heading 12</Heading>
        <Text variant="bold">This is a Bold text component.</Text>
        <Text>This is a plain text component.</Text>
      </Block>
      <Block heading="Buttons">
        <HStack spacing={4}>
          <Button>Default</Button>
          <Button variant="primary">Default</Button>
          <Button variant="outline">Primary</Button>
          <ButtonWithIcon
            icon={<img src={logo} width="50px" />}
            iconPosition="left"
            clickHandler={() => {
              console.log('button with Left Icon clicked')
            }}
          >
            Button Text
          </ButtonWithIcon>
          <ButtonWithIcon
            icon={<img src={logo} width="50px" />}
            iconPosition="right"
            clickHandler={() => {
              console.log('button with Left Icon clicked')
            }}
          >
            Button Text
          </ButtonWithIcon>
          <ButtonWithIcon
            isLoading
            icon={<img src={logo} width="50px" />}
            iconPosition="left"
            clickHandler={() => {
              console.log('button with Left Icon clicked')
            }}
          >
            Right Icon Button With loading
          </ButtonWithIcon>
        </HStack>
      </Block>
      <Block heading="DatePicker">
        <HStack spacing="8">
          <Box>
            <Text>Date Picker with Drop Down (Start Date)</Text>
            <VantageDatePicker
              onChangeCallBack={dateChangedFunc}
              anotherDate={endDate}
              selected={startDate}
              datePickerType="startDate"
            />
          </Box>
          <Box>
            <Text>Date Picker with Button (End Date)</Text>
            <VantageDatePicker
              onChangeCallBack={dateChangedFunc}
              anotherDate={startDate}
              selected={endDate}
              datePickerType="endDate"
            />
          </Box>
          <Box>
            <Text>Simple Date Picker</Text>
            <VantageDatePicker
              onChangeCallBack={dateChangedFunc}
              anotherDate={endDate}
              selected={startDate}
            />
          </Box>
        </HStack>
      </Block>
      <Block heading="Report Modal">
        <VantageModal />
      </Block>
      <Block heading="More Filters Component">
        <FormComponent
          submitHandler={moreFiltersOnSubmit}
          inputData={unifiedSearchFilterData}
        />
      </Block>

      {/* Unified Search - Search Result - FEATURE - More Filter */}
      <HStack spacing={4} m="4">
        <>
          {[0, 1].map((obj: number) => (
            <Box key={`chart_${obj}`}>
              <Heading variant="size16" mb="19px" textAlign="center">
                {obj === 0 ? 'Transaction Price' : 'Price PSF'}
              </Heading>
              <Box borderWidth="1px" borderRadius="lg" p="4" boxShadow="lg">
                {/* {obj === 0 && <MedianChartTransactionPrice />}
                {obj === 1 && <MedianChartPSF />} */}
              </Box>
            </Box>
          ))}
        </>
      </HStack>
      <Block heading="Pie Chart">
        <VantagePieChart width={400} height={400} />
      </Block>
    </>
  )
}

export default KitchenSink
