import {DataGrid, type DataGridProps, type GridColumnVisibilityModel} from '@mui/x-data-grid'
import {Stack, Button} from '@mui/material'
import {ExportButton} from '@refinedev/mui'
import {useExport} from '@refinedev/core'
import React, {useState, useEffect, useMemo} from 'react'
import Cookies from 'js-cookie'

import {localeText} from '../locales/ru/localeText'

interface CustomDataGridProps extends DataGridProps {
  hasCoordinates?: boolean
  resource?: string // Add this prop
}

const DEV_FIELDS = ['id', 'code', 'country_code', 'city_id', 'carrier_id'] as const

export const CustomDataGrid = ({hasCoordinates = false, columns = [], resource, ...props}: CustomDataGridProps) => {
  const isDev = import.meta.env.DEV
  const {triggerExport, isLoading: exportLoading} = useExport({
    resource: resource ?? '',
    // pageSize: 100, #*
    // maxItemCount: 100, #*
  })

  const initialShowCoordinates = Cookies.get('showCoordinates') === 'true'
  const initialShowDevData = Cookies.get('showDevData') === 'true'

  const [showCoordinates, setShowCoordinates] = useState(initialShowCoordinates)
  const [showDevData, setShowDevData] = useState(initialShowDevData)

  const availableDevFields = useMemo(() => DEV_FIELDS.filter((field) => columns.some((column) => column.field === field)), [columns])

  const initialVisibilityModel = useMemo(() => {
    const model: GridColumnVisibilityModel = {}

    availableDevFields.forEach((field) => {
      model[field] = initialShowDevData
    })

    if (hasCoordinates) {
      model.latitude = initialShowCoordinates
      model.longitude = initialShowCoordinates
    }

    return model
  }, [availableDevFields, hasCoordinates, initialShowCoordinates, initialShowDevData])

  const [columnVisibilityModel, setColumnVisibilityModel] = useState<GridColumnVisibilityModel>(initialVisibilityModel)

  useEffect(() => {
    setColumnVisibilityModel((prevModel) => {
      const newModel = {...prevModel}

      availableDevFields.forEach((field) => {
        newModel[field] = showDevData
      })

      if (hasCoordinates) {
        newModel.latitude = showCoordinates
        newModel.longitude = showCoordinates
      }

      return newModel
    })

    if (hasCoordinates) {
      Cookies.set('showCoordinates', String(showCoordinates))
    }
    Cookies.set('showDevData', String(showDevData))
  }, [showCoordinates, showDevData, hasCoordinates, availableDevFields])

  const toggleCoordinates = () => {
    setShowCoordinates((prev) => !prev)
  }

  const toggleDevData = () => {
    setShowDevData((prev) => !prev)
  }

  return (
    <Stack spacing={2}>
      <DataGrid
        {...props}
        columns={columns}
        localeText={localeText}
        columnVisibilityModel={columnVisibilityModel}
        onColumnVisibilityModelChange={setColumnVisibilityModel}
        // Добавляем базовые функции сортировки и фильтрации
        sortingMode="client"
        filterMode="client"
        initialState={{
          // pagination: {
          //   paginationModel: {pageSize: 25, page: 0},
          // },
          sorting: {
            sortModel: [{field: 'id', sort: 'asc'}],
          },
        }}
        pageSizeOptions={[10, 25, 50, 100]}
      />

      <Stack direction="row" spacing={2} justifyContent="space-between" mb={2}>
        <Stack direction="row" spacing={2} sx={{mb: 2}}>
          {hasCoordinates && (
            <Button variant="contained" onClick={toggleCoordinates}>
              {showCoordinates ? 'Скрыть координаты' : 'Показать координаты'}
            </Button>
          )}

          {isDev && availableDevFields.length > 0 && (
            <Button variant="contained" onClick={toggleDevData}>
              {showDevData ? 'Скрыть служебные данные' : 'Показать служебные данные'}
            </Button>
          )}
        </Stack>

        <ExportButton onClick={triggerExport} loading={exportLoading} />
      </Stack>
    </Stack>
  )
}
