import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import { uniqueId } from 'lodash'
import React, { ReactElement, useEffect, useMemo, useState } from 'react'
import axios from 'axios'
import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import TablePrice_lists from '../../components/Price_lists/TablePrice_lists'
import BaseButton from '../../components/BaseButton'
import CardBoxModal from '../../components/CardBoxModal'
import DragDropFilePicker from '../../components/DragDropFilePicker'
import { getPageTitle } from '../../config'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { setRefetch, uploadCsv } from '../../stores/price_lists/price_listsSlice'
import { hasPermission } from '../../helpers/userPermissions'

type PriceListRow = {
  id: string
  price_list_name?: string
  price_list_type?: string
  effective_start?: string
  effective_end?: string
  is_active?: boolean
  active?: boolean
  notes?: string
}

const formatDate = (value?: string) => {
  if (!value) {
    return 'Not scheduled'
  }

  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return 'Not scheduled'
  }

  return new Intl.DateTimeFormat('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  }).format(date)
}

const PriceListsTablesPage = () => {
  const [filterItems, setFilterItems] = useState<any[]>([])
  const [csvFile, setCsvFile] = useState<File | null>(null)
  const [isModalActive, setIsModalActive] = useState(false)
  const [previewRows, setPreviewRows] = useState<PriceListRow[]>([])
  const [pageError, setPageError] = useState('')
  const { currentUser } = useAppSelector((state) => state.auth)
  const dispatch = useAppDispatch()

  const [filters] = useState([
    { label: 'Price list name', title: 'price_list_name' },
    { label: 'Notes', title: 'notes' },
    { label: 'Effective start', title: 'effective_start', date: 'true' },
    { label: 'Effective end', title: 'effective_end', date: 'true' },
    {
      label: 'Price list type',
      title: 'price_list_type',
      type: 'enum',
      options: ['contract', 'promo', 'standard'],
    },
  ])

  const hasCreatePermission = Boolean(currentUser && hasPermission(currentUser, 'CREATE_PRICE_LISTS'))

  useEffect(() => {
    if (!currentUser) {
      return
    }

    const loadPreviewRows = async () => {
      try {
        const { data } = await axios.get('/price_lists', {
          params: {
            page: 0,
            limit: 12,
          },
        })
        const rows = Array.isArray(data?.rows) ? data.rows : data
        setPreviewRows(Array.isArray(rows) ? rows : [])
        setPageError('')
      } catch (error) {
        console.error('Failed to load price lists workspace', error)
        setPageError('Unable to load price list overview. Check API access or retry the page.')
      }
    }

    loadPreviewRows()
  }, [currentUser])

  const stats = useMemo(() => {
    const activeCount = previewRows.filter((row) => row.is_active !== false && row.active !== false).length
    const contractCount = previewRows.filter((row) => row.price_list_type === 'contract').length
    const expiringSoon = previewRows
      .filter((row) => row.effective_end)
      .sort(
        (a, b) =>
          new Date(a.effective_end || '').getTime() - new Date(b.effective_end || '').getTime(),
      )[0]

    return {
      activeCount,
      contractCount,
      expiringSoon,
    }
  }, [previewRows])

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

  const getPriceListsCSV = async () => {
    try {
      const response = await axios({
        url: '/price_lists?filetype=csv',
        method: 'GET',
        responseType: 'blob',
      })
      const type = response.headers['content-type']
      const blob = new Blob([response.data], { type })
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = 'price-lists.csv'
      link.click()
      setPageError('')
    } catch (error) {
      console.error('Failed to export price lists CSV', error)
      setPageError('CSV export failed. Check the price list API and try again.')
    }
  }

  const onModalConfirm = async () => {
    if (!csvFile) {
      setPageError('Choose a CSV file before importing price lists.')
      return
    }

    await dispatch(uploadCsv(csvFile))
    dispatch(setRefetch(true))
    setCsvFile(null)
    setIsModalActive(false)
    setPageError('')
  }

  const onModalCancel = () => {
    setCsvFile(null)
    setIsModalActive(false)
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Contract price files')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Contract price files'
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <div className='mb-6 grid gap-6 lg:grid-cols-[1.2fr_0.8fr]'>
          <CardBox>
            <p className='text-xs font-bold uppercase tracking-[0.22em] text-emerald-600'>
              Buyer-specific pricing
            </p>
            <h1 className='mt-3 text-3xl font-bold text-slate-950 dark:text-white'>
              Manage contract, promo, and standard price lists
            </h1>
            <p className='mt-3 max-w-3xl text-sm leading-6 text-slate-600 dark:text-slate-300'>
              Foodservice buyers should only see the pricing they negotiated. Use this
              workspace to import price files, review effective dates, and keep account
              assignments ready for purchase orders and reorders.
            </p>
          </CardBox>

          <CardBox cardBoxClassName='space-y-4'>
            <div className='flex items-center justify-between gap-4'>
              <span className='text-sm text-slate-500 dark:text-slate-400'>Active files</span>
              <span className='text-2xl font-bold text-slate-950 dark:text-white'>{stats.activeCount}</span>
            </div>
            <div className='flex items-center justify-between gap-4'>
              <span className='text-sm text-slate-500 dark:text-slate-400'>Contract lists</span>
              <span className='text-2xl font-bold text-slate-950 dark:text-white'>{stats.contractCount}</span>
            </div>
            <div className='rounded border border-amber-200 bg-amber-50 p-3 dark:border-amber-800 dark:bg-amber-950/30'>
              <p className='text-xs font-bold uppercase tracking-[0.18em] text-amber-700 dark:text-amber-300'>
                Next review
              </p>
              <p className='mt-1 text-sm font-semibold text-slate-900 dark:text-slate-100'>
                {stats.expiringSoon
                  ? `${stats.expiringSoon.price_list_name || 'Price list'} ends ${formatDate(stats.expiringSoon.effective_end)}`
                  : 'No expiration dates found'}
              </p>
            </div>
          </CardBox>
        </div>

        {pageError && (
          <div className='mb-6 rounded border border-red-200 bg-red-50 p-4 text-sm font-semibold text-red-800 dark:border-red-800 dark:bg-red-950/30 dark:text-red-200'>
            {pageError}
          </div>
        )}

        <div className='mb-6 grid gap-4 md:grid-cols-3'>
          {previewRows.slice(0, 3).map((row) => (
            <div
              key={row.id}
              className='rounded border border-slate-200 bg-white p-5 dark:border-slate-700 dark:bg-slate-900'
            >
              <div className='flex items-start justify-between gap-3'>
                <div>
                  <p className='text-xs font-bold uppercase tracking-[0.18em] text-emerald-600'>
                    {row.price_list_type || 'standard'}
                  </p>
                  <h2 className='mt-2 text-lg font-bold text-slate-950 dark:text-white'>
                    {row.price_list_name || 'Untitled price list'}
                  </h2>
                </div>
                <span className='rounded-full bg-emerald-50 px-3 py-1 text-xs font-bold text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300'>
                  {row.is_active === false || row.active === false ? 'Paused' : 'Active'}
                </span>
              </div>
              <div className='mt-5 grid grid-cols-2 gap-3 text-sm'>
                <div>
                  <p className='text-slate-500 dark:text-slate-400'>Starts</p>
                  <p className='font-semibold text-slate-950 dark:text-white'>{formatDate(row.effective_start)}</p>
                </div>
                <div>
                  <p className='text-slate-500 dark:text-slate-400'>Ends</p>
                  <p className='font-semibold text-slate-950 dark:text-white'>{formatDate(row.effective_end)}</p>
                </div>
              </div>
            </div>
          ))}
        </div>

        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap items-center gap-3'>
          {hasCreatePermission && (
            <BaseButton href='/price_lists/price_lists-new' color='info' label='New price list' />
          )}
          <BaseButton color='info' outline label='Add filter' onClick={addFilter} />
          <BaseButton color='info' outline label='Export CSV' onClick={getPriceListsCSV} />
          {hasCreatePermission && (
            <BaseButton color='info' outline label='Import CSV' onClick={() => setIsModalActive(true)} />
          )}
          <div className='md:ml-auto' id='delete-rows-button'></div>
        </CardBox>

        <CardBox className='mb-6' hasTable>
          <TablePrice_lists
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid
          />
        </CardBox>
      </SectionMain>

      <CardBoxModal
        title='Import price lists CSV'
        buttonColor='info'
        buttonLabel='Confirm'
        isActive={isModalActive}
        onConfirm={onModalConfirm}
        onCancel={onModalCancel}
      >
        <DragDropFilePicker file={csvFile} setFile={setCsvFile} formats='.csv' />
      </CardBoxModal>
    </>
  )
}

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

export default PriceListsTablesPage
