'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 AccountFormDrawer from './AccountFormDrawer'
import { useChartOfAccount } from '@/services/queries/chartOfAccount'
import { Account, ChartOfAccount } from '@/types/services/chartOfAccount'
import { useAccounts } from '@/services/queries/account'
import { formatCurrency } from '@/utils/transform'
import { useChartOfAccountTypes } from '@/services/queries/chartOfAccountType'

// Account Type
export type AccountType = {
  id: number
  code: string
  name: string
  category: string
  balance: string
}

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

type AccountTypeWithAction = Account & {
  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)} />
}

// Category color mapping for Accounts
const getCategoryColor = (category: string) => {
  switch (category) {
    case 'Kas & Bank':
      return 'success'
    case 'Piutang':
      return 'info'
    case 'Persediaan':
      return 'warning'
    case 'Aset Tetap':
      return 'primary'
    case 'Hutang':
      return 'error'
    case 'Ekuitas':
      return 'secondary'
    case 'Pendapatan':
      return 'success'
    case 'Beban':
      return 'error'
    default:
      return 'default'
  }
}

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

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

  // States
  const [addAccountOpen, setAddAccountOpen] = useState(false)
  const [rowSelection, setRowSelection] = useState({})
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [openConfirm, setOpenConfirm] = useState(false)
  const [accountId, setAccountId] = useState('')
  const [search, setSearch] = useState('')
  const [categoryFilter, setCategoryFilter] = useState<string>('Semua')
  const [editingAccount, setEditingAccount] = useState<Account | null>(null)

  const { data, isLoading } = useAccounts({
    page: currentPage,
    limit: pageSize,
    search
  })

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

  const accounts = data?.data ?? []
  const totalCount = data?.total ?? 0

  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)
  }, [])

  // Handle row click for edit
  const handleRowClick = (account: Account, event: React.MouseEvent) => {
    // Don't trigger row click if clicking on checkbox or link
    const target = event.target as HTMLElement
    if (target.closest('input[type="checkbox"]') || target.closest('a') || target.closest('button')) {
      return
    }

    setEditingAccount(account)
    setAddAccountOpen(true)
  }

  // Handle closing drawer and reset editing state
  const handleCloseDrawer = () => {
    setAddAccountOpen(false)
    setEditingAccount(null)
  }

  const columns = useMemo<ColumnDef<AccountTypeWithAction, 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: 'Kode Akun',
        cell: ({ row }) => (
          <Button
            variant='text'
            color='primary'
            className='p-0 min-w-0 font-medium normal-case justify-start'
            sx={{
              textTransform: 'none',
              fontWeight: 500,
              '&:hover': {
                textDecoration: 'underline',
                backgroundColor: 'transparent'
              }
            }}
          >
            {row.original.number}
          </Button>
        )
      }),
      columnHelper.accessor('name', {
        header: 'Nama Akun',
        cell: ({ row }) => (
          <Typography color='text.primary' className='font-medium'>
            {row.original.name}
          </Typography>
        )
      }),
      columnHelper.accessor('chart_of_account.name', {
        header: 'Kategori',
        cell: ({ row }) => (
          <Typography color='text.primary' className='font-medium'>
            {row.original.chart_of_account.name}
          </Typography>
        )
      }),
      columnHelper.accessor('current_balance', {
        header: 'Saldo',
        cell: ({ row }) => {
          return (
            <Typography className='font-medium text-right text-primary'>
              {row.original.current_balance < 0 ? '-' : ''}
              {formatCurrency(row.original.current_balance)}
            </Typography>
          )
        }
      })
    ],
    [locale]
  )

  const table = useReactTable({
    data: accounts as Account[],
    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>
        <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 Akun'
            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'
              className='max-sm:is-full is-auto'
              startIcon={<i className='tabler-plus' />}
              onClick={() => {
                setEditingAccount(null)
                setAddAccountOpen(true)
              }}
            >
              Tambah Akun
            </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>
            {accounts.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(),
                        'cursor-pointer hover:bg-gray-50': true
                      })}
                      onClick={e => handleRowClick(row.original, e)}
                    >
                      {row.getVisibleCells().map(cell => (
                        <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</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]}
          disabled={isLoading}
        />
      </Card>
      {/* <AccountFormDrawer
        open={addAccountOpen}
        handleClose={handleCloseDrawer}
        accountData={data}
        setData={setData}
        editingAccount={editingAccount}
      /> */}
    </>
  )
}

export default AccountListTable
