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 TableTutor_profiles from '../../components/Tutor_profiles/TableTutor_profiles'
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/tutor_profiles/tutor_profilesSlice';


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



const Tutor_profilesTablesPage = () => {
  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: 'Headline', title: 'headline'},{label: 'InstitutionName', title: 'institution_name'},{label: 'DegreeOrQualification', title: 'degree_qualification'},{label: 'VerificationNote', title: 'verification_note'},{label: 'JitsiMeetingID', title: 'jitsi_meet_meeting_id'},{label: 'JitsiMeetingPassword', title: 'jitsi_meet_password'},{label: 'AvailabilityScheduleJSON', title: 'availability_json'},
          {label: 'GraduationYear', title: 'graduation_year', number: 'true'},{label: 'TotalSessions', title: 'total_sessions', number: 'true'},{label: 'TotalReviews', title: 'total_reviews', number: 'true'},{label: 'ResponseRatePercent', title: 'response_rate', number: 'true'},{label: 'ResponseTimeHours', title: 'response_time_hours', number: 'true'},{label: 'MaxConcurrentBookings', title: 'max_concurrent_bookings', number: 'true'},
          {label: 'Rating', title: 'rating', number: 'true'},
          
    
    
    {label: 'User', title: 'user'},
    
    
              {label: 'SubjectCategories', title: 'subject_categories'},{label: 'Subjects', title: 'subjects'},{label: 'SpokenLanguages', title: 'languages'},
          {label: 'TeachingType', title: 'teaching_type', type: 'enum', options: ['university_student','certified_professional','experienced_teacher']},{label: 'SessionLanguage', title: 'session_language', type: 'enum', options: ['bangla','english','both']},{label: 'TeachingFormat', title: 'teaching_format', type: 'enum', options: ['live_video','async_review','mixed']},{label: 'VerificationStatus', title: 'verification_status', type: 'enum', options: ['verified','pending','rejected']},{label: 'BadgeLevel', title: 'badge_level', type: 'enum', options: ['rising_talent','top_rated','expert','none']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_TUTOR_PROFILES');
    

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

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

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

export default Tutor_profilesTablesPage
