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

// Voucher Type Interface
export interface VoucherType {
  id: number
  code: string
  type: 'discount' | 'cashback' | 'free_shipping' | 'product'
  discountType?: 'fixed' | 'percent'
  discountValue?: number
  minPurchase?: number
  validFrom: string
  validUntil: string
  isActive: boolean
}

// Main Voucher Catalog Type Interface
export interface VoucherCatalogType {
  id: string
  name: string
  description?: string
  pointCost: number
  stock?: number
  isActive: boolean
  validUntil?: Date
  imageUrl?: string
  createdAt: Date
  updatedAt: Date
  // Voucher-specific fields
  code: string
  type: 'discount' | 'cashback' | 'free_shipping' | 'product'
  discountType?: 'fixed' | 'percent'
  discountValue?: number
  minPurchase?: number
  validFrom: string
}

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

type VoucherCatalogTypeWithAction = VoucherCatalogType & {
  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)} />
}

// Updated dummy data with integrated voucher information
const DUMMY_VOUCHER_DATA: VoucherCatalogType[] = [
  {
    id: '1',
    name: 'Voucher Diskon 50K',
    description: 'Voucher diskon Rp 50.000 untuk pembelian minimal Rp 200.000',
    pointCost: 500,
    stock: 100,
    isActive: true,
    validUntil: new Date('2024-12-31'),
    imageUrl: 'https://example.com/voucher-50k.jpg',
    createdAt: new Date('2024-01-15'),
    updatedAt: new Date('2024-02-10'),
    code: 'DISC50K',
    type: 'discount',
    discountType: 'fixed',
    discountValue: 50000,
    minPurchase: 200000,
    validFrom: '2024-01-15'
  },
  {
    id: '2',
    name: 'Free Shipping Voucher',
    description: 'Gratis ongkos kirim untuk seluruh Indonesia',
    pointCost: 200,
    stock: 500,
    isActive: true,
    validUntil: new Date('2024-06-30'),
    imageUrl: 'https://example.com/free-shipping.jpg',
    createdAt: new Date('2024-01-20'),
    updatedAt: new Date('2024-02-15'),
    code: 'FREESHIP',
    type: 'free_shipping',
    validFrom: '2024-01-20'
  },
  {
    id: '3',
    name: 'Bluetooth Speaker Premium',
    description: 'Speaker bluetooth kualitas premium dengan bass yang menggelegar',
    pointCost: 2500,
    stock: 25,
    isActive: true,
    validUntil: new Date('2024-09-30'),
    imageUrl: 'https://example.com/bluetooth-speaker.jpg',
    createdAt: new Date('2024-01-25'),
    updatedAt: new Date('2024-02-20'),
    code: 'SPEAKER25',
    type: 'product',
    validFrom: '2024-01-25'
  },
  {
    id: '4',
    name: 'Voucher Cashback 20%',
    description: 'Cashback 20% maksimal Rp 100.000 untuk kategori elektronik',
    pointCost: 800,
    stock: 200,
    isActive: true,
    validUntil: new Date('2024-08-31'),
    createdAt: new Date('2024-02-01'),
    updatedAt: new Date('2024-02-25'),
    code: 'CASHBACK20',
    type: 'cashback',
    discountType: 'percent',
    discountValue: 20,
    minPurchase: 100000,
    validFrom: '2024-02-01'
  },
  {
    id: '5',
    name: 'Smartwatch Fitness',
    description: 'Smartwatch dengan fitur fitness tracking dan heart rate monitor',
    pointCost: 5000,
    stock: 15,
    isActive: true,
    validUntil: new Date('2024-12-31'),
    createdAt: new Date('2024-02-05'),
    updatedAt: new Date('2024-03-01'),
    code: 'WATCH15',
    type: 'product',
    validFrom: '2024-02-05'
  },
  {
    id: '6',
    name: 'Tumbler Stainless Premium',
    description: 'Tumbler stainless steel 500ml dengan desain eksklusif',
    pointCost: 1200,
    stock: 50,
    isActive: true,
    validUntil: new Date('2024-10-31'),
    createdAt: new Date('2024-02-10'),
    updatedAt: new Date('2024-03-05'),
    code: 'TUMBLER50',
    type: 'product',
    validFrom: '2024-02-10'
  },
  {
    id: '7',
    name: 'Gift Card 100K',
    description: 'Gift card senilai Rp 100.000 yang bisa digunakan untuk semua produk',
    pointCost: 1000,
    stock: 300,
    isActive: true,
    validUntil: new Date('2024-12-31'),
    createdAt: new Date('2024-02-15'),
    updatedAt: new Date('2024-03-10'),
    code: 'GIFT100K',
    type: 'discount',
    discountType: 'fixed',
    discountValue: 100000,
    validFrom: '2024-02-15'
  },
  {
    id: '8',
    name: 'Wireless Earbuds',
    description: 'Earbuds wireless dengan noise cancellation dan case charging',
    pointCost: 3500,
    stock: 30,
    isActive: true,
    validUntil: new Date('2024-11-30'),
    createdAt: new Date('2024-03-01'),
    updatedAt: new Date('2024-03-15'),
    code: 'EARBUDS30',
    type: 'product',
    validFrom: '2024-03-01'
  },
  {
    id: '9',
    name: 'Voucher Buy 1 Get 1',
    description: 'Beli 1 gratis 1 untuk kategori fashion wanita',
    pointCost: 600,
    stock: 150,
    isActive: false,
    validUntil: new Date('2024-07-31'),
    createdAt: new Date('2024-03-05'),
    updatedAt: new Date('2024-03-20'),
    code: 'BUY1GET1',
    type: 'discount',
    discountType: 'percent',
    discountValue: 50,
    minPurchase: 50000,
    validFrom: '2024-03-05'
  },
  {
    id: '10',
    name: 'Power Bank 20000mAh',
    description: 'Power bank fast charging 20000mAh dengan 3 port USB',
    pointCost: 1800,
    stock: 40,
    isActive: true,
    validUntil: new Date('2024-12-31'),
    createdAt: new Date('2024-03-10'),
    updatedAt: new Date('2024-03-25'),
    code: 'POWERBANK40',
    type: 'product',
    validFrom: '2024-03-10'
  }
]

