'use client'

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

// 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 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 { TodoType, TodoStatusType, TodoPriorityType, TodoStatusColorType, TodoPriorityColorType } from '@/types/apps/todoTypes'

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

// Style Imports
import tableStyles from '@core/styles/table.module.css'

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

type TodoTypeWithAction = TodoType & {
  action?: string
}

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)} />
}

// Vars
const todoStatusObj: TodoStatusColorType = {
  pending: 'warning',
  'in-progress': 'info',
  completed: 'success'
}

const todoPriorityObj: TodoPriorityColorType = {
  high: 'error',
  medium: 'warning',
  low: 'success'
}

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

const TodoListTable = () => {
  // States
  const [addTodoOpen, setAddTodoOpen] = useState(false)
  const [editTodo, setEditTodo] = useState<TodoType | null>(null)
  const [rowSelection, setRowSelection] = useState({})
  const [data, setData] = useState<TodoType[]>([])
  const [filteredData, setFilteredData] = useState<TodoType[]>([])
  const [globalFilter, setGlobalFilter] = useState('')

  // Load data from localStorage on mount
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const storedTodos = localStorage.getItem('todos')
      if (storedTodos) {
        try {
          const parsedTodos = JSON.parse(storedTodos)
          setData(parsedTodos)
          setFilteredData(parsedTodos)
        } catch (error) {
          console.error('Error parsing todos from localStorage:', error)
        }
      }
    }
  }, [])

  // Save data to localStorage whenever data changes
  useEffect(() => {
    if (typeof window !== 'undefined' && data.length >= 0) {
      localStorage.setItem('todos', JSON.stringify(data))
    }
  }, [data])

  // Update filteredData when data changes
  useEffect(() => {
    setFilteredData(data)
  }, [data])

  const columns = useMemo<ColumnDef<TodoTypeWithAction, 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('title', {
        header: 'عنوان',
        cell: ({ row }) => (
          <Typography color='text.primary' className='font-medium'>
            {row.original.title}
          </Typography>
        )
      }),
      columnHelper.accessor('description', {
        header: 'توضیحات',
        cell: ({ row }) => (
          <Typography variant='body2' className='max-is-[300px] truncate'>
            {row.original.description || '-'}
          </Typography>
        )
      }),
      columnHelper.accessor('status', {
        header: 'وضعیت',
        cell: ({ row }) => (
          <div className='flex items-center gap-3'>
            <Chip
              variant='tonal'
              label={row.original.status === 'in-progress' ? 'در حال انجام' : row.original.status}
              size='small'
              color={todoStatusObj[row.original.status]}
              className='capitalize'
            />
          </div>
        )
      }),
      columnHelper.accessor('priority', {
        header: 'اولویت',
        cell: ({ row }) => (
          <div className='flex items-center gap-3'>
            <Chip
              variant='tonal'
              label={row.original.priority}
              size='small'
              color={todoPriorityObj[row.original.priority]}
              className='capitalize'
            />
          </div>
        )
      }),
      columnHelper.accessor('dueDate', {
        header: 'تاریخ سررسید',
        cell: ({ row }) => (
          <Typography color='text.primary'>
            {row.original.dueDate ? new Date(row.original.dueDate).toLocaleDateString() : '-'}
          </Typography>
        )
      }),
      columnHelper.accessor('createdDate', {
        header: 'ایجاد شده',
        cell: ({ row }) => (
          <Typography color='text.primary'>
            {new Date(row.original.createdDate).toLocaleDateString()}
          </Typography>
        )
      }),
      columnHelper.accessor('action', {
        header: 'عملیات',
        cell: ({ row }) => (
          <div className='flex items-center'>
            <IconButton
              onClick={() => {
                setEditTodo(row.original)
                setAddTodoOpen(true)
              }}
            >
              <i className='tabler-edit text-textSecondary' />
            </IconButton>
            <IconButton onClick={() => setData(data?.filter(todo => todo.id !== row.original.id))}>
              <i className='tabler-trash text-textSecondary' />
            </IconButton>
            <OptionMenu
              iconButtonProps={{ size: 'medium' }}
              iconClassName='text-textSecondary'
              options={[
                {
                  text: 'ویرایش',
                  icon: 'tabler-edit',
                  menuItemProps: {
                    onClick: () => {
                      setEditTodo(row.original)
                      setAddTodoOpen(true)
                    },
                    className: 'flex items-center gap-2 text-textSecondary'
                  }
                },
                {
                  text: 'حذف',
                  icon: 'tabler-trash',
                  menuItemProps: {
                    onClick: () => setData(data?.filter(todo => todo.id !== row.original.id)),
                    className: 'flex items-center gap-2 text-textSecondary'
                  }
                }
              ]}
            />
          </div>
        ),
        enableSorting: false
      })
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [data, filteredData]
  )

  const table = useReactTable({
    data: filteredData as TodoType[],
    columns,
    filterFns: {
      fuzzy: fuzzyFilter
    },
    state: {
      rowSelection,
      globalFilter
    },
    initialState: {
      pagination: {
        pageSize: 10
      }
    },
    enableRowSelection: true,
    globalFilterFn: fuzzyFilter,
    onRowSelectionChange: setRowSelection,
    getCoreRowModel: getCoreRowModel(),
    onGlobalFilterChange: setGlobalFilter,
    getFilteredRowModel: getFilteredRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getFacetedRowModel: getFacetedRowModel(),
    getFacetedUniqueValues: getFacetedUniqueValues(),
    getFacetedMinMaxValues: getFacetedMinMaxValues()
  })

  const handleBulkDelete = () => {
    const selectedRows = table.getFilteredSelectedRowModel().rows
    const selectedIds = selectedRows.map(row => row.original.id)
    setData(data?.filter(todo => !selectedIds.includes(todo.id)))
    setRowSelection({})
  }

  const handleAddTodo = () => {
    setEditTodo(null)
    setAddTodoOpen(true)
  }

  const handleCloseDrawer = () => {
    setAddTodoOpen(false)
    setEditTodo(null)
  }

  return (
    <>
      <Card>
        <CardHeader title='فیلترها' className='pbe-4' />
        <TableFilters setData={setFilteredData} tableData={data} />
        <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={globalFilter ?? ''}
              onChange={value => setGlobalFilter(String(value))}
              placeholder='Search Todo'
              className='max-sm:is-full'
            />
            {Object.keys(rowSelection).length > 0 && (
              <Button
                color='error'
                variant='tonal'
                startIcon={<i className='tabler-trash' />}
                onClick={handleBulkDelete}
                className='max-sm:is-full'
              >
                Delete Selected ({Object.keys(rowSelection).length})
              </Button>
            )}
            <Button
              variant='contained'
              startIcon={<i className='tabler-plus' />}
              onClick={handleAddTodo}
              className='max-sm:is-full'
            >
              Add New Todo
            </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>
            {table.getFilteredRowModel().rows.length === 0 ? (
              <tbody>
                <tr>
                  <td colSpan={table.getVisibleFlatColumns().length} className='text-center'>
                    No data available
                  </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 table={table} />}
          count={table.getFilteredRowModel().rows.length}
          rowsPerPage={table.getState().pagination.pageSize}
          page={table.getState().pagination.pageIndex}
          onPageChange={(_, page) => {
            table.setPageIndex(page)
          }}
        />
      </Card>
      <AddEditTodoDrawer
        open={addTodoOpen}
        handleClose={handleCloseDrawer}
        todoData={data}
        setData={setData}
        editTodo={editTodo}
        setEditTodo={setEditTodo}
      />
    </>
  )
}

export default TodoListTable


