'use client'

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

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

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

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

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

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

// Util Imports
import { getInitials } from '@/utils/getInitials'
import { getLocalizedUrl } from '@/utils/i18n'
import { formatCurrency } from '@/utils/transform'

// Style Imports
import tableStyles from '@core/styles/table.module.css'
import Loading from '@/components/layout/shared/Loading'
import AddEditTierDrawer from './AddTierDrawer'
import DeleteTierDialog from './DeleteTierDialog'
import { Tier } from '@/types/services/tier'
import { useTiers } from '@/services/queries/tier'
import { useTiersMutation } from '@/services/mutations/tier'

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

type TierTypeWithAction = Tier & {
  action?: 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)} />
}

// Helper function to get all benefits as array
const getAllBenefits = (benefits: Record<string, any>): Array<{ key: string; value: any; display: string }> => {
  return Object.entries(benefits).map(([key, value]) => ({
    key,
    value,
    display: formatBenefitDisplay(key, value)
  }))
}

const formatBenefitDisplay = (key: string, value: any): string => {
  // Convert snake_case to readable format
  const readableKey = key.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())

  if (value === true) {
    return readableKey
  }

  if (value === false) {
    return `${readableKey} (Tidak Aktif)`
  }

  if (typeof value === 'number') {
    // Handle multipliers
    if (key.includes('multiplier')) {
      return `${readableKey} ${value}x`
    }
    // Handle percentages
    if (key.includes('discount') || key.includes('bonus')) {
      return `${readableKey} ${value}%`
    }
    // Default number formatting
    return `${readableKey} ${value}`
  }

  return `${readableKey}: ${value}`
}

// Helper function to format points
const formatPoints = (points: number) => {
  return new Intl.NumberFormat('id-ID').format(points)
}

// Mock mutation hook for delete (replace with actual hook)

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

