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 TableLead_requests from '../../components/Lead_requests/TableLead_requests'
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/lead_requests/lead_requestsSlice';


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



const Lead_requestsTablesPage = () => {
  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: 'FullName', title: 'full_name'},{label: 'CompanyName', title: 'company_name'},{label: 'Email', title: 'email'},{label: 'Phone', title: 'phone'},{label: 'MessageArabic', title: 'message_ar'},{label: 'InternalNotes', title: 'internal_notes'},
          
          
          {label: 'PreferredContactTime', title: 'preferred_contact_time', date: 'true'},{label: 'LastContactedAt', title: 'last_contacted_at', date: 'true'},
    
    
    {label: 'InterestedStone', title: 'interested_stone'},
    
    
    
    {label: 'InterestedService', title: 'interested_service'},
    
    
    
    {label: 'RelatedProject', title: 'related_project'},
    
    
    
    {label: 'AssignedTo', title: 'assigned_to'},
    
    
              
          {label: 'RequestType', title: 'request_type', type: 'enum', options: ['quote','callback','information','appointment','custom_order']},{label: 'CustomerType', title: 'customer_type', type: 'enum', options: ['architect','interior_designer','contractor','developer','individual','other']},{label: 'LeadStatus', title: 'lead_status', type: 'enum', options: ['new','qualified','in_progress','quoted','won','lost','closed']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_LEAD_REQUESTS');
    

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

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

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

export default Lead_requestsTablesPage
