import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import { uniqueId } from 'lodash';
import React, { ReactElement, 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 TableOrbix_quiz_assistant_sessions from '../../components/Orbix_quiz_assistant_sessions/TableOrbix_quiz_assistant_sessions'
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/orbix_quiz_assistant_sessions/orbix_quiz_assistant_sessionsSlice';


import {hasPermission} from "../../helpers/userPermissions";



const Orbix_quiz_assistant_sessionsTablesPage = () => {
  const [filterItems, setFilterItems] = useState([]);
  const [csvFile, setCsvFile] = useState<File | null>(null);
  const [isModalActive, setIsModalActive] = useState(false);
  const [showTableView, setShowTableView] = useState(false);

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

  const dispatch = useAppDispatch();


  const [filters] = useState([{label: 'Topic', title: 'topic'},{label: 'Notes', title: 'notes'},
          {label: 'TargetQuestionCount', title: 'target_question_count', number: 'true'},
          
          {label: 'StartedAt', title: 'started_at', date: 'true'},{label: 'FinishedAt', title: 'finished_at', date: 'true'},
    
    
    {label: 'User', title: 'user'},
    
    
    
    {label: 'GeneratedQuiz', title: 'generated_quiz'},
    
    
              
          {label: 'AgeGroup', title: 'age_group', type: 'enum', options: ['early','kids','teens','adult','mixed']},{label: 'Difficulty', title: 'difficulty', type: 'enum', options: ['easy','medium','hard','mixed']},{label: 'Status', title: 'status', type: 'enum', options: ['collecting_requirements','draft_ready','exported_to_quiz','cancelled']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_ORBIX_QUIZ_ASSISTANT_SESSIONS');
    

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

    const getOrbix_quiz_assistant_sessionsCSV = async () => {
        const response = await axios({url: '/orbix_quiz_assistant_sessions?filetype=csv', 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 = 'orbix_quiz_assistant_sessionsCSV.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('Orbix_quiz_assistant_sessions')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Orbix_quiz_assistant_sessions" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
          
            {hasCreatePermission && <BaseButton className={'mr-3'} href={'/orbix_quiz_assistant_sessions/orbix_quiz_assistant_sessions-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={getOrbix_quiz_assistant_sessionsCSV} />
          
            {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={'/orbix_quiz_assistant_sessions/orbix_quiz_assistant_sessions-list'}>
                Back to <span className='capitalize'>calendar</span>
              </Link>
            
          </div>
        </CardBox>
        <CardBox className="mb-6" hasTable>
          <TableOrbix_quiz_assistant_sessions
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid={true}
            />
        </CardBox>
      </SectionMain>
      <CardBoxModal
          title='Upload CSV'
          buttonColor='info'
          buttonLabel={'Confirm'}
        // buttonLabel={false ? 'Deleting...' : 'Confirm'}
          isActive={isModalActive}
          onConfirm={onModalConfirm}
          onCancel={onModalCancel}
      >
          <DragDropFilePicker
              file={csvFile}
              setFile={setCsvFile}
              formats={'.csv'}
          />
      </CardBoxModal>
    </>
  )
}

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

export default Orbix_quiz_assistant_sessionsTablesPage
