'use client'

// React Imports
import { useCallback, useEffect, useMemo, useState } from 'react'

// Next Imports
import Link from 'next/link'
import { useParams } from 'next/navigation'

// MUI Imports
import Button from '@mui/material/Button'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import Checkbox from '@mui/material/Checkbox'
import Chip from '@mui/material/Chip'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import { styled } from '@mui/material/styles'
import type { TextFieldProps } from '@mui/material/TextField'
import Typography from '@mui/material/Typography'

// Third-party Imports
import type { RankingInfo } from '@tanstack/match-sorter-utils'
import { rankItem } from '@tanstack/match-sorter-utils'
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import classnames from 'classnames'

// Type Imports
import type { Locale } from '@configs/i18n'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import OptionMenu from '@core/components/option-menu'

// Style Imports
import tableStyles from '@core/styles/table.module.css'
import { Box, CircularProgress, TablePagination } from '@mui/material'
import { useDispatch } from 'react-redux'
import TablePaginationComponent from '@/components/TablePaginationComponent'
import Loading from '@/components/layout/shared/Loading'
import { getLocalizedUrl } from '@/utils/i18n'
import { ExpenseType } from '@/types/apps/expenseType'
import { expenseData } from '@/data/dummy/expense'
import StatusFilterTabs from '@/components/StatusFilterTab'
import DateRangePicker from '@/components/RangeDatePicker'

declare module '@tanstack/table-core' {
  interface FilterFns {
    fuzzy: FilterFn<unknown>
  }
  interface FilterMeta {
    itemRank: RankingInfo
  }
}

type ExpenseTypeWithAction = ExpenseType & {
  actions?: string
}

// Styled Components
const Icon = styled('i')({})

const fuzzyFilter: FilterFn<any> = (row, columnId, value, addMeta) => {
  // Rank the item
  const itemRank = rankItem(row.getValue(columnId), value)

  // Store the itemRank info
  addMeta({
    itemRank
  })

  // Return if the item should be filtered in/out
  return itemRank.passed
}

const DebouncedInput = ({
  value: initialValue,
  onChange,
  debounce = 500,
  ...props
}: {
  value: string | number
  onChange: (value: string | number) => void
  debounce?: number
} & Omit<TextFieldProps, 'onChange'>) => {
  // States
  const [value, setValue] = useState(initialValue)

  useEffect(() => {
    setValue(initialValue)
  }, [initialValue])

  useEffect(() => {
    const timeout = setTimeout(() => {
      onChange(value)
    }, debounce)

    return () => clearTimeout(timeout)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value])

  return <CustomTextField {...props} value={value} onChange={e => setValue(e.target.value)} />
}

// Status color mapping for Expense
const getStatusColor = (status: string) => {
  switch (status) {
    case 'Belum Dibayar':
      return 'error'
    case 'Dibayar Sebagian':
      return 'warning'
    case 'Lunas':
      return 'success'
    default:
      return 'default'
  }
}

// Format currency
const formatCurrency = (amount: number) => {
  return new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    minimumFractionDigits: 0
  }).format(amount)
}

// Column Definitions
const columnHelper = createColumnHelper<ExpenseTypeWithAction>()

