'use client'

import { useState, useEffect, useMemo, useCallback } from 'react'
import type { ChangeEvent } from 'react'
import { useTranslations, useLocale } from 'next-intl'
import { useRouter, useSearchParams } from 'next/navigation'
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 Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import DialogContentText from '@mui/material/DialogContentText'
import MenuItem from '@mui/material/MenuItem'
import Box from '@mui/material/Box'
import Stack from '@mui/material/Stack'
import Grid from '@mui/material/Grid2'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import Tooltip from '@mui/material/Tooltip'
import CircularProgress from '@mui/material/CircularProgress'
import Skeleton from '@mui/material/Skeleton'
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 { toast } from 'react-toastify'

import CustomTextField from '@core/components/mui/TextField'
import { getImageUrl, getSearchParams } from '@/utils'
import tableStyles from '@core/styles/table.module.css'
import CustomTablePaginationComponent from '@/components/CustomTablePaginationComponent'
import { useDeleteProduct, useGetProductsList } from '@/@core/hooks/data/products'
import { IProduct } from '@/types/data/simpleProduct/product.interface'
import { useGetCategoriesDropdown } from '@/@core/hooks/data/categories'
import { ICategory } from '@/types/data/categories/category.interface'
import { TPageSizeOption } from '@/@core/types/api'
import Image from 'next/image'

