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 TableQuotes from '../../components/Quotes/TableQuotes'
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/quotes/quotesSlice'
import { hasPermission } from '../../helpers/userPermissions'

type Person = {
  firstName?: string
  lastName?: string
  email?: string
}

type QuoteRow = {
  id: string
  quote_number?: string
  quote_status?: string
  quote_total?: number | string
  requested_at?: string
  expires_at?: string
  account?: {
    account_name?: string
  }
  location?: {
    location_name?: string
  }
  requested_by?: Person
  owner?: Person
  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 formatCurrency = (value?: number | string) => {
  const amount = Number(value || 0)

  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0,
  }).format(amount)
}

const formatPerson = (person?: Person) => {
  if (!person) {
    return 'Unassigned'
  }

  const name = [person.firstName, person.lastName].filter(Boolean).join(' ')
  if (name) {
    return name
  }

  return person.email || 'Unassigned'
}

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

  const [filters] = useState([
    { label: 'Quote number', title: 'quote_number' },
    { label: 'Notes', title: 'notes' },
    { label: 'Quote total', title: 'quote_total', number: 'true' },
    { label: 'Requested at', title: 'requested_at', date: 'true' },
    { label: 'Expires at', title: 'expires_at', date: 'true' },
    { label: 'Account', title: 'account' },
    { label: 'Location', title: 'location' },
    { label: 'Requested by', title: 'requested_by' },
    { label: 'Owner', title: 'owner' },
    {
      label: 'Quote status',
      title: 'quote_status',
      type: 'enum',
      options: ['requested', 'in_review', 'sent', 'accepted', 'declined', 'expired'],
    },
  ])

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

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

    const loadPreviewRows = async () => {
      try {
        const { data } = await axios.get('/quotes', {
          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 quotes workspace', error)
        setPageError('Unable to load quote pipeline. Check API access or retry the page.')
      }
    }

    loadPreviewRows()
  }, [currentUser])

  const stats = useMemo(() => {
    const openCount = previewRows.filter((row) =>
      ['requested', 'in_review', 'sent'].includes(row.quote_status || ''),
    ).length
    const acceptedCount = previewRows.filter((row) => row.quote_status === 'accepted').length
    const openValue = previewRows
      .filter((row) => ['requested', 'in_review', 'sent'].includes(row.quote_status || ''))
      .reduce((total, row) => total + Number(row.quote_total || 0), 0)

    return {
      openCount,
      acceptedCount,
      openValue,
    }
  }, [previewRows])

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

  const getQuotesCSV = async () => {
    try {
      const response = await axios({
        url: '/quotes?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 = 'quotes.csv'
      link.click()
      setPageError('')
    } catch (error) {
      console.error('Failed to export quotes CSV', error)
      setPageError('CSV export failed. Check the quotes API and try again.')
    }
  }

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Quote pipeline')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title='Quote pipeline' 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'>
              RFQ to purchase order
            </p>
            <h1 className='mt-3 text-3xl font-bold text-slate-950 dark:text-white'>
              Track buyer requests, sample follow-ups, and quote decisions
            </h1>
            <p className='mt-3 max-w-3xl text-sm leading-6 text-slate-600 dark:text-slate-300'>
              Quotes connect sales reps, contract pricing, buyer locations, and expiration
              dates. This view keeps every RFQ visible before it becomes an order or drops
              out of the pipeline.
            </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'>Open quotes</span>
              <span className='text-2xl font-bold text-slate-950 dark:text-white'>{stats.openCount}</span>
            </div>
            <div className='flex items-center justify-between gap-4'>
              <span className='text-sm text-slate-500 dark:text-slate-400'>Open value</span>
              <span className='text-2xl font-bold text-slate-950 dark:text-white'>
                {formatCurrency(stats.openValue)}
              </span>
            </div>
            <div className='rounded border border-emerald-200 bg-emerald-50 p-3 dark:border-emerald-800 dark:bg-emerald-950/30'>
              <p className='text-xs font-bold uppercase tracking-[0.18em] text-emerald-700 dark:text-emerald-300'>
                Accepted
              </p>
              <p className='mt-1 text-sm font-semibold text-slate-900 dark:text-slate-100'>
                {stats.acceptedCount} quotes ready for order conversion
              </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.quote_status || 'requested'}
                  </p>
                  <h2 className='mt-2 text-lg font-bold text-slate-950 dark:text-white'>
                    {row.quote_number || 'Draft quote'}
                  </h2>
                </div>
                <span className='rounded-full bg-slate-100 px-3 py-1 text-xs font-bold text-slate-700 dark:bg-slate-800 dark:text-slate-200'>
                  {formatCurrency(row.quote_total)}
                </span>
              </div>
              <div className='mt-5 space-y-3 text-sm'>
                <div className='flex justify-between gap-4'>
                  <span className='text-slate-500 dark:text-slate-400'>Account</span>
                  <span className='font-semibold text-slate-950 dark:text-white'>
                    {row.account?.account_name || 'Unassigned'}
                  </span>
                </div>
                <div className='flex justify-between gap-4'>
                  <span className='text-slate-500 dark:text-slate-400'>Owner</span>
                  <span className='font-semibold text-slate-950 dark:text-white'>{formatPerson(row.owner)}</span>
                </div>
                <div className='flex justify-between gap-4'>
                  <span className='text-slate-500 dark:text-slate-400'>Expires</span>
                  <span className='font-semibold text-slate-950 dark:text-white'>{formatDate(row.expires_at)}</span>
                </div>
              </div>
            </div>
          ))}
        </div>

        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap items-center gap-3'>
          {hasCreatePermission && (
            <BaseButton href='/quotes/quotes-new' color='info' label='New quote' />
          )}
          <BaseButton color='info' outline label='Add filter' onClick={addFilter} />
          <BaseButton color='info' outline label='Export CSV' onClick={getQuotesCSV} />
          {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>
          <TableQuotes
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid
          />
        </CardBox>
      </SectionMain>

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

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

export default QuotesTablesPage
