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_physical_baselines from '../../components/User_physical_baselines/TableUser_physical_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_physical_baselines/user_physical_baselinesSlice';


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



const User_physical_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: 'Height(cm)', title: 'height_cm', number: 'true'},{label: 'Height(ft)', title: 'height_ft', number: 'true'},{label: 'Height(in)', title: 'height_in', number: 'true'},{label: 'Weight(kg)', title: 'weight_kg', number: 'true'},{label: 'Weight(lb)', title: 'weight_lb', number: 'true'},{label: 'WristCircumference(cm)', title: 'wrist_circumference_cm', number: 'true'},
          
    
    
    {label: 'User', title: 'user'},
    
    
              
          {label: 'DominantHand', title: 'dominant_hand', type: 'enum', options: ['left','right','ambidextrous']},{label: 'FitzpatrickSkinType', title: 'fitzpatrick_skin_type', type: 'enum', options: ['1','2','3','4','5','6']},{label: 'BloodType', title: 'blood_type', type: 'enum', options: ['a_plus','a_minus','b_plus','b_minus','ab_plus','ab_minus','o_plus','o_minus','unknown']},{label: 'RhFactor', title: 'rh_factor', type: 'enum', options: ['positive','negative','unknown']},{label: 'BodyFrameSize', title: 'body_frame_size', type: 'enum', options: ['small','medium','large','unknown']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_USER_PHYSICAL_BASELINES');
    

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

    const getUser_physical_baselinesCSV = async () => {
        const response = await axios({url: '/user_physical_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_physical_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_physical_baselines')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="User_physical_baselines" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
          
            {hasCreatePermission && <BaseButton className={'mr-3'} href={'/user_physical_baselines/user_physical_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_physical_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_physical_baselines/user_physical_baselines-list'}>
                Back to <span className='capitalize'>card</span>
              </Link>
            
          </div>
        </CardBox>
        <CardBox className="mb-6" hasTable>
          <TableUser_physical_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_physical_baselinesTablesPage.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated
        
        permission={'READ_USER_PHYSICAL_BASELINES'}
        
      >
          {page}
      </LayoutAuthenticated>
  )
}

export default User_physical_baselinesTablesPage
