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 TableGeneration_requests from '../../components/Generation_requests/TableGeneration_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/generation_requests/generation_requestsSlice';


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



const Generation_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: 'PromptText', title: 'prompt_text'},{label: 'TargetKey', title: 'target_key'},{label: 'ErrorMessage', title: 'error_message'},
          {label: 'TargetBPM', title: 'target_bpm', number: 'true'},{label: 'ComputeSeconds', title: 'compute_seconds', number: 'true'},
          {label: 'EstimatedCost', title: 'estimated_cost', number: 'true'},
          {label: 'QueuedAt', title: 'queued_at', date: 'true'},{label: 'StartedAt', title: 'started_at', date: 'true'},{label: 'FinishedAt', title: 'finished_at', date: 'true'},
    
    
    {label: 'Workspace', title: 'workspace'},
    
    
    
    {label: 'Project', title: 'project'},
    
    
    
    {label: 'Song', title: 'song'},
    
    
    
    {label: 'RequestedBy', title: 'requested_user'},
    
    
    
    {label: 'AIModel', title: 'model'},
    
    
    
    {label: 'InputAsset', title: 'input_asset'},
    
    
    
    {label: 'TargetGenre', title: 'target_genre'},
    
    
    
    {label: 'OutputAsset', title: 'output_asset'},
    
    
              
          {label: 'RequestType', title: 'request_type', type: 'enum', options: ['generate_beat_from_text','generate_beat_from_vocals','arrangement_builder','vocal_processing','auto_mix','mastering','cover_art','song_naming','metadata_tagging','genre_suggestion','make_it_amapiano']},{label: 'Mood', title: 'mood', type: 'enum', options: ['happy','sad','spiritual','energetic','romantic','chill','aggressive']},{label: 'Status', title: 'status', type: 'enum', options: ['queued','running','succeeded','failed','canceled']},
  ]);
    
    const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_GENERATION_REQUESTS');
    

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

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

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

export default Generation_requestsTablesPage
