'use client'

import { useEffect, useMemo, useState, useCallback } from 'react'
import type { ChangeEvent } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import Card from '@mui/material/Card'
import Button from '@mui/material/Button'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import CircularProgress from '@mui/material/CircularProgress'
import Box from '@mui/material/Box'
import Stack from '@mui/material/Stack'
import InputAdornment from '@mui/material/InputAdornment'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import { useRouter, useSearchParams } from 'next/navigation'
import { MenuItem } from '@mui/material'

import { rankItem } from '@tanstack/match-sorter-utils'
import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
  getFilteredRowModel,
  getSortedRowModel
} from '@tanstack/react-table'
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
import DeleteCategoryDialog from './DeleteCategoryDialog'
import EditCategoryDrawer from './EditCategoryDrawer'

import { getSearchParams } from '@/utils'
import AddCategoryDrawer from './addCategoryDrawer'
import CustomTextField from '@core/components/mui/TextField'
import tableStyles from '@core/styles/table.module.css'
import { useGetCategoriesList } from '@/@core/hooks/data/categories'
import CustomTablePaginationComponent from '@/components/CustomTablePaginationComponent'
import { TPageSizeOption } from '@/@core/types/api'
import { SetSrc } from '@/utils/set-src'

export type ApiCategoryType = {
  id: string
  parent_id: string | null
  name_ar: string
  name_en: string
  description_ar: string
  description_en: string
  image: string
  sort_order: number
  is_active: boolean
}

type CategoryWithActionsType = ApiCategoryType & { actions?: string }

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

const columnHelper = createColumnHelper<CategoryWithActionsType>()

