import React, { Suspense, startTransition, useCallback, useEffect, useMemo, useState } from 'react'
import { useParams, useSearchParams } from 'react-router-dom'
import classNames from 'classnames'

import Container from '@/components/shared/Container'
import { Badge, Button } from '@/components/ui'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { useCurrentMenuIcon } from '@/utils/hooks/useCurrentMenuIcon'

import { useStoreActions, useStoreState } from '@/store/store'
import { GridDto } from '@/proxy/form/models'
import { getList } from '@/services/form.service'
import { ListViewLayoutType } from '../admin/listForm/edit/types'

import {
  FaChartArea,
  FaList,
  FaSitemap,
  FaTable,
  FaCalendarAlt,
  FaProjectDiagram,
} from 'react-icons/fa'

/* =======================
   🔥 LAZY VIEW IMPORTS
   ======================= */
const Grid = React.lazy(() => import('./Grid'))
const Pivot = React.lazy(() => import('./Pivot'))
const Tree = React.lazy(() => import('./Tree'))
const Chart = React.lazy(() => import('./Chart'))
const GanttView = React.lazy(() => import('./GanttView'))
const SchedulerView = React.lazy(() => import('./SchedulerView'))

function isLayoutValid(dto: GridDto, layout: ListViewLayoutType | undefined): boolean {
  if (!layout || layout === 'grid') return true
  if (layout === 'pivot') return !!dto.gridOptions?.layoutDto?.pivot
  if (layout === 'chart') return !!dto.gridOptions?.layoutDto?.chart
  if (layout === 'tree')
    return !!(dto.gridOptions?.layoutDto?.tree && dto.gridOptions?.treeOptionDto?.parentIdExpr)
  if (layout === 'gantt')
    return !!(
      dto.gridOptions?.layoutDto?.gantt &&
      dto.gridOptions?.ganttOptionDto?.parentIdExpr &&
      dto.gridOptions?.ganttOptionDto?.titleExpr
    )
  if (layout === 'scheduler')
    return !!(
      dto.gridOptions?.layoutDto?.scheduler &&
      dto.gridOptions?.schedulerOptionDto?.textExpr &&
      dto.gridOptions?.schedulerOptionDto?.startDateExpr
    )
  return false
}