export type ProductWithActionsType = IProduct & { 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<ProductWithActionsType>()

const ProductListTable = () => {
  const t = useTranslations('PRODUCTS')
  const locale = useLocale()
  const router = useRouter()
  const searchParams = useSearchParams()
  const buildLocalePath = (path: string) => `/${locale}${path}`

  const [searchValue, setSearchValue] = useState(searchParams.get('search') || '')
  const [debouncedSearch, setDebouncedSearch] = useState(searchParams.get('search') || '')
  const [deleteDialog, setDeleteDialog] = useState<{ id: string; name: string } | null>(null)

  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 availabilityFilter = (searchParams.get('is_available') as '' | 'true' | 'false') || ''
  const categoryFilter = searchParams.get('category_id') || ''

  const deleteProduct = useDeleteProduct()

  const {
    data: response,
    isLoading,
    refetch,
    isError
  } = useGetProductsList(
    {
      page,
      per_page: rowsPerPage,
      search: debouncedSearch || undefined,
      sort_by: sortDirection ? 'sort_order' : undefined,
      sort_as: sortDirection || undefined,
      is_available: availabilityFilter !== '' ? availabilityFilter === 'true' : undefined,
      category_id: categoryFilter || undefined
    },
    {
      staleTime: 1000 * 60 * 5,
      gcTime: 1000 * 60 * 30
    }
  )

  const { data: categoriesDropdown } = useGetCategoriesDropdown({ sort_by: 'sort_order', sort_as: 'asc' })
  const categoryOptions = useMemo(() => {
    if (!Array.isArray(categoriesDropdown)) {
      return []
    }

    const flatten = (categories: ICategory[], depth = 0): { id: string; label: string }[] => {
      return categories.flatMap(category => {
        const labelPrefix = depth ? `${'-- '.repeat(depth)}` : ''
        const name = locale === 'ar' ? category.name_ar : category.name_en
        const current = { id: String(category.id), label: `${labelPrefix}${name}` }
        const children = Array.isArray(category.children) ? flatten(category.children, depth + 1) : []

        return [current, ...children]
      })
    }

    return flatten(categoriesDropdown)
  }, [categoriesDropdown, locale])

  const payload = response?.data
  const data: ProductWithActionsType[] = payload?.data ?? []
  const total = payload?.total ?? 0
  const availableTotal = (payload as any)?.available_total ?? data.filter(item => item.is_available).length
  const featuredTotal = (payload as any)?.featured_total ?? data.filter(item => item.is_featured).length

  const derivedAverage = useMemo(() => {
    if (data.length === 0) {
      return 0
    }

    const sum = data.reduce((acc, item) => acc + Number(item.current_price || item.price || 0), 0)
    return sum / data.length
  }, [data])

  const averagePrice = Number((payload as any)?.average_price ?? derivedAverage ?? 0)

  const numberFormatter = useMemo(() => new Intl.NumberFormat(locale === 'ar' ? 'ar-SA' : 'en-US'), [locale])
  const currencyCode = process.env.NEXT_PUBLIC_CURRENCY_CODE || 'SAR'
  const currencyFormatter = useMemo(
    () =>
      new Intl.NumberFormat(locale === 'ar' ? 'ar-SA' : 'en-US', {
        style: 'currency',
        currency: currencyCode,
        maximumFractionDigits: 2
      }),
    [currencyCode, locale]
  )

  const formatNumber = (value?: number) => numberFormatter.format(value ?? 0)
  const formatCurrency = (value?: number | string | null) => {
    const numeric = Number(value ?? 0)
    if (Number.isNaN(numeric)) {
      return '—'
    }

    return currencyFormatter.format(numeric)
  }

  const heroStats = [
    {
      key: 'total',
      label: t('stats.totalProducts'),
      helper: t('stats.totalProductsHint'),
      value: formatNumber(payload?.total ?? data.length),
      icon: 'tabler-box'
    },
    {
      key: 'available',
      label: t('stats.availableProducts'),
      helper: t('stats.availableProductsHint'),
      value: formatNumber(availableTotal),
      icon: 'tabler-check'
    },
    {
      key: 'featured',
      label: t('stats.featuredProducts'),
      helper: t('stats.featuredProductsHint'),
      value: formatNumber(featuredTotal),
      icon: 'tabler-star'
    },
    {
      key: 'avg',
      label: t('stats.averagePrice'),
      helper: t('stats.averagePriceHint'),
      value: formatCurrency(averagePrice),
      icon: 'tabler-currency-dollar'
    }
  ]

  const columns = useMemo<ColumnDef<ProductWithActionsType, any>[]>(
    () => [
      columnHelper.accessor('name_ar', {
        header: t('productName'),
        cell: ({ row }) => {
          const product = row.original
          const name = locale === 'ar' ? product.name_ar : product.name_en
          const desc = locale === 'ar' ? product.description_ar : product.description_en

          return (
            <Stack direction='row' spacing={3} alignItems='center'>
              <img
                src={getImageUrl(product?.image)}
                width={56}
                height={56}
                className='rounded-lg object-cover bg-actionHover'
                alt={name}
              />
              <Box className='space-y-1'>
                <Typography className='font-semibold' color='text.primary'>
                  {name}
                </Typography>
                <Typography variant='body2' color='text.secondary' noWrap>
                  {desc || t('noDescription')}
                </Typography>
                <Stack direction='row' spacing={1} flexWrap='wrap'>
                  {product.sku && (
                    <Chip size='small' color='default' variant='outlined' label={`${t('sku')}: ${product.sku}`} />
                  )}
                  {typeof product.sort_order === 'number' && (
                    <Chip size='small' variant='outlined' label={`${t('sortOrder')}: ${product.sort_order}`} />
                  )}
                </Stack>
              </Box>
            </Stack>
          )
        }
      }),
      columnHelper.accessor('category', {
        header: t('category'),
        cell: ({ row }) => (
          <Stack spacing={0.5}>
            <Typography>{locale === 'ar' ? row.original.category?.name_ar : row.original.category?.name_en}</Typography>
            {row.original.category?.description_en && (
              <Typography variant='caption' color='text.secondary' noWrap>
                {locale === 'ar' ? row.original.category?.description_ar : row.original.category?.description_en}
              </Typography>
            )}
          </Stack>
        )
      }),
      columnHelper.accessor('price', {
        header: t('price'),
        cell: ({ row }) => (
          <Stack spacing={0.5}>
            <Typography fontWeight={600}>{formatCurrency(row.original.current_price ?? row.original.price)}</Typography>
            {row.original.has_discount && row.original.price && (
              <Typography variant='caption' color='text.secondary' sx={{ textDecoration: 'line-through' }}>
                {formatCurrency(row.original.price)}
              </Typography>
            )}
          </Stack>
        )
      }),
      columnHelper.accessor('is_featured', {
        header: t('featured'),
        cell: ({ row }) => (
          <Chip
            size='small'
            color={row.original.is_featured ? 'secondary' : 'default'}
            variant={row.original.is_featured ? 'filled' : 'outlined'}
            label={row.original.is_featured ? t('yes') : t('no')}
          />
        )
      }),
      columnHelper.accessor('is_available', {
        header: t('available'),
        cell: ({ row }) => (
          <Chip
            size='small'
            color={row.original.is_available ? 'success' : 'error'}
            variant='outlined'
            label={row.original.is_available ? t('availability.available') : t('availability.unavailable')}
          />
        )
      }),
      columnHelper.accessor('actions', {
        header: t('actions'),
        cell: ({ row }) => (
          <Stack direction='row' spacing={1}>
            <Tooltip title={t('actionsEdit')}>
              <IconButton
                color='primary'
                onClick={() => router.push(buildLocalePath(`/products/edit/${row.original.id}`))}
              >
                <i className='tabler-edit' />
              </IconButton>
            </Tooltip>
            <Tooltip title={t('actionsView')}>
              <IconButton onClick={() => router.push(buildLocalePath(`/products/${row.original.id}`))}>
                <i className='tabler-eye' />
              </IconButton>
            </Tooltip>
            <Tooltip title={t('actionsDelete')}>
              <IconButton
                color='error'
                onClick={() => setDeleteDialog({ id: String(row.original.id), name: row.original.name_en })}
              >
                <i className='tabler-trash' />
              </IconButton>
            </Tooltip>
          </Stack>
        ),
        enableSorting: false
      })
    ],
    [buildLocalePath, locale, router, t]
  )

  const table = useReactTable({
    data,
    columns,
    filterFns: { fuzzy: fuzzyFilter },
    getCoreRowModel: getCoreRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getSortedRowModel: getSortedRowModel(),
    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 }
      )
    }
  })

  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')
      categoryFilter ? params.set('category_id', categoryFilter) : params.delete('category_id')
      sortDirection ? params.set('sort_as', sortDirection) : params.delete('sort_as')
      availabilityFilter ? params.set('is_available', availabilityFilter) : params.delete('is_available')

      setDebouncedSearch(trimmed)
      router.replace(`?${params.toString()}`, { scroll: false })
    }, 600)

    return () => clearTimeout(timeout)
  }, [availabilityFilter, categoryFilter, sortDirection, searchValue, router])

  const handlePageSizeChange = useCallback(
    (event: ChangeEvent<HTMLInputElement>) => {
      const newPageSize = Number(event.target.value)
      router.push(`?${getSearchParams({ per_page: newPageSize, page: 1 })}`, { scroll: false })
    },
    [router]
  )

  const resetFilters = () => {
    setSearchValue('')
    const params = new URLSearchParams()
    params.set('page', '1')
    params.set('per_page', String(rowsPerPage))
    router.replace(`?${params.toString()}`, { scroll: false })
  }

  const handleConfirmDelete = async () => {
    if (!deleteDialog) return

    try {
      const response = await deleteProduct.mutateAsync(deleteDialog.id)
      toast.success((response as any)?.message || t('deleteDialog.success'))
      setDeleteDialog(null)
      refetch()
    } catch (error: any) {
      const apiMessage = error?.response?.data?.message
      toast.error(apiMessage || t('deleteDialog.error'))
    }
  }

  if (isError) return <Typography color='error'>{t('error')}</Typography>

  return (
    <Stack spacing={4}>
      <Card
        sx={{
          background: 'linear-gradient(135deg, #162447 0%, #3a7bd5 100%)',
          color: 'common.white'
        }}
      >
        <Box className='p-6 space-y-4'>
          <Stack direction={{ xs: 'column', md: 'row' }} justifyContent='space-between' spacing={3}>
            <Box>
              <Typography variant='h4' fontWeight={600} gutterBottom>
                {t('page.title')}
              </Typography>
              <Typography sx={{ color: 'rgba(255,255,255,0.75)' }}>{t('page.subtitle')}</Typography>
            </Box>
            <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} alignItems={{ xs: 'stretch', sm: 'center' }}>
              <Button
                variant='contained'
                color='secondary'
                onClick={() => router.push(buildLocalePath('/products/add'))}
                startIcon={<i className='tabler-plus' />}
              >
                {t('page.actions.add')}
              </Button>
            </Stack>
          </Stack>

          <Grid container spacing={3}>
            {heroStats?.map(stat => (
              <Grid key={stat.key} size={{ xs: 12, sm: 6, lg: 3 }}>
                <Box
                  sx={{
                    p: 3,
                    borderRadius: 3,
                    backgroundColor: 'rgba(0,0,0,0.2)',
                    border: '1px solid rgba(255,255,255,0.2)',
                    height: '100%'
                  }}
                >
                  <Stack spacing={1.5}>
                    <Box
                      sx={{
                        width: 42,
                        height: 42,
                        borderRadius: '50%',
                        backgroundColor: 'rgba(0,0,0,0.25)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <i className={`${stat.icon} text-white`} />
                    </Box>
                    {isLoading ? (
                      <Skeleton variant='text' width='60%' sx={{ bgcolor: 'rgba(255,255,255,0.3)' }} />
                    ) : (
                      <Typography variant='h4'>{stat.value}</Typography>
                    )}
                    <Typography variant='body2' sx={{ color: 'rgba(255,255,255,0.7)' }}>
                      {stat.label}
                    </Typography>
                    <Typography variant='caption' sx={{ color: 'rgba(255,255,255,0.6)' }}>
                      {stat.helper}
                    </Typography>
                  </Stack>
                </Box>
              </Grid>
            ))}
          </Grid>
        </Box>
      </Card>

      <Card>
        <Stack spacing={3} className='p-6'>
          <div className='flex flex-wrap justify-between gap-4 items-end'>
            <CustomTextField
              placeholder={t('searchPlaceholder') || t('filters.searchPlaceholder')}
              value={searchValue}
              onChange={e => setSearchValue(e.target.value)}
              className='max-sm:w-full flex-1 min-w-[200px]'
            />

            <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')

                    availabilityFilter ? params.set('is_available', availabilityFilter) : params.delete('is_available')
                    categoryFilter ? params.set('category_id', categoryFilter) : params.delete('category_id')

                    router.push(`?${params.toString()}`, { scroll: false })
                  })()
                }
                className='w-32'
              >
                <MenuItem value=''>--</MenuItem>
                <MenuItem value='asc'>{t('sort.asc')}</MenuItem>
                <MenuItem value='desc'>{t('sort.desc')}</MenuItem>
              </CustomTextField>

              <CustomTextField
                select
                size='small'
                label={t('available')}
                value={availabilityFilter}
                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 '' | 'true' | 'false'
                    nextStatus ? params.set('is_available', nextStatus) : params.delete('is_available')
                    categoryFilter ? params.set('category_id', categoryFilter) : params.delete('category_id')

                    router.push(`?${params.toString()}`, { scroll: false })
                  })()
                }
                className='w-40'
              >
                <MenuItem value=''>{locale === 'ar' ? 'الكل' : t('availability.all')}</MenuItem>
                <MenuItem value='true'>{locale === 'ar' ? 'المتوفر فقط' : t('availability.available')}</MenuItem>
                <MenuItem value='false'>{locale === 'ar' ? 'غير المتوفر فقط' : t('availability.unavailable')}</MenuItem>
              </CustomTextField>

              <CustomTextField
                select
                size='small'
                label={t('category')}
                value={categoryFilter}
                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')
                    availabilityFilter ? params.set('is_available', availabilityFilter) : params.delete('is_available')

                    const nextCategory = e.target.value as string
                    nextCategory ? params.set('category_id', nextCategory) : params.delete('category_id')

                    router.push(`?${params.toString()}`, { scroll: false })
                  })()
                }
                className='w-48'
              >
                <MenuItem value=''>{t('category')}</MenuItem>
                {categoryOptions.map(option => (
                  <MenuItem key={option.id} value={option.id}>
                    {option.label}
                  </MenuItem>
                ))}
              </CustomTextField>

              <Button
                variant='text'
                color='inherit'
                onClick={resetFilters}
                startIcon={<i className='tabler-refresh' />}
              >
                {t('filters.clear')}
              </Button>
            </div>
          </div>

          <Divider />

          <div className='overflow-x-auto -mx-4 px-4'>
            <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: 6 }).map((_, i) => (
                    <tr key={`skeleton-${i}`}>
                      {Array.from({ length: table.getVisibleFlatColumns().length }).map((_, j) => (
                        <td key={`skeleton-${i}-${j}`}>
                          <Skeleton variant='rounded' height={32} />
                        </td>
                      ))}
                    </tr>
                  ))
                ) : table.getRowModel().rows.length === 0 ? (
                  <tr>
                    <td colSpan={table.getVisibleFlatColumns().length} className='text-center py-6'>
                      {t('noData')}
                    </td>
                  </tr>
                ) : (
                  table.getRowModel().rows.map(row => (
                    <tr key={row.id} className='bg-backgroundPaper shadow-sm hover:shadow-md transition-all rounded-xl'>
                      {row.getVisibleCells().map(cell => (
                        <td key={cell.id} className='py-4 px-4 align-middle'>
                          {flexRender(cell.column.columnDef.cell, cell.getContext())}
                        </td>
                      ))}
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          <Divider />

          <Stack direction={{ xs: 'column', md: 'row' }} justifyContent='space-between' alignItems='center' gap={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} />
          </Stack>
        </Stack>
      </Card>

      <Dialog open={Boolean(deleteDialog)} onClose={() => setDeleteDialog(null)}>
        <DialogTitle>{t('deleteDialog.title')}</DialogTitle>
        <DialogContent>
          <DialogContentText>{t('deleteDialog.description', { name: deleteDialog?.name ?? '' })}</DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialog(null)} color='secondary'>
            {t('deleteDialog.cancel')}
          </Button>
          <Button onClick={handleConfirmDelete} color='error' disabled={deleteProduct.isPending}>
            {deleteProduct.isPending ? <CircularProgress size={18} color='inherit' /> : t('deleteDialog.confirm')}
          </Button>
        </DialogActions>
      </Dialog>
    </Stack>
  )
}

export default ProductListTable
