import { mdiChartTimelineVariant, mdiPlus } from '@mdi/js'
import Head from 'next/head'
import { uniqueId } from 'lodash'
import React, { ReactElement, useCallback, useEffect, 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 TableWorkers_comp_classes from '../../components/Workers_comp_classes/TableWorkers_comp_classes'
import BaseButton from '../../components/BaseButton'
import axios from 'axios'
import Link from 'next/link'
import { useAppSelector } from '../../stores/hooks'
import { hasPermission } from '../../helpers/userPermissions'
import FormField from '../../components/FormField'

const formatDateLabel = (value: string) => {
  if (!value) {
    return ''
  }

  return new Date(`${value}T00:00:00`).toLocaleDateString()
}

const formatDateInputValue = (value: Date) => {
  const year = value.getFullYear()
  const month = `${value.getMonth() + 1}`.padStart(2, '0')
  const day = `${value.getDate()}`.padStart(2, '0')

  return `${year}-${month}-${day}`
}

const getThisWeekFilters = () => {
  const today = new Date()
  const startOfWeek = new Date(today)

  startOfWeek.setDate(today.getDate() - today.getDay())

  return {
    startDate: formatDateInputValue(startOfWeek),
    endDate: formatDateInputValue(today),
  }
}

const Workers_comp_classesList = () => {
  const [filterItems, setFilterItems] = useState<any[]>([])
  const [filters] = useState([
    { label: 'Name', title: 'name' },
    { label: 'Percentage', title: 'percentage', number: 'true' },
  ])
  const [reportFilters, setReportFilters] = useState({
    startDate: '',
    endDate: '',
  })
  const [appliedReportFilters, setAppliedReportFilters] = useState({
    startDate: '',
    endDate: '',
  })
  const [reportData, setReportData] = useState<any>(null)
  const [reportLoading, setReportLoading] = useState(false)
  const [reportError, setReportError] = useState('')

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

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

  const fetchReport = useCallback(async (nextFilters: { startDate: string; endDate: string }) => {
    setReportLoading(true)
    setReportError('')

    try {
      const params: { startDate?: string; endDate?: string } = {}

      if (nextFilters.startDate) {
        params.startDate = nextFilters.startDate
      }

      if (nextFilters.endDate) {
        params.endDate = nextFilters.endDate
      }

      const res = await axios.get('/workers_comp_report/report', { params })
      setReportData(res.data)
      setAppliedReportFilters(nextFilters)
    } catch (error: any) {
      console.error('Failed to fetch workers comp report', error)
      setReportData(null)
      setReportError(
        error?.response?.data?.message || 'Failed to fetch workers comp report.',
      )
    } finally {
      setReportLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchReport({ startDate: '', endDate: '' })
  }, [fetchReport])

  const handleApplyDateFilter = () => {
    fetchReport(reportFilters)
  }

  const handleThisWeekFilter = () => {
    const thisWeekFilters = getThisWeekFilters()
    setReportFilters(thisWeekFilters)
    fetchReport(thisWeekFilters)
  }

  const handleClearDateFilter = () => {
    const clearedFilters = { startDate: '', endDate: '' }
    setReportFilters(clearedFilters)
    fetchReport(clearedFilters)
  }

  const reportHeading = appliedReportFilters.startDate || appliedReportFilters.endDate
    ? `Workman's Comp Totals (${formatDateLabel(appliedReportFilters.startDate) || 'Beginning'} - ${formatDateLabel(appliedReportFilters.endDate) || 'Today'})`
    : "Workman's Comp Totals (All Time)"

  return (
    <>
      <Head>
        <title>{getPageTitle('Workers Comp Classes')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Workers Comp Classes'}
          main
        >
          {hasPermission(currentUser, 'CREATE_WORKERS_COMP_CLASSES') && (
            <div className="flex items-center gap-2">
              <BaseButton color='info' label='Filter' onClick={addFilter} />
              <Link href={'/workers_comp_classes/workers_comp_classes-new'}>
                <BaseButton
                  color="info"
                  icon={mdiPlus}
                  label="New Workers Comp Class"
                />
              </Link>
            </div>
          )}
        </SectionTitleLineWithButton>

        <CardBox className="mb-6">
          <div className="mb-4 flex flex-wrap gap-3">
            <BaseButton
              color="info"
              outline
              label="This Week"
              onClick={handleThisWeekFilter}
              disabled={reportLoading}
            />
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <FormField label="Start Date" labelFor="workers-comp-start-date">
              <input
                id="workers-comp-start-date"
                type="date"
                value={reportFilters.startDate}
                onChange={(event) =>
                  setReportFilters({
                    ...reportFilters,
                    startDate: event.target.value,
                  })
                }
              />
            </FormField>
            <FormField label="End Date" labelFor="workers-comp-end-date">
              <input
                id="workers-comp-end-date"
                type="date"
                value={reportFilters.endDate}
                onChange={(event) =>
                  setReportFilters({
                    ...reportFilters,
                    endDate: event.target.value,
                  })
                }
              />
            </FormField>
            <div className="flex items-end gap-3 pb-6">
              <BaseButton
                color="info"
                label={reportLoading ? 'Applying...' : 'Apply Date Filter'}
                onClick={handleApplyDateFilter}
                disabled={reportLoading}
                className="w-full"
              />
              <BaseButton
                color="info"
                outline
                label="Clear"
                onClick={handleClearDateFilter}
                disabled={reportLoading}
              />
            </div>
          </div>
          {reportError && (
            <div className="mt-2 rounded bg-red-100 p-3 text-red-700">
              {reportError}
            </div>
          )}
        </CardBox>

        {reportData && (
          <CardBox className="mb-6">
            <h3 className="text-xl font-semibold mb-4">{reportHeading}</h3>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="p-4 bg-blue-50 rounded shadow">
                <p className="text-sm text-blue-600 font-bold">Total Work Comp</p>
                <p className="text-2xl font-semibold">
                  ${Number(reportData.totalComp || 0).toFixed(2)}
                </p>
              </div>
              {Object.entries(reportData.totalsByClass || {}).map(([className, total]: any) => (
                <div key={className} className="p-4 bg-gray-50 rounded shadow">
                  <p className="text-sm text-gray-500 font-bold">{className}</p>
                  <p className="text-xl font-semibold">${Number(total).toFixed(2)}</p>
                </div>
              ))}
            </div>
            {!reportLoading && !Object.keys(reportData.totalsByClass || {}).length && (
              <p className="mt-4 text-sm text-gray-500">
                No workers comp totals found for the selected date range.
              </p>
            )}
          </CardBox>
        )}

        <CardBox className="mb-6" hasTable>
          <TableWorkers_comp_classes
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid={false}
          />
        </CardBox>
      </SectionMain>
    </>
  )
}

Workers_comp_classesList.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}

export default Workers_comp_classesList
