import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import { uniqueId } from 'lodash';
import React, { ReactElement, useMemo, 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 TableDocuments from '../../components/Documents/TableDocuments'
import BaseButton from '../../components/BaseButton'
import BaseButtons from '../../components/BaseButtons'
import axios from "axios";
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
import CardBoxModal from "../../components/CardBoxModal";
import DragDropFilePicker from "../../components/DragDropFilePicker";
import {setRefetch, uploadCsv} from '../../stores/documents/documentsSlice';


import { buildNextFilterItem, filterEntityFieldsForRole, getAddFilterState, pruneHiddenFilterItems } from "../../helpers/entityVisibility";
import { getRoleLaneFromUser } from "../../helpers/roleLanes";
import {hasPermission} from "../../helpers/userPermissions";



const DocumentsTablesPage = () => {
  const [filterItems, setFilterItems] = useState([]);
  const [csvFile, setCsvFile] = useState<File | null>(null);
  const [isModalActive, setIsModalActive] = useState(false);

  const { currentUser } = useAppSelector((state) => state.auth);
  

  const dispatch = useAppDispatch();
  const roleLane = getRoleLaneFromUser(currentUser);

  const filters = useMemo(() => filterEntityFieldsForRole('documents', roleLane, [{label: 'Filename', title: 'file_name'},{label: 'MIMEtype', title: 'mime_type'},{label: 'Storagekey', title: 'storage_key'},{label: 'PublicURL', title: 'public_url'},{label: 'Notes', title: 'notes'},
          {label: 'Filesize(bytes)', title: 'file_size_bytes', number: 'true'},
          {label: 'Tenant', title: 'tenant'},
          {label: 'Uploadedby', title: 'uploaded_by'},
          {label: 'Bookingrequest', title: 'booking_request'},
          {label: 'Reservation', title: 'reservation'},
          {label: 'Servicerequest', title: 'service_request'},
          {label: 'Invoice', title: 'invoice'},
          {label: 'Documenttype', title: 'document_type', type: 'enum', options: ['invoice_pdf','guest_id','contract','approval_attachment','arrival_instructions','checklist','inspection_report','other']},
  ]), [roleLane]);
    
  React.useEffect(() => {
    setFilterItems((currentItems) => pruneHiddenFilterItems(currentItems, filters));
  }, [filters]);

  const addFilterState = useMemo(() => getAddFilterState(filterItems, filters), [filterItems, filters]);

  const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_DOCUMENTS');

  const addFilter = () => {
    setFilterItems((currentItems) => {
      const nextItem = buildNextFilterItem(currentItems, filters, () => uniqueId());

      return nextItem ? [...currentItems, nextItem] : currentItems;
    });
  };

    const getDocumentsCSV = async () => {
        const response = await axios({url: '/documents?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 = 'documentsCSV.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('Documents')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Documents" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6 border border-white/10 shadow-none'>
          <div className='flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between'>
            <div>
              <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>Working view</p>
              <h2 className='mt-1 text-lg font-semibold text-white'>Document hub</h2>
              <p className='mt-1 text-sm text-slate-400'>Collect files, filter the document list, and switch views from a mobile-friendly action strip.</p>
            </div>

            <div className='flex w-full flex-col gap-3 xl:w-auto xl:items-end'>
              <BaseButtons
                type='justify-start xl:justify-end'
                mb='mb-0'
                classAddon='mb-2 mr-0 w-full sm:mr-2 sm:w-auto last:mr-0'
                className='w-full xl:w-auto'
              >
                {hasCreatePermission ? <BaseButton href={'/documents/documents-new'} color='info' label='New item' /> : null}
                <BaseButton
                  color='whiteDark'
                  outline
                  label={addFilterState.buttonLabel}
                  onClick={addFilter}
                  disabled={!addFilterState.canAddFilter}
                />
                <BaseButton color='whiteDark' outline label='Export CSV' onClick={getDocumentsCSV} />
                {hasCreatePermission ? <BaseButton color='whiteDark' outline label='Import CSV' onClick={() => setIsModalActive(true)} /> : null}
                <BaseButton href='/documents/documents-table' color='whiteDark' outline label='Table view' />
              </BaseButtons>

              <p className='max-w-full text-left text-xs leading-5 text-slate-400 xl:max-w-sm xl:text-right'>{addFilterState.helperText}</p>

              <div className='flex min-h-[40px] w-full items-center justify-start xl:w-auto xl:justify-end'>
                <div id='delete-rows-button'></div>
              </div>
            </div>
          </div>
        </CardBox>
        
        <CardBox className="mb-6" hasTable>
          <TableDocuments
            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>
    </>
  )
}

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

export default DocumentsTablesPage
