'use client'

import { useState, useMemo } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import Card from '@mui/material/Card'
import Button from '@mui/material/Button'
import Checkbox from '@mui/material/Checkbox'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import { rankItem } from '@tanstack/match-sorter-utils'
import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
  getFilteredRowModel,
  getSortedRowModel
} from '@tanstack/react-table'

import CustomTextField from '@core/components/mui/TextField'
import { getImageUrl } from '@/utils'
import tableStyles from '@core/styles/table.module.css'
import { IProduct } from '@/types/data/simpleProduct/product.interface'
import { useRouter } from 'next/navigation'
import { useGetFeaturedProducts } from '@/@core/hooks/data/products/useGetFeaturedProducts'

export type ProductWithActionsType = IProduct & { actions?: string }

const fuzzyFilter = (row: any, columnId: string, value: string, addMeta: any) => {
  const itemRank = rankItem(row.getValue(columnId), value)
  addMeta({ itemRank })
  return itemRank.passed
}

const columnHelper = createColumnHelper<ProductWithActionsType>()

const ProductFeaturedListTable = () => {
  const t = useTranslations('PRODUCTS')
  const locale = useLocale()
  const router = useRouter()

  const [globalFilter, setGlobalFilter] = useState('')
  const [selectedId, setSelectedId] = useState<any | undefined>(undefined)

  const { data: response, isLoading, isError } = useGetFeaturedProducts()

  const data: ProductWithActionsType[] = response?.data ?? []

  const columns = useMemo(
    () => [
      {
        id: 'select',
        header: ({ table }: any) => (
          <Checkbox
            checked={table.getIsAllRowsSelected()}
            indeterminate={table.getIsSomeRowsSelected()}
            onChange={table.getToggleAllRowsSelectedHandler()}
          />
        ),
        cell: ({ row }: any) => (
          <Checkbox
            checked={row.getIsSelected()}
            disabled={!row.getCanSelect()}
            onChange={row.getToggleSelectedHandler()}
          />
        )
      },
      columnHelper.accessor('image_url', {
        header: t('image'),
        cell: ({ row }) => (
          <img
            src={getImageUrl(row.original.image_url)}
            width={50}
            height={50}
            className='rounded bg-actionHover'
            alt={locale === 'ar' ? row.original.name_ar : row.original.name_en}
          />
        )
      }),
      columnHelper.accessor('name_ar', {
        header: t('productName'),
        cell: ({ row }) => {
          const name = locale === 'ar' ? row.original.name_ar : row.original.name_en
          const desc = locale === 'ar' ? row.original.description_ar : row.original.description_en
          return (
            <div className='flex flex-col'>
              <Typography className='font-medium'>{name}</Typography>
              <Typography variant='body2'>{desc}</Typography>
            </div>
          )
        }
      }),
      columnHelper.accessor('category', {
        header: t('category'),
        cell: ({ row }) => (
          <Typography>{locale === 'ar' ? row.original.category?.name_ar : row.original.category?.name_en}</Typography>
        )
      }),
      columnHelper.accessor('price', {
        header: t('price'),
        cell: ({ row }) => <Typography>{row.original.price}</Typography>
      }),
      columnHelper.accessor('is_featured', {
        header: t('featured'),
        cell: ({ row }) => (
          <Typography color={row.original.is_featured ? 'success.main' : 'text.secondary'}>
            {row.original.is_featured ? t('yes') : t('no')}
          </Typography>
        )
      }),
      columnHelper.accessor('is_available', {
        header: t('available'),
        cell: ({ row }) => (
          <Typography color={row.original.is_available ? 'success.main' : 'error.main'}>
            {row.original.is_available ? t('yes') : t('no')}
          </Typography>
        )
      }),
      columnHelper.accessor('actions', {
        header: t('actions'),
        cell: ({ row }) => (
          <div className='flex items-center gap-2'>
            <IconButton onClick={() => setSelectedId(row.original.id)}>
              <i className='tabler-edit text-textSecondary' />
            </IconButton>
            <IconButton onClick={() => setSelectedId(row.original.id)}>
              <i className='tabler-trash text-error' />
            </IconButton>
            <IconButton onClick={() => router.push(`/products/${row.original.id}`)}>
              <i className='tabler-eye text-primary' />
            </IconButton>
          </div>
        ),
        enableSorting: false
      })
    ],
    [locale, t]
  )

  const table = useReactTable({
    data,
    columns,
    filterFns: { fuzzy: fuzzyFilter },
    state: { globalFilter },
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getSortedRowModel: getSortedRowModel()
  })

  if (isLoading) return <Typography>{t('loading')}</Typography>
  if (isError) return <Typography color='error'>{t('error')}</Typography>

  return (
    <Card>
      {/*  <div className='flex flex-wrap justify-between gap-4 p-6'>
        <CustomTextField
          placeholder={t('searchPlaceholder')}
          value={globalFilter}
          onChange={e => setGlobalFilter(e.target.value)}
          className='max-sm:w-full'
        />
        <Button variant='contained' startIcon={<i className='tabler-plus' />}>
          {t('addProduct')}
        </Button>
      </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}>{flexRender(header.column.columnDef.header, header.getContext())}</th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody>
            {isLoading && !data.length ? (
              Array.from({ length: 10 }).map((_, i) => (
                <tr key={`skeleton-${i}`}>
                  {Array.from({ length: table.getVisibleFlatColumns().length }).map((_, j) => (
                    <td key={`skeleton-${i}-${j}`}>
                      <div className='h-4 w-full bg-gray-200 animate-pulse rounded' />
                    </td>
                  ))}
                </tr>
              ))
            ) : data.length ? (
              table.getRowModel().rows.map(row => (
                <tr key={row.id}>
                  {row.getVisibleCells().map(cell => (
                    <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
                  ))}
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={table.getVisibleFlatColumns().length} className='text-center py-4'>
                  {t('noData')}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </Card>
  )
}

export default ProductFeaturedListTable
