'use client'

// React Imports
import { useCallback, useEffect, useMemo, useState } from 'react'

// Next Imports
import Link from 'next/link'
import { useParams } from 'next/navigation'

// MUI Imports
import Button from '@mui/material/Button'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import Checkbox from '@mui/material/Checkbox'
import Chip from '@mui/material/Chip'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import { styled } from '@mui/material/styles'
import type { TextFieldProps } from '@mui/material/TextField'
import Typography from '@mui/material/Typography'

// Third-party Imports
import type { RankingInfo } from '@tanstack/match-sorter-utils'
import { rankItem } from '@tanstack/match-sorter-utils'
import type { ColumnDef, FilterFn } from '@tanstack/react-table'
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import classnames from 'classnames'

// Type Imports
import type { Locale } from '@configs/i18n'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import OptionMenu from '@core/components/option-menu'

// Style Imports
import tableStyles from '@core/styles/table.module.css'
import { Box, CircularProgress, TablePagination } from '@mui/material'
import { useDispatch } from 'react-redux'
import TablePaginationComponent from '@/components/TablePaginationComponent'
import Loading from '@/components/layout/shared/Loading'
import { getLocalizedUrl } from '@/utils/i18n'
import { SalesDeliveryType } from '@/types/apps/salesTypes'
import { salesDeliveryData } from '@/data/dummy/sales'

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

type SalesDeliveryTypeWithAction = SalesDeliveryType & {
  actions?: 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)} />
}

// Status color mapping for Sales Delivery
const getStatusColor = (status: string) => {
  switch (status) {
    case 'Open':
      return 'warning'
    case 'Selesai':
      return 'success'
    default:
      return 'default'
  }
}

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