const ProductCategoryTable = () => {
  const t = useTranslations('categories.table')
  const pageT = useTranslations('categories.page')
  const locale = useLocale()

  const router = useRouter()
  const searchParams = useSearchParams()
  const buildLocalePath = (path: string) => `/${locale}${path}`

  const [addCategoryOpen, setAddCategoryOpen] = useState(false)
  const [searchValue, setSearchValue] = useState(searchParams.get('search') || '')
  const [debouncedSearch, setDebouncedSearch] = useState(searchParams.get('search') || '')

  const page = Number(searchParams.get('page')) || 1
  const rowsPerPage = (Number(searchParams.get('per_page')) as TPageSizeOption) || 10
  const sortDirection = (searchParams.get('sort_as') as '' | 'asc' | 'desc') || ''
  const statusFilter = (searchParams.get('is_active') as '' | '1' | '0') || ''
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [deleteContext, setDeleteContext] = useState<{ id?: string; parentId?: string | null }>({})
  const [editOpen, setEditOpen] = useState(false)
  const [selectedId, setSelectedId] = useState<string | undefined>(undefined)

  const {
    data: response,
    isLoading,
    isError,
    refetch,
    isFetching
  } = useGetCategoriesList(
    {
      per_page: rowsPerPage,
      page,
      search: debouncedSearch || undefined,
      sort_by: sortDirection ? 'sort_order' : undefined,
      sort_as: sortDirection || undefined,
      is_active: statusFilter !== '' ? Number(statusFilter) : undefined
    },
    {
      staleTime: 1000 * 60 * 5, // 5 minutes fresh → no refetch on tab/category switch
      gcTime: 1000 * 60 * 30 // keep cached pages around for 30 minutes
    }
  )

  const data: CategoryWithActionsType[] = (response as any)?.data?.data ?? []
  const total = (response as any)?.data?.total ?? 0

  const numberFormatter = useMemo(() => new Intl.NumberFormat(locale === 'ar' ? 'ar-SA' : 'en-US'), [locale])

  const columns = useMemo<ColumnDef<CategoryWithActionsType, any>[]>(
    () => [
      /*   {
        id: 'select',
        header: ({ table }) => (
          <Checkbox
            checked={table.getIsAllRowsSelected()}
            indeterminate={table.getIsSomeRowsSelected()}
            onChange={table.getToggleAllRowsSelectedHandler()}
          />
        ),
        cell: ({ row }) => (
          <Checkbox
            checked={row.getIsSelected()}
            disabled={!row.getCanSelect()}
            onChange={row.getToggleSelectedHandler()}
          />
        )
      }, */
      columnHelper.accessor('name_ar', {
        header: t('categoryName'),
        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
          const handleNavigate = () => router.push(buildLocalePath(`/categories/${row.original.id}`))

          return (
            <div className='flex items-center gap-3'>
              <img
                src={SetSrc(row.original.image)}
                width={45}
                height={45}
                className='rounded bg-actionHover'
                alt={name}
              />
              <div className='flex flex-col items-start'>
                <button type='button' className='text-left' onClick={handleNavigate}>
                  <Typography className='font-medium hover:underline' color='primary'>
                    {name}
                  </Typography>
                </button>
                <Typography variant='body2' color='text.secondary'>
                  {desc}
                </Typography>
              </div>
            </div>
          )
        }
      }),
      columnHelper.accessor('sort_order', {
        header: t('sortOrder'),
        cell: ({ row }) => <Typography>{row.original.sort_order}</Typography>
      }),
      columnHelper.accessor('is_active', {
        header: t('status'),
        cell: ({ row }) => (
          <Chip
            size='small'
            color={row.original.is_active ? 'success' : 'default'}
            variant={row.original.is_active ? 'filled' : 'outlined'}
            label={row.original.is_active ? t('active') : t('inactive')}
          />
        )
      }),
      columnHelper.accessor('actions', {
        header: t('actions'),
        cell: ({ row }) => {
          return (
            <div className='flex flex-wrap items-center gap-2'>
              <Button
                variant='outlined'
                size='small'
                color='primary'
                onClick={() => router.push(buildLocalePath(`/categories/${row.original.id}/products`))}
              >
                {t('viewProducts')}
              </Button>

              <Button
                variant='outlined'
                size='small'
                color='secondary'
                onClick={() => router.push(buildLocalePath(`/categories/${row.original.id}`))}
              >
                {t('viewDetails')}
              </Button>

              <IconButton
                onClick={() => {
                  setSelectedId(row.original.id)
                  setEditOpen(true)
                }}
              >
                <i className='tabler-edit text-textSecondary' />
              </IconButton>

              <IconButton
                onClick={() => {
                  const targetId = row.original.id
                  const parentId = row.original.parent_id ?? null
                  setSelectedId(targetId)
                  setDeleteContext({ id: targetId, parentId })
                  setDeleteOpen(true)
                }}
              >
                <i className='tabler-trash text-error' />
              </IconButton>
            </div>
          )
        },
        enableSorting: false
      })
    ],
    [locale, router, t]
  )

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getSortedRowModel: getSortedRowModel(),
    filterFns: { fuzzy: fuzzyFilter },
    manualPagination: true,
    pageCount: Math.max(1, Math.ceil(total / rowsPerPage)),
    state: { pagination: { pageIndex: page - 1, pageSize: rowsPerPage } },
    onPaginationChange: updater => {
      const newPagination = typeof updater === 'function' ? updater(table.getState().pagination) : updater
      router.push(
        `?${getSearchParams({
          page: newPagination.pageIndex + 1,
          per_page: newPagination.pageSize
        })}`,
        { scroll: false }
      )
    }
  })

  const handleResetFilters = () => {
    setSearchValue('')
    setDebouncedSearch('')

    router.replace(`?${getSearchParams({ page: 1, per_page: 10 })}`, { scroll: false })
  }

  const handlePageSizeChange = useCallback(
    (event: ChangeEvent<HTMLInputElement>) => {
      const newPageSize = Number(event.target.value)
      router.push(`?${getSearchParams({ per_page: newPageSize, page: 1 })}`, { scroll: false })
    },
    [router]
  )

  useEffect(() => {
    const timeout = setTimeout(() => {
      const params = new URLSearchParams(window.location.search)
      const trimmed = searchValue.trim()

      trimmed ? params.set('search', trimmed) : params.delete('search')
      params.set('page', '1')

      setDebouncedSearch(trimmed)
      router.replace(`?${params.toString()}`, { scroll: false })
    }, 600)

    return () => clearTimeout(timeout)
  }, [searchValue, router])
  if (isError) return <Typography color='error'>{t('error')}</Typography>

  return (
    <Stack spacing={4}>
      <Card
        sx={{
          background: 'linear-gradient(135deg, #1F1B4B 0%, #623CEA 100%)',
          color: 'common.white'
        }}
      >
        <Box className='p-6 flex flex-col gap-4'>
          <Stack
            direction={{ xs: 'column', md: 'row' }}
            justifyContent='space-between'
            alignItems={{ xs: 'flex-start', md: 'center' }}
            spacing={2}
          >
            <Box>
              <Typography variant='h4' className='font-semibold'>
                {pageT('title')}
              </Typography>
              <Typography sx={{ color: 'rgba(255,255,255,0.75)' }}>{pageT('subtitle')}</Typography>
            </Box>
            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} alignItems={{ xs: 'stretch', sm: 'center' }}>
              {isFetching && !isLoading && <CircularProgress size={20} color='inherit' />}

              <Button
                variant='contained'
                color='secondary'
                onClick={() => setAddCategoryOpen(true)}
                startIcon={<i className='tabler-plus' />}
              >
                {t('addCategory')}
              </Button>
            </Stack>
          </Stack>
        </Box>
      </Card>

      <Card>
        <div className='flex flex-wrap justify-between gap-4 p-6 items-end'>
          <CustomTextField
            placeholder={t('searchPlaceholder')}
            value={searchValue}
            onChange={e => setSearchValue(e.target.value)}
            className='max-sm:w-full flex-1 min-w-[220px]'
            slotProps={{
              input: {
                startAdornment: (
                  <InputAdornment position='start'>
                    <i className='tabler-search text-textSecondary text-lg' />
                  </InputAdornment>
                )
              }
            }}
          />

          <div className='flex flex-wrap items-end gap-3'>
            <CustomTextField
              select
              size='small'
              label={t('sortOrder')}
              value={sortDirection}
              onChange={e =>
                (() => {
                  const params = new URLSearchParams(searchParams.toString())

                  params.set('page', '1')
                  params.set('per_page', String(rowsPerPage))

                  const trimmed = debouncedSearch.trim()
                  trimmed ? params.set('search', trimmed) : params.delete('search')

                  const nextSort = e.target.value as '' | 'asc' | 'desc'
                  nextSort ? params.set('sort_as', nextSort) : params.delete('sort_as')

                  statusFilter ? params.set('is_active', statusFilter) : params.delete('is_active')

                  router.push(`?${params.toString()}`, { scroll: false })
                })()
              }
              className='w-36'
            >
              <MenuItem value=''>--</MenuItem>
              <MenuItem value='asc'>{t('asc')}</MenuItem>
              <MenuItem value='desc'>{t('desc')}</MenuItem>
            </CustomTextField>

            <CustomTextField
              select
              size='small'
              label={t('status')}
              value={statusFilter}
              onChange={e =>
                (() => {
                  const params = new URLSearchParams(searchParams.toString())

                  params.set('page', '1')
                  params.set('per_page', String(rowsPerPage))

                  const trimmed = debouncedSearch.trim()
                  trimmed ? params.set('search', trimmed) : params.delete('search')

                  sortDirection ? params.set('sort_as', sortDirection) : params.delete('sort_as')

                  const nextStatus = e.target.value as '' | '1' | '0'
                  nextStatus ? params.set('is_active', nextStatus) : params.delete('is_active')

                  router.push(`?${params.toString()}`, { scroll: false })
                })()
              }
              className='w-36'
            >
              <MenuItem value=''>--</MenuItem>
              <MenuItem value='1'>{t('active')}</MenuItem>
              <MenuItem value='0'>{t('inactive')}</MenuItem>
            </CustomTextField>

            {isFetching && !isLoading && <CircularProgress size={20} />}

            <Button
              variant='text'
              color='secondary'
              onClick={handleResetFilters}
              startIcon={<i className='tabler-refresh' />}
            >
              {pageT('clear')}
            </Button>
          </div>
        </div>

        <div className='overflow-x-auto px-6 pb-6'>
          <table className={`${tableStyles.table} border-separate border-spacing-y-2`}>
            <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>
                ))
              ) : table.getRowModel().rows.length === 0 ? (
                <tr>
                  <td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
                    {t('noData')}
                  </td>
                </tr>
              ) : (
                table.getRowModel().rows.map(row => (
                  <tr
                    key={row.id}
                    className='rounded-xl overflow-hidden bg-backgroundPaper shadow-sm hover:shadow-md transition-all'
                  >
                    {row.getVisibleCells().map(cell => (
                      <td key={cell.id} className='py-4 px-4 border-b border-divider last:border-none align-middle'>
                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                      </td>
                    ))}
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        <Divider />

        <div className='flex flex-wrap justify-between gap-4 px-6 py-3'>
          <CustomTextField
            select
            value={table.getState().pagination.pageSize}
            onChange={handlePageSizeChange}
            className='w-24'
          >
            <MenuItem value='5'>5</MenuItem>
            <MenuItem value='10'>10</MenuItem>
            <MenuItem value='15'>15</MenuItem>
            <MenuItem value='25'>25</MenuItem>
          </CustomTextField>
          <CustomTablePaginationComponent table={table} totalItems={total} />
        </div>
      </Card>

      <AddCategoryDrawer
        open={addCategoryOpen}
        handleClose={() => setAddCategoryOpen(false)}
        onAdded={() => refetch()}
        parentId={null}
        disableParentSelection
      />
      <EditCategoryDrawer
        open={editOpen}
        handleClose={() => setEditOpen(false)}
        categoryId={selectedId}
        onUpdated={() => refetch()}
      />

      <DeleteCategoryDialog
        open={deleteOpen}
        handleClose={() => setDeleteOpen(false)}
        categoryId={deleteContext.id ?? selectedId}
        onDeleted={() => refetch()}
      />
    </Stack>
  )
}

export default ProductCategoryTable
