'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 AddEditWheelSpinDrawer from './AddEditWheelSpinDrawer'

// WheelSpin Type Interface
export interface WheelSpinType {
  id: string
  name: string
  weight: number
  omset: number
  fallback: boolean
  stock?: number
  createdAt: Date
  updatedAt: Date
}

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

type WheelSpinTypeWithAction = WheelSpinType & {
  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)} />
}

// Dummy data for wheel spin prizes
const DUMMY_WHEEL_SPIN_DATA: WheelSpinType[] = [
  {
    id: '1',
    name: 'Diskon 10%',
    weight: 25,
    omset: 500000,
    fallback: false,
    stock: 100,
    createdAt: new Date('2024-01-15'),
    updatedAt: new Date('2024-02-10')
  },
  {
    id: '2',
    name: 'Gratis Ongkir',
    weight: 30,
    omset: 200000,
    fallback: false,
    stock: 200,
    createdAt: new Date('2024-01-20'),
    updatedAt: new Date('2024-02-15')
  },
  {
    id: '3',
    name: 'Cashback 50k',
    weight: 15,
    omset: 1000000,
    fallback: false,
    stock: 50,
    createdAt: new Date('2024-01-25'),
    updatedAt: new Date('2024-02-20')
  },
  {
    id: '4',
    name: 'Voucher 100k',
    weight: 10,
    omset: 2000000,
    fallback: false,
    stock: 25,
    createdAt: new Date('2024-02-01'),
    updatedAt: new Date('2024-02-25')
  },
  {
    id: '5',
    name: 'Poin 500',
    weight: 35,
    omset: 100000,
    fallback: false,
    stock: 500,
    createdAt: new Date('2024-02-05'),
    updatedAt: new Date('2024-03-01')
  },
  {
    id: '6',
    name: 'Produk Gratis',
    weight: 5,
    omset: 5000000,
    fallback: false,
    stock: 10,
    createdAt: new Date('2024-02-10'),
    updatedAt: new Date('2024-03-05')
  },
  {
    id: '7',
    name: 'Coba Lagi',
    weight: 50,
    omset: 0,
    fallback: true,
    createdAt: new Date('2024-02-15'),
    updatedAt: new Date('2024-03-10')
  },
  {
    id: '8',
    name: 'Double Poin',
    weight: 20,
    omset: 750000,
    fallback: false,
    stock: 75,
    createdAt: new Date('2024-03-01'),
    updatedAt: new Date('2024-03-15')
  },
  {
    id: '9',
    name: 'Mystery Box',
    weight: 8,
    omset: 1500000,
    fallback: false,
    stock: 30,
    createdAt: new Date('2024-03-05'),
    updatedAt: new Date('2024-03-20')
  },
  {
    id: '10',
    name: 'Diskon 25%',
    weight: 12,
    omset: 3000000,
    fallback: false,
    stock: 20,
    createdAt: new Date('2024-03-10'),
    updatedAt: new Date('2024-03-25')
  }
]

// Mock data hook with dummy data
const useWheelSpin = ({ page, limit, search }: { page: number; limit: number; search: string }) => {
  const [isLoading, setIsLoading] = useState(false)

  // Simulate loading
  useEffect(() => {
    setIsLoading(true)
    const timer = setTimeout(() => setIsLoading(false), 500)
    return () => clearTimeout(timer)
  }, [page, limit, search])

  // Filter data based on search
  const filteredData = useMemo(() => {
    if (!search) return DUMMY_WHEEL_SPIN_DATA

    return DUMMY_WHEEL_SPIN_DATA.filter(wheelSpin => wheelSpin.name.toLowerCase().includes(search.toLowerCase()))
  }, [search])

  // Paginate data
  const paginatedData = useMemo(() => {
    const startIndex = (page - 1) * limit
    const endIndex = startIndex + limit
    return filteredData.slice(startIndex, endIndex)
  }, [filteredData, page, limit])

  return {
    data: {
      wheelSpins: paginatedData,
      total_count: filteredData.length
    },
    isLoading,
    error: null,
    isFetching: isLoading
  }
}

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