const List: React.FC = () => {
  const { listFormCode = '' } = useParams()
  const [searchParams] = useSearchParams()

  const { translate } = useLocalization()
  const mode = useStoreState((state) => state.theme.mode)
  const MenuIcon = useCurrentMenuIcon('w-5 h-5')

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

  const [gridDto, setGridDto] = useState<GridDto | null>(null)
  const [viewMode, setViewMode] = useState<ListViewLayoutType | undefined>()

  /* =======================
     🔹 GRID DTO FETCH
     ======================= */
  const refreshGridDto = useCallback(async () => {
    if (!listFormCode) return
    try {
      const response = await getList({ listFormCode })
      setGridDto(response.data)
    } catch (err) {
      console.error('GridDto load error:', err)
    }
  }, [listFormCode])

  useEffect(() => {
    refreshGridDto()
  }, [refreshGridDto])

  /* =======================
     🔹 INITIAL VIEW MODE
     ======================= */
  useEffect(() => {
    if (!gridDto) return

    const savedLayout = states.find((s) => s.listFormCode === listFormCode)?.layout
    const defaultLayout = gridDto.gridOptions?.layoutDto?.defaultLayout
    const candidate = savedLayout ?? defaultLayout
    
    setViewMode(isLayoutValid(gridDto, candidate) ? candidate : 'grid')
  }, [gridDto, states, listFormCode])

  /* =======================
     🔹 VIEW SWITCH HANDLER
     ======================= */
  const setLayout = useCallback(
    (layout: ListViewLayoutType) => {
      startTransition(() => {
        setViewMode(layout)
      })
      setStates({ listFormCode, layout })
    },
    [listFormCode, setStates],
  )

  /* =======================
     🔹 PRELOAD MAP (HOVER)
     ======================= */
  const preload = useMemo(
    () => ({
      grid: () => import('./Grid'),
      pivot: () => import('./Pivot'),
      tree: () => import('./Tree'),
      chart: () => import('./Chart'),
      gantt: () => import('./GanttView'),
      scheduler: () => import('./SchedulerView'),
    }),
    [],
  )

  if (!listFormCode || !gridDto || !viewMode) {
    return null
  }

  return (
    <Container>
      {/* =======================
          HEADER
         ======================= */}
      <div
        className={classNames(
          'flex items-center gap-2 pb-1 border-b',
          mode === 'light' ? 'border-gray-200' : 'border-neutral-700',
        )}
      >
        {MenuIcon}
        <h4 className="text-sm font-medium">{translate('::' + gridDto.gridOptions.title)}</h4>
        <Badge content={viewMode} />

        {/* =======================
            VIEW BUTTONS
           ======================= */}
        <div className="flex gap-1 ml-auto">
          {gridDto?.gridOptions?.layoutDto.scheduler &&
            gridDto?.gridOptions?.schedulerOptionDto?.textExpr &&
            gridDto?.gridOptions?.schedulerOptionDto?.startDateExpr && (
              <Button
                size="xs"
                variant={viewMode === 'scheduler' ? 'solid' : 'default'}
                onClick={() => setLayout('scheduler')}
                onMouseEnter={() => preload.scheduler()}
              >
                <FaCalendarAlt />
              </Button>
            )}

          {gridDto?.gridOptions?.layoutDto.gantt &&
            gridDto?.gridOptions?.ganttOptionDto?.parentIdExpr &&
            gridDto?.gridOptions?.ganttOptionDto?.titleExpr && (
              <Button
                size="xs"
                variant={viewMode === 'gantt' ? 'solid' : 'default'}
                onClick={() => setLayout('gantt')}
                onMouseEnter={() => preload.gantt()}
              >
                <FaProjectDiagram />
              </Button>
            )}

          {gridDto?.gridOptions?.layoutDto.tree &&
            gridDto?.gridOptions?.treeOptionDto?.parentIdExpr && (
              <Button
                size="xs"
                variant={viewMode === 'tree' ? 'solid' : 'default'}
                onClick={() => setLayout('tree')}
                onMouseEnter={() => preload.tree()}
              >
                <FaSitemap />
              </Button>
            )}

          <Button
            size="xs"
            variant={viewMode === 'grid' ? 'solid' : 'default'}
            onClick={() => setLayout('grid')}
            onMouseEnter={() => preload.grid()}
          >
            <FaList />
          </Button>

          {gridDto.gridOptions.layoutDto.pivot && (
            <Button
              size="xs"
              variant={viewMode === 'pivot' ? 'solid' : 'default'}
              onClick={() => setLayout('pivot')}
              onMouseEnter={() => preload.pivot()}
            >
              <FaTable />
            </Button>
          )}

          {gridDto.gridOptions.layoutDto.chart && (
            <Button
              size="xs"
              variant={viewMode === 'chart' ? 'solid' : 'default'}
              onClick={() => setLayout('chart')}
              onMouseEnter={() => preload.chart()}
            >
              <FaChartArea />
            </Button>
          )}
        </div>
      </div>

      {/* =======================
          VIEW RENDER
         ======================= */}
      <Suspense fallback={<div className="p-4 text-sm">Yükleniyor...</div>}>
        {viewMode === 'grid' && (
          <Grid
            listFormCode={listFormCode}
            searchParams={searchParams}
            isSubForm={false}
            gridDto={gridDto}
          />
        )}

        {viewMode === 'pivot' && (
          <Pivot
            listFormCode={listFormCode}
            searchParams={searchParams}
            isSubForm={false}
            gridDto={gridDto}
            refreshGridDto={refreshGridDto}
          />
        )}

        {viewMode === 'tree' && (
          <Tree
            listFormCode={listFormCode}
            searchParams={searchParams}
            isSubForm={false}
            gridDto={gridDto}
          />
        )}

        {viewMode === 'scheduler' && (
          <SchedulerView
            listFormCode={listFormCode}
            searchParams={searchParams}
            isSubForm={false}
            gridDto={gridDto}
          />
        )}

        {viewMode === 'gantt' && (
          <GanttView
            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}
          />
        )}
      </Suspense>
    </Container>
  )
}

export default List