const ExpenseListTable = () => {
  const dispatch = useDispatch()

  // States
  const [addExpenseOpen, setAddExpenseOpen] = useState(false)
  const [rowSelection, setRowSelection] = useState({})
  const [currentPage, setCurrentPage] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  const [openConfirm, setOpenConfirm] = useState(false)
  const [expenseId, setExpenseId] = useState('')
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('Semua')
  const [filteredData, setFilteredData] = useState<ExpenseType[]>(expenseData)
  const [startDate, setStartDate] = useState<Date | null>(new Date())
  const [endDate, setEndDate] = useState<Date | null>(new Date())

  // Hooks
  const { lang: locale } = useParams()

  // Filter data based on search and status
  useEffect(() => {
    let filtered = expenseData

    // Filter by search
    if (search) {
      filtered = filtered.filter(
        expense =>
          expense.number.toLowerCase().includes(search.toLowerCase()) ||
          expense.benefeciaryName.toLowerCase().includes(search.toLowerCase()) ||
          expense.benefeciaryCompany.toLowerCase().includes(search.toLowerCase()) ||
          expense.status.toLowerCase().includes(search.toLowerCase()) ||
          expense.reference.toLowerCase().includes(search.toLowerCase())
      )
    }

    // Filter by status
    if (statusFilter !== 'Semua') {
      filtered = filtered.filter(expense => expense.status === statusFilter)
    }

    setFilteredData(filtered)
    setCurrentPage(0)
  }, [search, statusFilter])

  const totalCount = filteredData.length
  const paginatedData = useMemo(() => {
    const startIndex = currentPage * pageSize
    return filteredData.slice(startIndex, startIndex + pageSize)
  }, [filteredData, currentPage, pageSize])

  // Calculate subtotal and total from filtered data
  const subtotalBalanceDue = useMemo(() => {
    return filteredData.reduce((sum, expense) => sum + expense.balanceDue, 0)
  }, [filteredData])

  const subtotalTotal = useMemo(() => {
    return filteredData.reduce((sum, expense) => sum + expense.total, 0)
  }, [filteredData])

  const taxAmount = subtotalTotal * 0.1 // 10% tax example
  const finalTotal = subtotalTotal + taxAmount

  const handlePageChange = useCallback((event: unknown, newPage: number) => {
    setCurrentPage(newPage)
  }, [])

  const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const newPageSize = parseInt(event.target.value, 10)
    setPageSize(newPageSize)
    setCurrentPage(0)
  }, [])

  const handleDelete = () => {
    setOpenConfirm(false)
  }

  const handleExpenseClick = (expenseId: string) => {
    console.log('Navigasi ke detail Expense:', expenseId)
  }

  const handleStatusFilter = (status: string) => {
    setStatusFilter(status)
  }

  const columns = useMemo<ColumnDef<ExpenseTypeWithAction, any>[]>(
    () => [
      {
        id: 'select',
        header: ({ table }) => (
          <Checkbox
            {...{
              checked: table.getIsAllRowsSelected(),
              indeterminate: table.getIsSomeRowsSelected(),
              onChange: table.getToggleAllRowsSelectedHandler()
            }}
          />
        ),
        cell: ({ row }) => (
          <Checkbox
            {...{
              checked: row.getIsSelected(),
              disabled: !row.getCanSelect(),
              indeterminate: row.getIsSomeSelected(),
              onChange: row.getToggleSelectedHandler()
            }}
          />
        )
      },
      columnHelper.accessor('number', {
        header: 'Nomor Expense',
        cell: ({ row }) => (
          <Button
            variant='text'
            color='primary'
            className='p-0 min-w-0 font-medium normal-case justify-start'
            onClick={() => handleExpenseClick(row.original.id.toString())}
            sx={{
              textTransform: 'none',
              fontWeight: 500,
              '&:hover': {
                textDecoration: 'underline',
                backgroundColor: 'transparent'
              }
            }}
          >
            {row.original.number}
          </Button>
        )
      }),
      columnHelper.accessor('benefeciaryName', {
        header: 'Beneficiary',
        cell: ({ row }) => (
          <div className='flex flex-col'>
            <Typography color='text.primary' className='font-medium'>
              {row.original.benefeciaryName}
            </Typography>
            <Typography variant='body2' color='text.secondary'>
              {row.original.benefeciaryCompany}
            </Typography>
          </div>
        )
      }),
      columnHelper.accessor('reference', {
        header: 'Referensi',
        cell: ({ row }) => <Typography color='text.secondary'>{row.original.reference || '-'}</Typography>
      }),
      columnHelper.accessor('date', {
        header: 'Tanggal',
        cell: ({ row }) => <Typography>{row.original.date}</Typography>
      }),
      columnHelper.accessor('status', {
        header: 'Status',
        cell: ({ row }) => (
          <div className='flex items-center gap-3'>
            <Chip
              variant='tonal'
              label={row.original.status}
              size='small'
              color={getStatusColor(row.original.status) as any}
              className='capitalize'
            />
          </div>
        )
      }),
      columnHelper.accessor('balanceDue', {
        header: 'Sisa Tagihan',
        cell: ({ row }) => (
          <Typography className={`font-medium ${row.original.balanceDue > 0 ? 'text-red-600' : 'text-green-600'}`}>
            {formatCurrency(row.original.balanceDue)}
          </Typography>
        )
      }),
      columnHelper.accessor('total', {
        header: 'Total',
        cell: ({ row }) => <Typography className='font-medium'>{formatCurrency(row.original.total)}</Typography>
      })
    ],
    []
  )

  const table = useReactTable({
    data: paginatedData as ExpenseType[],
    columns,
    filterFns: {
      fuzzy: fuzzyFilter
    },
    state: {
      rowSelection,
      pagination: {
        pageIndex: currentPage,
        pageSize
      }
    },
    enableRowSelection: true,
    onRowSelectionChange: setRowSelection,
    getCoreRowModel: getCoreRowModel(),
    manualPagination: true,
    pageCount: Math.ceil(totalCount / pageSize)
  })

  return (
    <>
      <Card>
        {/* Filter Status Tabs and Range Date */}
        <div className='p-6 border-bs'>
          <div className='flex items-center justify-between'>
            <StatusFilterTabs
              statusOptions={[
                'Semua',
                'Belum Dibayar',
                'Dibayar Sebagian',
                'Lunas',
                'Jatuh Tempo',
                'Transaksi Berulang'
              ]}
              selectedStatus={statusFilter}
              onStatusChange={handleStatusFilter}
            />
            <DateRangePicker
              startDate={startDate}
              endDate={endDate}
              onStartDateChange={setStartDate}
              onEndDateChange={setEndDate}
            />
          </div>
        </div>

        <div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
          <DebouncedInput
            value={search}
            onChange={value => setSearch(value as string)}
            placeholder='Cari Expense'
            className='max-sm:is-full'
          />
          <div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
            <CustomTextField
              select
              value={pageSize}
              onChange={handlePageSizeChange}
              className='max-sm:is-full sm:is-[70px]'
            >
              <MenuItem value={10}>10</MenuItem>
              <MenuItem value={25}>25</MenuItem>
              <MenuItem value={50}>50</MenuItem>
            </CustomTextField>
            <Button
              color='secondary'
              variant='tonal'
              startIcon={<i className='tabler-upload' />}
              className='max-sm:is-full'
            >
              Ekspor
            </Button>
            <Button
              variant='contained'
              component={Link}
              className='max-sm:is-full is-auto'
              startIcon={<i className='tabler-plus' />}
              href={getLocalizedUrl('/apps/expenses/add', locale as Locale)}
            >
              Tambah
            </Button>
          </div>
        </div>
        <div className='overflow-x-auto'>
          <table className={tableStyles.table}>
            <thead>
              {table.getHeaderGroups().map(headerGroup => (
                <tr key={headerGroup.id}>
                  {headerGroup.headers.map(header => (
                    <th key={header.id}>
                      {header.isPlaceholder ? null : (
                        <>
                          <div
                            className={classnames({
                              'flex items-center': header.column.getIsSorted(),
                              'cursor-pointer select-none': header.column.getCanSort()
                            })}
                            onClick={header.column.getToggleSortingHandler()}
                          >
                            {flexRender(header.column.columnDef.header, header.getContext())}
                            {{
                              asc: <i className='tabler-chevron-up text-xl' />,
                              desc: <i className='tabler-chevron-down text-xl' />
                            }[header.column.getIsSorted() as 'asc' | 'desc'] ?? null}
                          </div>
                        </>
                      )}
                    </th>
                  ))}
                </tr>
              ))}
            </thead>
            {filteredData.length === 0 ? (
              <tbody>
                <tr>
                  <td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
                    Tidak ada data tersedia
                  </td>
                </tr>
              </tbody>
            ) : (
              <tbody>
                {table.getRowModel().rows.map(row => {
                  return (
                    <tr key={row.id} className={classnames({ selected: row.getIsSelected() })}>
                      {row.getVisibleCells().map(cell => (
                        <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
                      ))}
                    </tr>
                  )
                })}

                {/* Subtotal Row */}
                <tr className='border-t-2 bg-gray-50'>
                  <td className='font-semibold text-lg py-4'>
                    <Typography variant='h6' className='font-semibold'>
                      Subtotal
                    </Typography>
                  </td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td className='font-semibold text-lg py-4'>
                    <Typography variant='h6' className='font-semibol'>
                      {formatCurrency(subtotalBalanceDue)}
                    </Typography>
                  </td>
                  <td className='font-semibold text-lg py-4'>
                    <Typography variant='h6' className='font-semibold'>
                      {formatCurrency(subtotalTotal)}
                    </Typography>
                  </td>
                </tr>

                {/* Total Row */}
                <tr className='border-t bg-gray-100'>
                  <td className='font-bold text-xl py-4'>
                    <Typography variant='h6' className='font-bold'>
                      Total
                    </Typography>
                  </td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td></td>
                  <td className='font-bold text-xl py-4'>
                    <Typography variant='h6' className='font-bold'>
                      {formatCurrency(subtotalBalanceDue + taxAmount)}
                    </Typography>
                  </td>
                  <td className='font-bold text-xl py-4'>
                    <Typography variant='h6' className='font-bold'>
                      {formatCurrency(finalTotal)}
                    </Typography>
                  </td>
                </tr>
              </tbody>
            )}
          </table>
        </div>

        <TablePagination
          component={() => (
            <TablePaginationComponent
              pageIndex={currentPage}
              pageSize={pageSize}
              totalCount={totalCount}
              onPageChange={handlePageChange}
            />
          )}
          count={totalCount}
          rowsPerPage={pageSize}
          page={currentPage}
          onPageChange={handlePageChange}
          onRowsPerPageChange={handlePageSizeChange}
          rowsPerPageOptions={[10, 25, 50]}
        />
      </Card>
    </>
  )
}

export default ExpenseListTable