const TierListTable = () => {
  // States
  const [addTierOpen, setAddTierOpen] = useState(false)
  const [editTierData, setEditTierData] = useState<Tier | undefined>(undefined)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [tierToDelete, setTierToDelete] = useState<Tier | null>(null)
  const [rowSelection, setRowSelection] = useState({})
  const [globalFilter, setGlobalFilter] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [search, setSearch] = useState('')

  const { data, isLoading, error, isFetching } = useTiers({
    page: currentPage,
    limit: pageSize,
    search
  })

  const { deleteTier } = useTiersMutation()

  const tiers = data?.data ?? []
  const totalCount = data?.total_count ?? 0

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

  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(1) // Reset to first page
  }, [])

  const handleEditTier = (tier: Tier) => {
    setEditTierData(tier)
    setAddTierOpen(true)
  }

  const handleDeleteTier = (tier: Tier) => {
    setTierToDelete(tier)
    setDeleteDialogOpen(true)
  }

  const handleConfirmDelete = () => {
    if (tierToDelete) {
      deleteTier.mutate(tierToDelete.id, {
        onSuccess: () => {
          console.log('Tier deleted successfully')
          setDeleteDialogOpen(false)
          setTierToDelete(null)
          // You might want to refetch data here
          // refetch()
        },
        onError: error => {
          console.error('Error deleting tier:', error)
          // Handle error (show toast, etc.)
        }
      })
    }
  }

  const handleCloseDeleteDialog = () => {
    if (!deleteTier.isPending) {
      setDeleteDialogOpen(false)
      setTierToDelete(null)
    }
  }

  const handleCloseTierDrawer = () => {
    setAddTierOpen(false)
    setEditTierData(undefined)
  }

  const columns = useMemo<ColumnDef<TierTypeWithAction, 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('name', {
        header: 'Nama Tier',
        cell: ({ row }) => (
          <div className='flex items-center gap-4'>
            <div className='flex flex-col'>
              <Link href={getLocalizedUrl(`/apps/tier/${row.original.id}/detail`, locale as Locale)}>
                <Typography className='font-medium cursor-pointer hover:underline text-primary'>
                  {row.original.name}
                </Typography>
              </Link>
            </div>
          </div>
        )
      }),
      columnHelper.accessor('min_points', {
        header: 'Minimum Poin',
        cell: ({ row }) => (
          <div className='flex items-center gap-2'>
            <Icon className='tabler-star' sx={{ color: 'var(--mui-palette-warning-main)' }} />
            <Typography color='text.primary'>{formatPoints(row.original.min_points)} poin</Typography>
          </div>
        )
      }),
      columnHelper.accessor('benefits', {
        header: 'Manfaat',
        cell: ({ row }) => {
          const allBenefits = getAllBenefits(row.original.benefits)

          if (allBenefits.length === 0) {
            return (
              <Typography variant='body2' color='text.secondary'>
                Tidak ada manfaat
              </Typography>
            )
          }

          return (
            <div className='flex flex-wrap gap-1 max-w-xs'>
              {allBenefits.slice(0, 2).map((benefit, index) => {
                // Different colors for different value types
                let chipColor: 'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' =
                  'secondary'

                if (benefit.value === false) {
                  chipColor = 'default'
                } else if (benefit.value === true) {
                  chipColor = 'success'
                } else if (typeof benefit.value === 'number') {
                  chipColor = 'info'
                }

                return (
                  <Chip
                    key={benefit.key}
                    label={benefit.display}
                    size='small'
                    variant='outlined'
                    color={chipColor}
                    title={benefit.display} // Tooltip for full text
                  />
                )
              })}
              {allBenefits.length > 2 && (
                <Chip
                  label={`+${allBenefits.length - 2} lainnya`}
                  size='small'
                  variant='outlined'
                  color='default'
                  title={allBenefits
                    .slice(2)
                    .map(b => b.display)
                    .join(', ')} // Show remaining benefits in tooltip
                />
              )}
            </div>
          )
        }
      }),
      columnHelper.accessor('created_at', {
        header: 'Tanggal Dibuat',
        cell: ({ row }) => (
          <Typography color='text.primary'>
            {new Date(row.original.created_at).toLocaleDateString('id-ID', {
              year: 'numeric',
              month: 'short',
              day: 'numeric'
            })}
          </Typography>
        )
      }),
      {
        id: 'actions',
        header: 'Aksi',
        cell: ({ row }) => (
          <div className='flex items-center'>
            <OptionMenu
              iconButtonProps={{ size: 'medium' }}
              iconClassName='text-textSecondary text-[22px]'
              options={[
                {
                  text: 'Edit',
                  icon: 'tabler-edit text-[22px]',
                  menuItemProps: {
                    className: 'flex items-center gap-2 text-textSecondary',
                    onClick: () => handleEditTier(row.original)
                  }
                },
                {
                  text: 'Hapus',
                  icon: 'tabler-trash text-[22px]',
                  menuItemProps: {
                    className: 'flex items-center gap-2 text-textSecondary',
                    onClick: () => handleDeleteTier(row.original)
                  }
                }
              ]}
            />
          </div>
        ),
        enableSorting: false
      }
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [locale, handleEditTier, handleDeleteTier]
  )

  const table = useReactTable({
    data: tiers as Tier[],
    columns,
    filterFns: {
      fuzzy: fuzzyFilter
    },
    state: {
      rowSelection,
      globalFilter,
      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'>
          <CustomTextField
            select
            value={table.getState().pagination.pageSize}
            onChange={e => table.setPageSize(Number(e.target.value))}
            className='max-sm:is-full sm:is-[70px]'
          >
            <MenuItem value='10'>10</MenuItem>
            <MenuItem value='25'>25</MenuItem>
            <MenuItem value='50'>50</MenuItem>
          </CustomTextField>
          <div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
            <DebouncedInput
              value={search ?? ''}
              onChange={value => setSearch(value as string)}
              placeholder='Cari Tier'
              className='max-sm:is-full'
            />
            <Button
              color='secondary'
              variant='tonal'
              startIcon={<i className='tabler-upload' />}
              className='max-sm:is-full'
            >
              Ekspor
            </Button>
            <Button
              variant='contained'
              startIcon={<i className='tabler-plus' />}
              onClick={() => setAddTierOpen(!addTierOpen)}
              className='max-sm:is-full'
            >
              Tambah Tier
            </Button>
          </div>
        </div>
        <div className='overflow-x-auto'>
          {isLoading ? (
            <Loading />
          ) : (
            <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>
              {table.getFilteredRowModel().rows.length === 0 ? (
                <tbody>
                  <tr>
                    <td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
                      Tidak ada data tersedia
                    </td>
                  </tr>
                </tbody>
              ) : (
                <tbody>
                  {table
                    .getRowModel()
                    .rows.slice(0, table.getState().pagination.pageSize)
                    .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>
                      )
                    })}
                </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>

      {/* Add/Edit Tier Drawer */}
      <AddEditTierDrawer open={addTierOpen} handleClose={handleCloseTierDrawer} data={editTierData} />

      {/* Delete Confirmation Dialog */}
      <DeleteTierDialog
        open={deleteDialogOpen}
        onClose={handleCloseDeleteDialog}
        onConfirm={handleConfirmDelete}
        tier={tierToDelete}
        isDeleting={deleteTier.isPending}
      />
    </>
  )
}

export default TierListTable
