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 TableMarketplace_listings from '../../components/Marketplace_listings/TableMarketplace_listings'
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/marketplace_listings/marketplace_listingsSlice';


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



const Marketplace_listingsTablesPage = () => {
  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: 'ListingTitle', title: 'listing_title'},{label: 'Description', title: 'description'},{label: 'Currency', title: 'currency'},
          
          {label: 'AvailableQuantityKg', title: 'available_quantity_kg', number: 'true'},{label: 'PricePerKg', title: 'price_per_kg', number: 'true'},
          {label: 'AvailableFrom', title: 'available_from', date: 'true'},{label: 'ExpiresAt', title: 'expires_at', date: 'true'},
    
    
    {label: 'SellerTenant', title: 'seller_tenant'},
    
    
    
    {label: 'Harvest', title: 'harvest'},
    
    
    
    {label: 'Species', title: 'species'},
    
    
    
    {label: 'FulfillmentLocation', title: 'fulfillment_location'},
    
    
              
          {label: 'ProductForm', title: 'product_form', type: 'enum', options: ['live','whole','gutted','fillet','frozen','other']},{label: 'ListingStatus', title: 'listing_status', type: 'enum', options: ['draft','active','paused','sold_out','expired','removed']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_MARKETPLACE_LISTINGS');
    

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

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

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

export default Marketplace_listingsTablesPage
