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 [integrationMessage, setIntegrationMessage] = useState<any>(null);
  const [activeIntegration, setActiveIntegration] = useState('');

  
  const { currentUser } = useAppSelector((state) => state.auth);
  const { count } = useAppSelector((state) => state.products);
  

  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 addPresetFilter = (selectedField: string, filterValue: string) => {
        const newItem = {
            id: uniqueId(),
            fields: {
                filterValue,
                filterValueFrom: '',
                filterValueTo: '',
                selectedField,
            },
        };
        setFilterItems([...filterItems, newItem]);
    };

    const readIntegrationError = (error) => {
        if (axios.isAxiosError(error)) {
            if (typeof error.response?.data === 'string') {
                return error.response.data;
            }

            if (error.response?.data) {
                return JSON.stringify(error.response.data);
            }
        }

        return error?.message || 'Integration action failed.';
    };

    const getProductsCSV = async () => {
        setActiveIntegration('csv-export');
        setIntegrationMessage(null);

        try {
            const response = await axios({url: '/integrations/csv/products', 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 = 'northstar-product-catalog.csv'
            link.click()
            window.URL.revokeObjectURL(link.href);
            setIntegrationMessage({
                type: 'success',
                title: 'CSV catalog exported',
                message: 'The live product catalog was exported through the integration endpoint.',
            });
        } catch (error) {
            setIntegrationMessage({
                type: 'error',
                title: 'CSV export failed',
                message: readIntegrationError(error),
            });
        } finally {
            setActiveIntegration('');
        }
    };

    const pushCatalogToGoogleSheets = async () => {
        setActiveIntegration('google-sheets');
        setIntegrationMessage(null);

        try {
            const { data } = await axios.post('/integrations/google-sheets/export-products');
            setIntegrationMessage({
                type: 'success',
                title: 'Google Sheets export complete',
                message: `Exported ${data.rowsExported} catalog rows to Google Sheets.`,
            });
        } catch (error) {
            setIntegrationMessage({
                type: 'error',
                title: 'Google Sheets needs configuration',
                message: readIntegrationError(error),
            });
        } finally {
            setActiveIntegration('');
        }
    };

    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="Contract catalog" main>
        {''}
        </SectionTitleLineWithButton>
        <div className='mb-6 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-dark-700 dark:bg-dark-900'>
          <div className='grid gap-0 lg:grid-cols-[1.4fr_1fr]'>
            <div className='p-6 lg:p-8'>
              <div className='mb-3 text-xs font-bold uppercase tracking-[0.24em] text-emerald-700 dark:text-emerald-300'>
                Foodservice supplier catalog
              </div>
              <h1 className='mb-4 max-w-3xl text-3xl font-semibold tracking-normal text-slate-950 dark:text-white'>
                Manage contract SKUs with the operational detail buyers expect.
              </h1>
              <p className='max-w-3xl text-base leading-7 text-slate-600 dark:text-slate-300'>
                Keep pack size, storage zone, allergens, certifications, MOQ, sample readiness, and spec sheets visible before a restaurant buyer places a purchase order.
              </p>
              <div className='mt-6 flex flex-wrap gap-2'>
                <button
                  type='button'
                  className='rounded-full border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm font-semibold text-emerald-800 transition hover:border-emerald-300 hover:bg-emerald-100 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
                  onClick={() => addPresetFilter('product_status', 'active')}
                >
                  Active SKUs
                </button>
                <button
                  type='button'
                  className='rounded-full border border-sky-200 bg-sky-50 px-4 py-2 text-sm font-semibold text-sky-800 transition hover:border-sky-300 hover:bg-sky-100 dark:border-sky-800 dark:bg-sky-950 dark:text-sky-100'
                  onClick={() => addPresetFilter('temperature_zone', 'refrigerated')}
                >
                  Refrigerated
                </button>
                <button
                  type='button'
                  className='rounded-full border border-cyan-200 bg-cyan-50 px-4 py-2 text-sm font-semibold text-cyan-800 transition hover:border-cyan-300 hover:bg-cyan-100 dark:border-cyan-800 dark:bg-cyan-950 dark:text-cyan-100'
                  onClick={() => addPresetFilter('temperature_zone', 'frozen')}
                >
                  Frozen
                </button>
                <button
                  type='button'
                  className='rounded-full border border-amber-200 bg-amber-50 px-4 py-2 text-sm font-semibold text-amber-800 transition hover:border-amber-300 hover:bg-amber-100 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100'
                  onClick={() => addPresetFilter('is_sample_eligible', 'true')}
                >
                  Sample-ready
                </button>
              </div>
            </div>
            <div className='border-t border-slate-200 bg-slate-50 p-6 dark:border-dark-700 dark:bg-dark-800 lg:border-l lg:border-t-0'>
              <div className='grid h-full grid-cols-2 gap-3'>
                <div className='rounded-xl border border-slate-200 bg-white p-4 dark:border-dark-700 dark:bg-dark-900'>
                  <div className='text-xs font-bold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400'>Catalog SKUs</div>
                  <div className='mt-3 text-3xl font-semibold text-slate-950 dark:text-white'>{count || 0}</div>
                </div>
                <div className='rounded-xl border border-slate-200 bg-white p-4 dark:border-dark-700 dark:bg-dark-900'>
                  <div className='text-xs font-bold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400'>Buyer use</div>
                  <div className='mt-3 text-lg font-semibold text-slate-950 dark:text-white'>Reorder + PO</div>
                </div>
                <div className='rounded-xl border border-slate-200 bg-white p-4 dark:border-dark-700 dark:bg-dark-900'>
                  <div className='text-xs font-bold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400'>Controls</div>
                  <div className='mt-3 text-lg font-semibold text-slate-950 dark:text-white'>Allergens</div>
                </div>
                <div className='rounded-xl border border-slate-200 bg-white p-4 dark:border-dark-700 dark:bg-dark-900'>
                  <div className='text-xs font-bold uppercase tracking-[0.18em] text-slate-500 dark:text-slate-400'>Docs</div>
                  <div className='mt-3 text-lg font-semibold text-slate-950 dark:text-white'>Spec sheets</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className='mb-6 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm dark:border-dark-700 dark:bg-dark-900'>
            <div className='flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between'>
              <div>
                <div className='text-xs font-bold uppercase tracking-[0.2em] text-emerald-700 dark:text-emerald-300'>
                  Catalog integrations
                </div>
                <h2 className='mt-2 text-xl font-semibold text-slate-950 dark:text-white'>
                  Keep price sheets and buyer-facing catalog data in sync.
                </h2>
                <p className='mt-2 max-w-3xl text-sm leading-6 text-slate-600 dark:text-slate-300'>
                  Export a clean CSV for spreadsheet buyers, import supplier price sheets, or push the current catalog to Google Sheets when credentials are configured.
                </p>
              </div>
              <div className='flex flex-wrap gap-2'>
                <button
                  type='button'
                  onClick={getProductsCSV}
                  className='inline-flex h-10 items-center rounded-xl bg-slate-950 px-4 text-sm font-semibold text-white hover:bg-slate-800 dark:bg-white dark:text-slate-950'
                >
                  {activeIntegration === 'csv-export' ? 'Exporting' : 'Export CSV'}
                </button>
                <button
                  type='button'
                  onClick={() => setIsModalActive(true)}
                  className='inline-flex h-10 items-center rounded-xl border border-slate-200 bg-white px-4 text-sm font-semibold text-slate-700 hover:bg-slate-50 dark:border-dark-700 dark:bg-dark-800 dark:text-slate-200'
                >
                  Import CSV
                </button>
                <button
                  type='button'
                  onClick={pushCatalogToGoogleSheets}
                  className='inline-flex h-10 items-center rounded-xl border border-emerald-200 bg-emerald-50 px-4 text-sm font-semibold text-emerald-800 hover:bg-emerald-100 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
                >
                  {activeIntegration === 'google-sheets' ? 'Pushing' : 'Push to Sheets'}
                </button>
              </div>
            </div>
            {integrationMessage && (
              <div
                className={`mt-4 rounded-xl border p-4 text-sm font-semibold ${
                  integrationMessage.type === 'success'
                    ? 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
                    : 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-100'
                }`}
              >
                <div>{integrationMessage.title}</div>
                <div className='mt-1 font-normal'>{integrationMessage.message}</div>
              </div>
            )}
        </div>
        <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>
          </div>  
          
            <div className='md:inline-flex items-center'>
              <Link className='font-semibold text-slate-700 underline-offset-4 hover:underline dark:text-slate-200' href={'/products/products-table'}>Table view</Link>
            </div>
          
        </CardBox>
        
        <CardBox className="mb-6" hasTable>
          <TableProducts
            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>
    </>
  )
}

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

export default ProductsTablesPage