const SalesDeliveryListTable = () => {
  const dispatch = useDispatch()

  // States
  const [addDeliveryOpen, setAddDeliveryOpen] = useState(false)
  const [rowSelection, setRowSelection] = useState({})
  const [currentPage, setCurrentPage] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  const [openConfirm, setOpenConfirm] = useState(false)
  const [deliveryId, setDeliveryId] = useState('')
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('Semua')
  const [filteredData, setFilteredData] = useState<SalesDeliveryType[]>(salesDeliveryData)

  // Hooks
  const { lang: locale } = useParams()

  // Filter data based on search and status
  useEffect(() => {
    let filtered = salesDeliveryData

    // Filter by search
    if (search) {
      filtered = filtered.filter(
        delivery =>
          delivery.number.toLowerCase().includes(search.toLowerCase()) ||
          delivery.vendorName.toLowerCase().includes(search.toLowerCase()) ||
          delivery.vendorCompany.toLowerCase().includes(search.toLowerCase()) ||
          delivery.status.toLowerCase().includes(search.toLowerCase())
      )
    }

    // Filter by status
    if (statusFilter !== 'Semua') {
      filtered = filtered.filter(delivery => delivery.status === statusFilter)
    }

    setFilteredData(filtered)
    setCurrentPage(0)
  }, [search, statusFilter])

  const totalCount = filteredData.length
  const paginatedData = useMemo(() => {
    const startIndex = currentPage * pageSize
    return filteredData.slice(startIndex, startIndex + pageSize)
  }, [filteredData, currentPage, pageSize])

  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(0)
  }, [])

  const handleDelete = () => {
    setOpenConfirm(false)
  }

  const handleDeliveryClick = (deliveryId: string) => {
    console.log('Navigasi ke detail Delivery:', deliveryId)
  }

  const handleStatusFilter = (status: string) => {
    setStatusFilter(status)
  }

  const columns = useMemo<ColumnDef<SalesDeliveryTypeWithAction, 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('number', {
        header: 'Nomor Delivery',
        cell: ({ row }) => (
          <Button
            variant='text'
            color='primary'
            className='p-0 min-w-0 font-medium normal-case justify-start'
            onClick={() => handleDeliveryClick(row.original.id.toString())}
            sx={{
              textTransform: 'none',
              fontWeight: 500,
              '&:hover': {
                textDecoration: 'underline',
                backgroundColor: 'transparent'
              }
            }}
          >
            {row.original.number}
          </Button>
        )
      }),
      columnHelper.accessor('vendorName', {
        header: 'Pelanggan',
        cell: ({ row }) => (
          <div className='flex flex-col'>
            <Typography color='text.primary' className='font-medium'>
              {row.original.vendorName}
            </Typography>
            <Typography variant='body2' color='text.secondary'>
              {row.original.vendorCompany}
            </Typography>
          </div>
        )
      }),
      columnHelper.accessor('reference', {
        header: 'Referensi',
        cell: ({ row }) => <Typography color='text.secondary'>{row.original.reference || '-'}</Typography>
      }),
      columnHelper.accessor('date', {
        header: 'Tanggal',
        cell: ({ row }) => <Typography>{row.original.date}</Typography>
      }),
      columnHelper.accessor('status', {
        header: 'Status',
        cell: ({ row }) => (
          <div className='flex items-center gap-3'>
            <Chip
              variant='tonal'
              label={row.original.status}
              size='small'
              color={getStatusColor(row.original.status) as any}
              className='capitalize'
            />
          </div>
        )
      })
    ],
    []
  )

  const table = useReactTable({
    data: paginatedData as SalesDeliveryType[],
    columns,
    filterFns: {
      fuzzy: fuzzyFilter
    },
    state: {
      rowSelection,
      pagination: {
        pageIndex: currentPage,
        pageSize
      }
    },
    enableRowSelection: true,
    onRowSelectionChange: setRowSelection,
    getCoreRowModel: getCoreRowModel(),
    manualPagination: true,
    pageCount: Math.ceil(totalCount / pageSize)
  })

  return (
    <>
      <Card>
        {/* Filter Status Tabs */}
        <div className='p-6 border-bs'>
          <div className='flex flex-wrap gap-2'>
            {['Semua', 'Open', 'Selesai'].map(status => (
              <Button
                key={status}
                variant={statusFilter === status ? 'contained' : 'outlined'}
                color={statusFilter === status ? 'primary' : 'inherit'}
                onClick={() => handleStatusFilter(status)}
                size='small'
                className='rounded-lg'
                sx={{
                  textTransform: 'none',
                  fontWeight: statusFilter === status ? 600 : 400,
                  borderRadius: '8px',
                  ...(statusFilter !== status && {
                    borderColor: '#e0e0e0',
                    color: '#666'
                  })
                }}
              >
                {status}
              </Button>
            ))}
          </div>
        </div>

        <div className='flex justify-between flex-col items-start md:flex-row md:items-center p-6 border-bs gap-4'>
          <DebouncedInput
            value={search}
            onChange={value => setSearch(value as string)}
            placeholder='Cari Sales Delivery'
            className='max-sm:is-full'
          />
          <div className='flex flex-col sm:flex-row max-sm:is-full items-start sm:items-center gap-4'>
            <CustomTextField
              select
              value={pageSize}
              onChange={handlePageSizeChange}
              className='max-sm:is-full sm:is-[70px]'
            >
              <MenuItem value={10}>10</MenuItem>
              <MenuItem value={25}>25</MenuItem>
              <MenuItem value={50}>50</MenuItem>
            </CustomTextField>
            <Button
              color='secondary'
              variant='tonal'
              startIcon={<i className='tabler-upload' />}
              className='max-sm:is-full'
            >
              Ekspor
            </Button>
          </div>
        </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}>
                      {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>
            {filteredData.length === 0 ? (
              <tbody>
                <tr>
                  <td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
                    Tidak ada data tersedia
                  </td>
                </tr>
              </tbody>
            ) : (
              <tbody>
                {table.getRowModel().rows.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]}
        />
      </Card>
    </>
  )
}

export default SalesDeliveryListTable
