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 TableEconomic_models from '../../components/Economic_models/TableEconomic_models'
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/economic_models/economic_modelsSlice';


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



const Economic_modelsTablesPage = () => {
  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: 'ModelName', title: 'name'},{label: 'AssumptionsJSON', title: 'assumptions_json'},{label: 'SensitivityJSON', title: 'sensitivity_json'},
          
          {label: 'GoldPrice', title: 'gold_price', number: 'true'},{label: 'DiscountRate(%)', title: 'discount_rate_pct', number: 'true'},{label: 'Throughput(tpd)', title: 'throughput_tpd', number: 'true'},{label: 'Recovery(%)', title: 'recovery_pct', number: 'true'},{label: 'MineLife(years)', title: 'mine_life_years', number: 'true'},{label: 'TotalCAPEX', title: 'capex_total', number: 'true'},{label: 'OPEXPerTonne', title: 'opex_per_tonne', number: 'true'},{label: 'NPV', title: 'npv', number: 'true'},{label: 'IRR(%)', title: 'irr_pct', number: 'true'},{label: 'Payback(years)', title: 'payback_years', number: 'true'},
          
    
    
    {label: 'Project', title: 'project'},
    
    
    
    {label: 'Phase', title: 'phase'},
    
    
    
    {label: 'Flowsheet', title: 'flowsheet'},
    
    
          
          {label: 'Currency', title: 'currency', type: 'enum', options: ['USD','CAD','EUR','AUD','ZAR','BRL']},{label: 'Status', title: 'status', type: 'enum', options: ['draft','in_review','approved','archived']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_ECONOMIC_MODELS');
    

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

    const getEconomic_modelsCSV = async () => {
        const response = await axios({url: '/economic_models?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 = 'economic_modelsCSV.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('Economic_models')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Economic_models" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox   className='mb-6' cardBoxClassName='flex flex-wrap'>
          
            {hasCreatePermission && <BaseButton className={'mr-3'} href={'/economic_models/economic_models-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={getEconomic_modelsCSV} />
          
            {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>
          </div>  
          
        </CardBox>
        
        <CardBox className="mb-6" hasTable>
          <TableEconomic_models
            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>
    </>
  )
}

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

export default Economic_modelsTablesPage
