import { useLocation, useParams, useSearchParams } from 'react-router-dom'
import { useEffect, useState } from 'react'
import Container from '@/components/shared/Container'
import Grid from './Grid'
import { FaChartArea, FaList, FaTable, FaTh, FaUser } from 'react-icons/fa'
import { useStoreActions, useStoreState } from '@/store/store'
import classNames from 'classnames'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { GridDto } from '@/proxy/form/models'
import Card from './Card'
import { Badge, Button } from '@/components/ui'
import Pivot from './Pivot'
import { getList } from '@/services/form.service'
import { useCurrentMenuIcon } from '@/utils/hooks/useCurrentMenuIcon'
import { ListViewLayoutType } from '../admin/listForm/edit/types'
import Chart from './Chart'

const List = () => {
  const params = useParams()
  const { translate } = useLocalization()
  const [searchParams] = useSearchParams()
  const listFormCode = params?.listFormCode ?? ''
  const mode = useStoreState((state) => state.theme.mode)
  const [viewMode, setViewMode] = useState<ListViewLayoutType>()

  const [gridDto, setGridDto] = useState<GridDto>()
  const MenuIcon = useCurrentMenuIcon('w-5 h-5')

  const { states } = useStoreState((state) => state.admin.lists)
  const { setStates } = useStoreActions((a) => a.admin.lists)

  // 🔹 Tekrar çağırılabilir metod
  const refreshGridDto = async () => {
    if (!listFormCode) return
    try {
      const response = await getList({ listFormCode })
      setGridDto(response.data)
    } catch (error) {
      console.error('GridDto refresh error:', error)
    }
  }

  useEffect(() => {
    refreshGridDto().then(() => {
      //base içerisine kaydedilen state içerisinden bakılacak
      const listFormStates = states.find((a) => a.listFormCode === listFormCode)
      if (listFormStates) {
        setViewMode(listFormStates.layout || 'grid')
      } else {
        setViewMode(gridDto?.gridOptions?.layoutDto.defaultLayout || 'grid')
      }
    })
  }, [listFormCode])

  if (!listFormCode) {
    return null
  }

  if (!gridDto) {
    return null
  }

  return (
    <Container>
      <div
        className={classNames('flex items-center border-solid gap-1 pb-1', {
          'border-gray-100': mode === 'light',
          'border-neutral-700': mode === 'dark',
        })}
      >
        <div className="flex items-center gap-2">
          {MenuIcon}
          <h4 className="text-slate-700 text-sm font-medium leading-none">
            {translate('::' + gridDto?.gridOptions?.title) || ''}
          </h4>
          ●
          <Badge content={viewMode} />
        </div>

        {gridDto?.gridOptions?.description === gridDto?.gridOptions?.title ? (
          <p className="mr-auto"></p>
        ) : (
          <p className="text-slate-500 text-xs mr-auto ml-2 leading-none">
            {translate('::' + gridDto?.gridOptions?.description)}
          </p>
        )}

        <div className="flex gap-1">
          {gridDto?.gridOptions?.layoutDto.grid && (
            <Button
              size="xs"
              variant={viewMode === 'grid' ? 'solid' : 'default'}
              onClick={() => {
                setViewMode('grid')
                setStates({ listFormCode, layout: 'grid' })
              }}
              title="Grid Görünümü"
            >
              <FaList className="w-4 h-4" />
            </Button>
          )}

          {gridDto?.gridOptions?.layoutDto.card && (
            <Button
              size="xs"
              variant={viewMode === 'card' ? 'solid' : 'default'}
              onClick={() => {
                setViewMode('card')
                setStates({ listFormCode, layout: 'card' })
              }}
              title="Kart Görünümü"
            >
              <FaTh className="w-4 h-4" />
            </Button>
          )}

          {gridDto?.gridOptions?.layoutDto.pivot && (
            <Button
              size="xs"
              variant={viewMode === 'pivot' ? 'solid' : 'default'}
              onClick={() => {
                setViewMode('pivot')
                setStates({ listFormCode, layout: 'pivot' })
              }}
              title="Pivot Görünümü"
            >
              <FaTable className="w-4 h-4" />
            </Button>
          )}

          {gridDto?.gridOptions?.layoutDto.chart && (
            <Button
              size="xs"
              variant={viewMode === 'chart' ? 'solid' : 'default'}
              onClick={() => {
                setViewMode('chart')
                setStates({ listFormCode, layout: 'chart' })
              }}
              title="Grafik Görünümü"
            >
              <FaChartArea className="w-4 h-4" />
            </Button>
          )}
        </div>
      </div>

      {viewMode === 'pivot' ? (
        <Pivot
          listFormCode={listFormCode}
          searchParams={searchParams}
          isSubForm={false}
          gridDto={gridDto}
          refreshGridDto={refreshGridDto}
        />
      ) : viewMode === 'card' ? (
        <Card
          listFormCode={listFormCode}
          searchParams={searchParams}
          isSubForm={false}
          gridDto={gridDto}
        />
      ) : viewMode === 'grid' ? (
        <Grid
          listFormCode={listFormCode}
          searchParams={searchParams}
          isSubForm={false}
          gridDto={gridDto}
        />
      ) : viewMode === 'chart' ? (
        <Chart
          id={gridDto?.gridOptions.id!}
          listFormCode={listFormCode}
          filter={searchParams.toString()}
          isSubForm={true}
          gridDto={gridDto}
          refreshGridDto={refreshGridDto}
        />
      ) : null}
    </Container>
  )
}

export default List
