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 TableDriver_compliances from '../../components/Driver_compliances/TableDriver_compliances'
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/driver_compliances/driver_compliancesSlice';


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



const Driver_compliancesTablesPage = () => {
  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: 'LicenseCountry', title: 'license_country'},{label: 'LicenseNumber', title: 'license_number'},{label: 'LicenseRestrictions', title: 'license_restrictions'},{label: 'CPCNumber', title: 'cpc_number'},{label: 'CPCCenter', title: 'cpc_center'},{label: 'CPCType', title: 'cpc_type'},{label: 'ADRNumber', title: 'adr_number'},{label: 'ADRRestrictions', title: 'adr_restrictions'},{label: 'MedicalCertificateNumber', title: 'medical_cert_number'},{label: 'MedicalIssuedBy', title: 'medical_issued_by'},{label: 'PsychTestNumber', title: 'psych_test_number'},{label: 'MedicalRestrictions', title: 'medical_restrictions'},{label: 'TachoCardNumber', title: 'tacho_card_number'},{label: 'TachoCountry', title: 'tacho_country'},
          {label: 'ViolationsCount', title: 'violations_count', number: 'true'},{label: 'WarningsCount', title: 'warnings_count', number: 'true'},
          
          {label: 'LicenseIssuedAt', title: 'license_issued_at', date: 'true'},{label: 'LicenseExpiresAt', title: 'license_expires_at', date: 'true'},{label: 'CPCIssuedAt', title: 'cpc_issued_at', date: 'true'},{label: 'CPCExpiresAt', title: 'cpc_expires_at', date: 'true'},{label: 'CPCLastTrainingAt', title: 'cpc_last_training_at', date: 'true'},{label: 'CPCNextTrainingAt', title: 'cpc_next_training_at', date: 'true'},{label: 'ADRExpiresAt', title: 'adr_expires_at', date: 'true'},{label: 'ADRLastCourseAt', title: 'adr_last_course_at', date: 'true'},{label: 'ADRNextCourseAt', title: 'adr_next_course_at', date: 'true'},{label: 'MedicalExpiresAt', title: 'medical_expires_at', date: 'true'},{label: 'PsychExpiresAt', title: 'psych_expires_at', date: 'true'},{label: 'EyeExamAt', title: 'eye_exam_at', date: 'true'},{label: 'CardioExamAt', title: 'cardio_exam_at', date: 'true'},{label: 'TachoExpiresAt', title: 'tacho_expires_at', date: 'true'},{label: 'TachoLastDownloadAt', title: 'tacho_last_download_at', date: 'true'},{label: 'TachoNextDownloadAt', title: 'tacho_next_download_at', date: 'true'},{label: 'DrivingBanUntil', title: 'driving_ban_until', date: 'true'},
    
    
    {label: 'DriverProfile', title: 'driver_profile'},
    
    
          
          
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_DRIVER_COMPLIANCES');
    

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

    const getDriver_compliancesCSV = async () => {
        const response = await axios({url: '/driver_compliances?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 = 'driver_compliancesCSV.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('Driver_compliances')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Driver_compliances" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox   className='mb-6' cardBoxClassName='flex flex-wrap'>
          
            {hasCreatePermission && <BaseButton className={'mr-3'} href={'/driver_compliances/driver_compliances-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={getDriver_compliancesCSV} />
          
            {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>
          </div>  
          
            <div className='md:inline-flex items-center ms-auto'>
              <Link href={'/driver_compliances/driver_compliances-table'}>Switch to Table</Link>
            </div>
          
        </CardBox>
        
        <CardBox className="mb-6" hasTable>
          <TableDriver_compliances
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid={false}
            />
        </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>
    </>
  )
}

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

export default Driver_compliancesTablesPage