const WheelSpinListTable = () => {
  // States
  const [addWheelSpinOpen, setAddWheelSpinOpen] = useState(false)
  const [editWheelSpinData, setEditWheelSpinData] = useState<WheelSpinType | undefined>(undefined)
  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 } = useWheelSpin({
    page: currentPage,
    limit: pageSize,
    search
  })

  const wheelSpins = data?.wheelSpins ?? []
  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 handleEditWheelSpin = (wheelSpin: WheelSpinType) => {
    setEditWheelSpinData(wheelSpin)
    setAddWheelSpinOpen(true)
  }

  const handleDeleteWheelSpin = (wheelSpinId: string) => {
    if (confirm('Apakah Anda yakin ingin menghapus hadiah wheel spin ini?')) {
      console.log('Deleting wheel spin:', wheelSpinId)
      // Add your delete logic here
      // deleteWheelSpin.mutate(wheelSpinId)
    }
  }

  const handleCloseWheelSpinDrawer = () => {
    setAddWheelSpinOpen(false)
    setEditWheelSpinData(undefined)
  }

  const columns = useMemo<ColumnDef<WheelSpinTypeWithAction, 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 Hadiah',
        cell: ({ row }) => (
          <div className='flex items-center gap-4'>
            <div className='flex flex-col'>
              <Link href={getLocalizedUrl(`/apps/wheel-spin/${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('weight', {
        header: 'Bobot',
        cell: ({ row }) => (
          <div className='flex items-center gap-2'>
            <Icon className='tabler-percentage' sx={{ color: 'var(--mui-palette-primary-main)' }} />
            <Typography color='text.primary'>{row.original.weight}%</Typography>
          </div>
        )
      }),
      columnHelper.accessor('omset', {
        header: 'Min. Omset',
        cell: ({ row }) => (
          <div className='flex items-center gap-2'>
            <Icon className='tabler-coin' sx={{ color: 'var(--mui-palette-success-main)' }} />
            <Typography color='text.primary'>{formatCurrency(row.original.omset)}</Typography>
          </div>
        )
      }),
      columnHelper.accessor('stock', {
        header: 'Stok',
        cell: ({ row }) => (
          <div className='flex items-center gap-2'>
            {row.original.stock !== undefined ? (
              <>
                <Icon className='tabler-package' sx={{ color: 'var(--mui-palette-info-main)' }} />
                <Typography color='text.primary'>{row.original.stock}</Typography>
              </>
            ) : (
              <Typography color='text.secondary'>Unlimited</Typography>
            )}
          </div>
        )
      }),
      columnHelper.accessor('fallback', {
        header: 'Status',
        cell: ({ row }) => (
          <Chip
            label={row.original.fallback ? 'Fallback' : 'Aktif'}
            color={row.original.fallback ? 'warning' : 'success'}
            variant='tonal'
            size='small'
          />
        )
      }),
      columnHelper.accessor('createdAt', {
        header: 'Tanggal Dibuat',
        cell: ({ row }) => (
          <Typography color='text.primary'>
            {new Date(row.original.createdAt).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: () => handleEditWheelSpin(row.original)
                  }
                },
                {
                  text: 'Hapus',
                  icon: 'tabler-trash text-[22px]',
                  menuItemProps: {
                    className: 'flex items-center gap-2 text-textSecondary',
                    onClick: () => handleDeleteWheelSpin(row.original.id)
                  }
                }
              ]}
            />
          </div>
        ),
        enableSorting: false
      }
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [locale, handleEditWheelSpin, handleDeleteWheelSpin]
  )

  const table = useReactTable({
    data: wheelSpins as WheelSpinType[],
    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 Hadiah Wheel Spin'
              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={() => setAddWheelSpinOpen(!addWheelSpinOpen)}
              className='max-sm:is-full'
            >
              Tambah Hadiah
            </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>
      <AddEditWheelSpinDrawer
        open={addWheelSpinOpen}
        handleClose={handleCloseWheelSpinDrawer}
        data={editWheelSpinData}
      />
    </>
  )
}

export default WheelSpinListTable
