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 TableUser_lifestyle_baselines from '../../components/User_lifestyle_baselines/TableUser_lifestyle_baselines'
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/user_lifestyle_baselines/user_lifestyle_baselinesSlice';


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



const User_lifestyle_baselinesTablesPage = () => {
  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: 'TypicalBedtime', title: 'typical_bedtime'},{label: 'TypicalWakeTime', title: 'typical_wake_time'},{label: 'RecreationalSubstanceUse', title: 'recreational_substance_use'},{label: 'ExerciseTypes', title: 'exercise_types'},{label: 'DietPatternOther', title: 'diet_pattern_other'},
          {label: 'CaffeineServingsperDay', title: 'caffeine_servings_per_day', number: 'true'},{label: 'TypicalStressLevel(1-10)', title: 'typical_stress_level', number: 'true'},{label: 'AverageDailyStepsEstimate', title: 'avg_daily_steps_estimate', number: 'true'},
          
          
    
    
    {label: 'User', title: 'user'},
    
    
              
          {label: 'AlcoholConsumption', title: 'alcohol_use', type: 'enum', options: ['never','social','weekly','daily','trying_to_quit']},{label: 'TobaccoorNicotineUse', title: 'tobacco_nicotine_use', type: 'enum', options: ['never','ex_smoker','current_smoker','vaper','chewing_tobacco']},{label: 'OccupationType', title: 'occupation_type', type: 'enum', options: ['sedentary_desk_job','active_job','manual_labour','variable','not_working','student','retired']},{label: 'DietPattern', title: 'diet_pattern', type: 'enum', options: ['omnivore','vegetarian','vegan','pescatarian','keto','paleo','mediterranean','halal','kosher','gluten_free','dairy_free','low_fodmap','other']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_USER_LIFESTYLE_BASELINES');
    

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

    const getUser_lifestyle_baselinesCSV = async () => {
        const response = await axios({url: '/user_lifestyle_baselines?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 = 'user_lifestyle_baselinesCSV.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('User_lifestyle_baselines')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="User_lifestyle_baselines" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
          
            {hasCreatePermission && <BaseButton className={'mr-3'} href={'/user_lifestyle_baselines/user_lifestyle_baselines-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={getUser_lifestyle_baselinesCSV} />
          
            {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={'/user_lifestyle_baselines/user_lifestyle_baselines-list'}>
                Back to <span className='capitalize'>card</span>
              </Link>
            
          </div>
        </CardBox>
        <CardBox className="mb-6" hasTable>
          <TableUser_lifestyle_baselines
            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>
    </>
  )
}

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

export default User_lifestyle_baselinesTablesPage
