'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 StatusFilterTabs from '@/components/StatusFilterTab'
import DateRangePicker from '@/components/RangeDatePicker'

// Updated CashBankType
export type CashBankType = {
  id: number
  date: string
  description: string
  reference: string
  accept: number
  send: number
  balance: number
  status: string
}

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

type CashBankTypeWithAction = CashBankType & {
  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 CashBank
const getStatusColor = (status: string) => {
  switch (status) {
    case 'Transaksi di Apskel':
      return 'info'
    case 'Transaksi di Bank':
      return 'primary'
    case 'Rekonsiliasi':
      return 'success'
    case 'Transaksi Berulang':
      return 'secondary'
    case 'Void':
      return 'error'
    case 'Menunggu Persetujuan':
      return 'warning'
    case 'Di tolak':
      return 'error'
    default:
      return 'default'
  }
}

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

// Sample CashBank data
const cashBankData: CashBankType[] = [
  {
    id: 1,
    date: '2024-01-15',
    description: 'Transfer ke supplier ABC',
    reference: 'TRF-001',
    accept: 0,
    send: 5000000,
    balance: 45000000,
    status: 'Transaksi di Bank'
  },
  {
    id: 2,
    date: '2024-01-16',
    description: 'Pembayaran dari customer XYZ',
    reference: 'PAY-002',
    accept: 10000000,
    send: 0,
    balance: 55000000,
    status: 'Rekonsiliasi'
  },
  {
    id: 3,
    date: '2024-01-17',
    description: 'Pembayaran gaji karyawan',
    reference: 'SALARY-001',
    accept: 0,
    send: 25000000,
    balance: 30000000,
    status: 'Menunggu Persetujuan'
  },
  {
    id: 4,
    date: '2024-01-18',
    description: 'Transfer antar rekening',
    reference: 'TRF-002',
    accept: 0,
    send: 2000000,
    balance: 28000000,
    status: 'Transaksi di Apskel'
  },
  {
    id: 5,
    date: '2024-01-19',
    description: 'Pembayaran otomatis tagihan listrik',
    reference: 'AUTO-001',
    accept: 0,
    send: 1500000,
    balance: 26500000,
    status: 'Transaksi Berulang'
  },
  {
    id: 6,
    date: '2024-01-20',
    description: 'Transfer yang dibatalkan',
    reference: 'TRF-003',
    accept: 0,
    send: 3000000,
    balance: 26500000,
    status: 'Void'
  },
  {
    id: 7,
    date: '2024-01-21',
    description: 'Pembayaran yang ditolak sistem',
    reference: 'PAY-003',
    accept: 0,
    send: 5000000,
    balance: 26500000,
    status: 'Di tolak'
  }
]

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

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

  // States
  const [addTransactionOpen, setAddTransactionOpen] = useState(false)
  const [rowSelection, setRowSelection] = useState({})
  const [currentPage, setCurrentPage] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  const [openConfirm, setOpenConfirm] = useState(false)
  const [transactionId, setTransactionId] = useState('')
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('Semua')
  const [filteredData, setFilteredData] = useState<CashBankType[]>(cashBankData)
  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 = cashBankData

    // Filter by search
    if (search) {
      filtered = filtered.filter(
        transaction =>
          transaction.description.toLowerCase().includes(search.toLowerCase()) ||
          transaction.reference.toLowerCase().includes(search.toLowerCase()) ||
          transaction.status.toLowerCase().includes(search.toLowerCase())
      )
    }

    // Filter by status
    if (statusFilter !== 'Semua') {
      filtered = filtered.filter(transaction => transaction.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 totals from filtered data
  const subtotalAccept = useMemo(() => {
    return filteredData.reduce((sum, transaction) => sum + transaction.accept, 0)
  }, [filteredData])

  const subtotalSend = useMemo(() => {
    return filteredData.reduce((sum, transaction) => sum + transaction.send, 0)
  }, [filteredData])

  const netBalance = subtotalAccept - subtotalSend

  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 handleTransactionClick = (transactionId: string) => {
    console.log('Navigasi ke detail Transaksi:', transactionId)
  }

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

  const columns = useMemo<ColumnDef<CashBankTypeWithAction, 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('date', {
        header: 'Tanggal',
        cell: ({ row }) => <Typography>{row.original.date}</Typography>
      }),
      columnHelper.accessor('description', {
        header: 'Keterangan',
        cell: ({ row }) => (
          <Button
            variant='text'
            color='primary'
            className='p-0 min-w-0 font-medium normal-case justify-start'
            component={Link}
            href={getLocalizedUrl(`/apps/cash-bank/1-10003/detail/transaction/${row.original.id}`, locale as Locale)}
            sx={{
              textTransform: 'none',
              fontWeight: 500,
              '&:hover': {
                textDecoration: 'underline',
                backgroundColor: 'transparent'
              }
            }}
          >
            {row.original.description}
          </Button>
        )
      }),
      columnHelper.accessor('reference', {
        header: 'Referensi',
        cell: ({ row }) => <Typography color='text.secondary'>{row.original.reference || '-'}</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('accept', {
        header: 'Penerimaan',
        cell: ({ row }) => (
          <Typography className={`font-medium ${row.original.accept > 0 ? 'text-green-600' : 'text-gray-500'}`}>
            {row.original.accept > 0 ? formatCurrency(row.original.accept) : '-'}
          </Typography>
        )
      }),
      columnHelper.accessor('send', {
        header: 'Pengeluaran',
        cell: ({ row }) => (
          <Typography className={`font-medium ${row.original.send > 0 ? 'text-red-600' : 'text-gray-500'}`}>
            {row.original.send > 0 ? formatCurrency(row.original.send) : '-'}
          </Typography>
        )
      }),
      columnHelper.accessor('balance', {
        header: 'Saldo',
        cell: ({ row }) => (
          <Typography className={`font-medium ${row.original.balance >= 0 ? 'text-green-600' : 'text-red-600'}`}>
            {formatCurrency(row.original.balance)}
          </Typography>
        )
      })
    ],
    []
  )

  const table = useReactTable({
    data: paginatedData as CashBankType[],
    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',
                'Transaksi di Apskel',
                'Transaksi di Bank',
                'Rekonsiliasi',
                'Transaksi Berulang',
                'Void',
                'Menunggu Persetujuan',
                'Di tolak'
              ]}
              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 Transaksi Cash/Bank'
            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/cashbank/add', locale as Locale)}
            >
              Tambah Transaksi
            </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 className='font-semibold text-lg py-4'>
                    <Typography variant='h6' className='font-semibold text-green-600'>
                      {formatCurrency(subtotalAccept)}
                    </Typography>
                  </td>
                  <td className='font-semibold text-lg py-4'>
                    <Typography variant='h6' className='font-semibold text-red-600'>
                      {formatCurrency(subtotalSend)}
                    </Typography>
                  </td>
                  <td className='font-semibold text-lg py-4'>
                    <Typography
                      variant='h6'
                      className={`font-semibold ${netBalance >= 0 ? 'text-green-600' : 'text-red-600'}`}
                    >
                      {formatCurrency(netBalance)}
                    </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></td>
                  <td className='font-bold text-xl py-4'>
                    <Typography
                      variant='h6'
                      className={`font-bold ${netBalance >= 0 ? 'text-green-600' : 'text-red-600'}`}
                    >
                      {formatCurrency(netBalance)}
                    </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 CashBankDetailTable