// Helper function to get voucher type display text
const getVoucherTypeDisplay = (type: string) => {
  const typeMap = {
    discount: 'Diskon',
    cashback: 'Cashback',
    free_shipping: 'Gratis Ongkir',
    product: 'Produk'
  }
  return typeMap[type as keyof typeof typeMap] || type
}

// Helper function to get voucher value display
const getVoucherValueDisplay = (voucher: VoucherCatalogType) => {
  if (voucher.type === 'free_shipping') return 'Gratis Ongkir'
  if (voucher.type === 'product') return 'Produk Fisik'

  if (voucher.discountValue) {
    if (voucher.discountType === 'percent') {
      return `${voucher.discountValue}%`
    } else {
      return formatCurrency(voucher.discountValue)
    }
  }

  return '-'
}

// Mock data hook with dummy data
const useVoucherCatalog = ({ 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_VOUCHER_DATA

    return DUMMY_VOUCHER_DATA.filter(
      voucher =>
        voucher.name.toLowerCase().includes(search.toLowerCase()) ||
        voucher.description?.toLowerCase().includes(search.toLowerCase()) ||
        voucher.code.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: {
      vouchers: paginatedData,
      total_count: filteredData.length
    },
    isLoading,
    error: null,
    isFetching: isLoading
  }
}

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

const VoucherListTable = () => {
  // States
  const [addVoucherOpen, setAddVoucherOpen] = useState(false)
  const [editVoucherData, setEditVoucherData] = useState<VoucherCatalogType | 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 } = useVoucherCatalog({
    page: currentPage,
    limit: pageSize,
    search
  })

  const vouchers = data?.vouchers ?? []
  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 handleEditVoucher = (voucher: VoucherCatalogType) => {
    setEditVoucherData(voucher)
    setAddVoucherOpen(true)
  }

  const handleDeleteVoucher = (voucherId: string) => {
    if (confirm('Apakah Anda yakin ingin menghapus voucher ini?')) {
      console.log('Deleting voucher:', voucherId)
      // Add your delete logic here
      // deleteVoucher.mutate(voucherId)
    }
  }

  const handleToggleActive = (voucherId: string, currentStatus: boolean) => {
    console.log('Toggling active status for voucher:', voucherId, !currentStatus)
    // Add your toggle logic here
    // toggleVoucherStatus.mutate({ id: voucherId, isActive: !currentStatus })
  }

  const handleCloseVoucherDrawer = () => {
    setAddVoucherOpen(false)
    setEditVoucherData(undefined)
  }

  const columns = useMemo<ColumnDef<VoucherCatalogTypeWithAction, 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 Voucher',
        cell: ({ row }) => (
          <div className='flex items-center gap-4'>
            <CustomAvatar src={row.original.imageUrl} size={40}>
              {getInitials(row.original.name)}
            </CustomAvatar>
            <div className='flex flex-col'>
              <Link href={getLocalizedUrl(`/apps/vouchers/${row.original.id}/detail`, locale as Locale)}>
                <Typography className='font-medium cursor-pointer hover:underline text-primary'>
                  {row.original.name}
                </Typography>
              </Link>
              {row.original.description && (
                <Typography variant='caption' color='textSecondary' className='max-w-xs truncate'>
                  {row.original.description}
                </Typography>
              )}
              <Typography variant='caption' color='textSecondary' className='font-mono'>
                {row.original.code}
              </Typography>
            </div>
          </div>
        )
      }),
      columnHelper.accessor('type', {
        header: 'Tipe Voucher',
        cell: ({ row }) => {
          const typeColors = {
            discount: 'primary',
            cashback: 'success',
            free_shipping: 'info',
            product: 'warning'
          } as const

          return (
            <Chip
              label={getVoucherTypeDisplay(row.original.type)}
              color={typeColors[row.original.type] || 'default'}
              variant='tonal'
              size='small'
            />
          )
        }
      }),
      columnHelper.accessor('discountValue', {
        header: 'Nilai Voucher',
        cell: ({ row }) => (
          <Typography color='text.primary' className='font-medium'>
            {getVoucherValueDisplay(row.original)}
          </Typography>
        )
      }),
      columnHelper.accessor('pointCost', {
        header: 'Biaya Poin',
        cell: ({ row }) => (
          <div className='flex items-center gap-2'>
            <Icon className='tabler-star-filled' sx={{ color: 'var(--mui-palette-warning-main)' }} />
            <Typography color='text.primary' className='font-medium'>
              {row.original.pointCost.toLocaleString('id-ID')} poin
            </Typography>
          </div>
        )
      }),
      columnHelper.accessor('minPurchase', {
        header: 'Min. Pembelian',
        cell: ({ row }) => (
          <Typography color='text.primary'>
            {row.original.minPurchase ? formatCurrency(row.original.minPurchase) : '-'}
          </Typography>
        )
      }),
      columnHelper.accessor('stock', {
        header: 'Stok',
        cell: ({ row }) => {
          const stock = row.original.stock
          const stockColor = stock === 0 ? 'error' : stock && stock <= 10 ? 'warning' : 'success'
          const stockText = stock === undefined ? 'Unlimited' : stock === 0 ? 'Habis' : stock.toString()

          return <Chip label={stockText} color={stockColor} variant='tonal' size='small' />
        }
      }),
      columnHelper.accessor('isActive', {
        header: 'Status',
        cell: ({ row }) => (
          <Chip
            label={row.original.isActive ? 'Aktif' : 'Nonaktif'}
            color={row.original.isActive ? 'success' : 'error'}
            variant='tonal'
            size='small'
          />
        )
      }),
      columnHelper.accessor('validUntil', {
        header: 'Berlaku Hingga',
        cell: ({ row }) => (
          <Typography color='text.primary'>
            {row.original.validUntil
              ? new Date(row.original.validUntil).toLocaleDateString('id-ID', {
                  year: 'numeric',
                  month: 'short',
                  day: 'numeric'
                })
              : 'Tidak terbatas'}
          </Typography>
        )
      }),
      {
        id: 'actions',
        header: 'Aksi',
        cell: ({ row }) => (
          <div className='flex items-center'>
            <OptionMenu
              iconButtonProps={{ size: 'medium' }}
              iconClassName='text-textSecondary text-[22px]'
              options={[
                {
                  text: row.original.isActive ? 'Nonaktifkan' : 'Aktifkan',
                  icon: row.original.isActive ? 'tabler-eye-off text-[22px]' : 'tabler-eye text-[22px]',
                  menuItemProps: {
                    className: 'flex items-center gap-2 text-textSecondary',
                    onClick: () => handleToggleActive(row.original.id, row.original.isActive)
                  }
                },
                {
                  text: 'Edit',
                  icon: 'tabler-edit text-[22px]',
                  menuItemProps: {
                    className: 'flex items-center gap-2 text-textSecondary',
                    onClick: () => handleEditVoucher(row.original)
                  }
                },
                {
                  text: 'Hapus',
                  icon: 'tabler-trash text-[22px]',
                  menuItemProps: {
                    className: 'flex items-center gap-2 text-textSecondary',
                    onClick: () => handleDeleteVoucher(row.original.id)
                  }
                }
              ]}
            />
          </div>
        ),
        enableSorting: false
      }
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [locale, handleEditVoucher, handleDeleteVoucher, handleToggleActive]
  )

  const table = useReactTable({
    data: vouchers as VoucherCatalogType[],
    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 Voucher'
              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={() => setAddVoucherOpen(!addVoucherOpen)}
              className='max-sm:is-full'
            >
              Tambah Voucher
            </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>
      <AddEditVoucherDrawer open={addVoucherOpen} handleClose={handleCloseVoucherDrawer} data={editVoucherData} />
    </>
  )
}

export default VoucherListTable
