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 TableSync_jobs from '../../components/Sync_jobs/TableSync_jobs'
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 {
  create as createSyncJob,
  setRefetch,
  uploadCsv,
} from '../../stores/sync_jobs/sync_jobsSlice';
import { hasPermission } from '../../helpers/userPermissions';

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

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

  const [filters] = useState([{label: 'ErrorSummary', title: 'error_summary'},{label: 'JobPayloadJson', title: 'job_payload_json'},
          {label: 'ProcessedCount', title: 'processed_count', number: 'true'},{label: 'InsertedCount', title: 'inserted_count', number: 'true'},{label: 'UpdatedCount', title: 'updated_count', number: 'true'},{label: 'SkippedCount', title: 'skipped_count', number: 'true'},{label: 'ErrorCount', title: 'error_count', number: 'true'},

          {label: 'StartedAt', title: 'started_at', date: 'true'},{label: 'FinishedAt', title: 'finished_at', date: 'true'},


    {label: 'TriggeredBy', title: 'triggered_by'},


          {label: 'JobType', title: 'job_type', type: 'enum', options: ['osu_sync_seed','osu_sync_incremental','osu_refresh_mappers','osu_refresh_artists','aggregate_mapper_totals','aggregate_artist_totals','cache_warmup']},{label: 'Status', title: 'status', type: 'enum', options: ['queued','running','succeeded','failed','canceled']},
  ]);

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

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

  const getSync_jobsCSV = async () => {
    const response = await axios({url: '/sync_jobs?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 = 'sync_jobsCSV.csv'
    link.click()
  };

  const runCatalogSync = async () => {
    try {
      setIsCatalogSyncing(true);
      await dispatch(
        createSyncJob({
          job_type: 'osu_sync_seed',
          status: 'queued',
          job_payload_json: JSON.stringify({ pages: 12, sort: 'plays_desc' }),
        }),
      ).unwrap();
      dispatch(setRefetch(true));
    } finally {
      setIsCatalogSyncing(false);
    }
  };

  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('Sync_jobs')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Sync_jobs" main>
          {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
          {hasCreatePermission && <BaseButton className={'mr-3'} href={'/sync_jobs/sync_jobs-new'} color='info' label='New Item'/>}

          {hasCreatePermission && (
            <BaseButton
              className={'mr-3'}
              color='success'
              label={isCatalogSyncing ? 'Syncing osu catalog…' : 'Sync / continue osu catalog'}
              disabled={isCatalogSyncing}
              onClick={runCatalogSync}
            />
          )}

          <BaseButton
              className={'mr-3'}
              color='info'
              label='Filter'
              onClick={addFilter}
          />
          <BaseButton className={'mr-3'} color='info' label='Download CSV' onClick={getSync_jobsCSV} />

          {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>

          <div className='md:inline-flex items-center ms-auto'>
            <Link href={'/sync_jobs/sync_jobs-table'}>Switch to Table</Link>
          </div>
        </CardBox>

        {hasCreatePermission && (
          <CardBox className='mb-6'>
            <p className='text-sm text-slate-500 dark:text-slate-300'>
              Use <strong>Sync / continue osu catalog</strong> before testing the game. Each run upserts into the existing catalog, refreshes mapper and artist totals, and if you leave <code>startPage</code> out it automatically continues from the next untouched page so your local pool keeps growing.
            </p>
          </CardBox>
        )}

        <TableSync_jobs
          filterItems={filterItems}
          setFilterItems={setFilterItems}
          filters={filters}
          showGrid={false}
        />
      </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>
    </>
  )
}

Sync_jobsTablesPage.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated

        permission={'READ_SYNC_JOBS'}

      >
          {page}
      </LayoutAuthenticated>
  )
}

export default Sync_jobsTablesPage
