import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import { uniqueId } from 'lodash'
import { useRouter } from 'next/router'
import React, { ReactElement, useEffect, useMemo, useState } from 'react'
import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'
import TablePage_elements from '../../components/Page_elements/TablePage_elements'
import BaseButton from '../../components/BaseButton'
import axios from 'axios'
import Link from 'next/link'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import CardBoxModal from '../../components/CardBoxModal'
import DragDropFilePicker from '../../components/DragDropFilePicker'
import { setRefetch, uploadCsv } from '../../stores/page_elements/page_elementsSlice'
import { hasPermission } from '../../helpers/userPermissions'

type ProjectPage = {
  id: string
}

const Page_elementsTablesPage = () => {
  const router = useRouter()
  const routeProjectId = useMemo(() => {
    const value = router.query.projectId
    if (Array.isArray(value)) return value[0] || ''
    return String(value || '')
  }, [router.query.projectId])

  const [filterItems, setFilterItems] = useState([])
  const [csvFile, setCsvFile] = useState<File | null>(null)
  const [isModalActive, setIsModalActive] = useState(false)
  const [projectPages, setProjectPages] = useState<ProjectPage[]>([])
  const [projectName, setProjectName] = useState('')
  const [isLoadingProject, setIsLoadingProject] = useState(false)

  const { currentUser } = useAppSelector((state) => state.auth)

  const dispatch = useAppDispatch()

  const [filters] = useState([
    { label: 'Name', title: 'name' },
    { label: 'StyleJSON', title: 'style_json' },
    { label: 'ContentJSON', title: 'content_json' },
    { label: 'Sortorder', title: 'sort_order', number: 'true' },
    { label: 'X(%)', title: 'x_percent', number: 'true' },
    { label: 'Y(%)', title: 'y_percent', number: 'true' },
    { label: 'Width(%)', title: 'width_percent', number: 'true' },
    { label: 'Height(%)', title: 'height_percent', number: 'true' },
    { label: 'Rotation(deg)', title: 'rotation_deg', number: 'true' },
    { label: 'Page', title: 'page' },
    {
      label: 'Elementtype',
      title: 'element_type',
      type: 'enum',
      options: ['nav_button', 'spot', 'description', 'tooltip', 'gallery', 'carousel', 'logo', 'video_player', 'popup'],
    },
  ])

  const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_PAGE_ELEMENTS')

  useEffect(() => {
    const loadProjectPages = async () => {
      if (!routeProjectId) {
        setProjectPages([])
        return
      }

      try {
        const response = await axios.get(`/tour_pages?limit=500&page=0&sort=asc&field=sort_order&project=${routeProjectId}`)
        const rows = Array.isArray(response?.data?.rows) ? response.data.rows : []
        setProjectPages(rows.map((row: { id: string }) => ({ id: row.id })))
      } catch (error: any) {
        console.error('Failed to load project pages for page elements scope:', error)
        setProjectPages([])
      }
    }

    loadProjectPages()
  }, [routeProjectId])

  useEffect(() => {
    const loadProject = async () => {
      if (!routeProjectId) {
        setProjectName('')
        return
      }

      setIsLoadingProject(true)
      try {
        const response = await axios.get(`/projects/${routeProjectId}`)
        setProjectName(response?.data?.name || '')
      } catch (error: any) {
        console.error('Failed to load project for page elements page:', error)
        setProjectName('')
      } finally {
        setIsLoadingProject(false)
      }
    }

    loadProject()
  }, [routeProjectId])

  const addFilter = () => {
    const newItem = {
      id: uniqueId(),
      fields: {
        filterValue: '',
        filterValueFrom: '',
        filterValueTo: '',
        selectedField: '',
      },
    }
    newItem.fields.selectedField = filters[0].title
    setFilterItems([...filterItems, newItem])
  }

  const projectFilterValue = useMemo(() => {
    if (!routeProjectId || projectPages.length === 0) return ''
    return projectPages.map((item) => item.id).join('|')
  }, [projectPages, routeProjectId])

  const projectExtraQuery = projectFilterValue ? `&page=${projectFilterValue}` : ''

  const getPage_elementsCSV = async () => {
    const response = await axios({
      url: `/page_elements?filetype=csv${projectExtraQuery}`,
      method: 'GET',
      responseType: 'blob',
    })
    const type = response.headers['content-type']
    const blob = new Blob([response.data], { type: type })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = 'page_elementsCSV.csv'
    link.click()
  }

  const onModalConfirm = async () => {
    if (!csvFile) return
    await dispatch(uploadCsv(csvFile))
    dispatch(setRefetch(true))
    setCsvFile(null)
    setIsModalActive(false)
  }

  const onModalCancel = () => {
    setCsvFile(null)
    setIsModalActive(false)
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Pages Elements')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title='Pages Elements' main>
          {''}
        </SectionTitleLineWithButton>

        <p className='mb-6 text-sm font-semibold'>
          {isLoadingProject ? 'Loading project...' : projectName || 'No project selected'}
        </p>

        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
          {hasCreatePermission && <BaseButton className={'mr-3'} href={'/page_elements/page_elements-new'} color='info' label='New Item' />}

          <BaseButton className={'mr-3'} color='info' label='Filter' onClick={addFilter} />
          <BaseButton className={'mr-3'} color='info' label='Download CSV' onClick={getPage_elementsCSV} />

          {hasCreatePermission && <BaseButton color='info' label='Upload CSV' onClick={() => setIsModalActive(true)} />}

          <div className='md:inline-flex items-center ms-auto'>
            <div id='delete-rows-button'></div>

            <Link
              href={
                routeProjectId
                  ? { pathname: '/page_elements/page_elements-list', query: { projectId: routeProjectId } }
                  : '/page_elements/page_elements-list'
              }
            >
              Back to <span className='capitalize'>kanban</span>
            </Link>
          </div>
        </CardBox>
        <CardBox className='mb-6' hasTable>
          <TablePage_elements
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid={true}
            extraQuery={projectExtraQuery}
          />
        </CardBox>
      </SectionMain>
      <CardBoxModal
        title='Upload CSV'
        buttonColor='info'
        buttonLabel={'Confirm'}
        isActive={isModalActive}
        onConfirm={onModalConfirm}
        onCancel={onModalCancel}
      >
        <DragDropFilePicker file={csvFile} setFile={setCsvFile} formats={'.csv'} />
      </CardBoxModal>
    </>
  )
}

Page_elementsTablesPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'READ_PAGE_ELEMENTS'}>{page}</LayoutAuthenticated>
}

export default Page_elementsTablesPage
