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 TableProducts from '../../components/Products/TableProducts'
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/products/productsSlice';


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



const ProductsTablesPage = () => {
  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 [filters] = useState([{label: 'SKU', title: 'sku'},{label: 'Product name', title: 'product_name'},{label: 'Brand', title: 'brand'},{label: 'Short description', title: 'short_description'},{label: 'Long description', title: 'long_description'},{label: 'Pack size', title: 'pack_size'},{label: 'Unit of measure', title: 'uom'},{label: 'Allergens', title: 'allergens'},{label: 'Certifications', title: 'certifications'},
          {label: 'Units per case', title: 'units_per_case', number: 'true'},{label: 'MOQ cases', title: 'moq_cases', number: 'true'},
          {label: 'Unit weight lbs', title: 'unit_weight_lbs', number: 'true'},{label: 'Case weight lbs', title: 'case_weight_lbs', number: 'true'},
          
    
    
    {label: 'Category', title: 'category'},
    
    
              
          {label: 'Temperature zone', title: 'temperature_zone', type: 'enum', options: ['ambient','refrigerated','frozen']},{label: 'Product status', title: 'product_status', type: 'enum', options: ['active','discontinued','seasonal','out_of_stock']},{label: 'Sample eligible', title: 'is_sample_eligible', type: 'enum', options: ['true','false']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_PRODUCTS');
    

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

    const getProductsCSV = async () => {
        const response = await axios({url: '/products?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 = 'productsCSV.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('Products')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Catalog table" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap items-center gap-3'>
          
            {hasCreatePermission && <BaseButton href={'/products/products-new'} color='info' label='Add SKU'/>}
          
          <BaseButton
              color='info'
              label='Add filter'
              onClick={addFilter}
          />
          <BaseButton color='info' label='Export CSV' onClick={getProductsCSV} />
          
            {hasCreatePermission && (
              <BaseButton
                color='info'
                label='Import CSV'
                onClick={() => setIsModalActive(true)}
              />
            )}
          
          <div className='md:inline-flex items-center md:ml-auto'>
            <div id='delete-rows-button'></div>
            
              <Link className='font-semibold text-slate-700 underline-offset-4 hover:underline dark:text-slate-200' href={'/products/products-list'}>
                Card catalog
              </Link>
            
          </div>
        </CardBox>
        <CardBox className="mb-6" hasTable>
          <TableProducts
            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>
    </>
  )
}

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

export default ProductsTablesPage
