"use client"

import type React from "react"
import { useCallback, useMemo, useState } from "react"
import {
  Box,
  Stack,
  IconButton,
  TableCell,
  Checkbox,
} from "@mui/material"
import { faArrowUpRightFromSquare, faFileExport, faRotate, faTrashCan } from "@fortawesome/free-solid-svg-icons"
import {
  ActionsIconButton,
  iconButtonStyles,
} from "@/shared/theme/css"
import FontAwesome from "@/shared/components/fontawesome"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { type TableConfig, useTableManager } from "@/hooks/use-table-manager"
import TableManager from "@/shared/components/table/table-manager"
import { dateFormat, formatDate } from "@/utils/format-time"
import { StatusChip, TrajetStyledRow } from "@/shared/sections/contract/styles"
import TableFilter from "@/shared/components/table/table-filter"
import { useTheme } from "@mui/material/styles"
import type { IUsager } from "@/shared/types/usager"
import { _usagers, DEFAULT_CIRCUIT_USAGER_TABLE_HEAD } from "@/shared/_mock/_usagers"
import { useRouter } from "@/hooks/use-router"
import { paths } from "@/routes/paths"
import { getEtatLabel } from "@/shared/_mock/_circuit"
import ConfirmDialog from "@/shared/components/dialog/confirmDialog"
import UserSelector from "./userSelector"
import { AddressSelector } from "./adressSelector"
import ExportButton from '@/shared/components/table/table-export-button';
import { TableType } from "@/shared/types/common"

const circuitUsagerConfig: TableConfig<IUsager> = {
  initialData: _usagers,
  defaultTableHead: DEFAULT_CIRCUIT_USAGER_TABLE_HEAD,
}

export default function CircuitUsager() {
  const router = useRouter()
  const theme = useTheme()
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [userToDelete, setUserToDelete] = useState<string | null>(null)
  const [selectedUsers, setSelectedUsers] = useState<string[]>([])

  const openTrajetPage = (id: string) => {
    router.push(`${paths.dashboard.exploitation.circuitUsager.usager}?id=${id}`)
  }

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    dataToExport,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleDelete,
  } = useTableManager<IUsager>(circuitUsagerConfig)

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "dateNaissance":
        return formatDate(value, dateFormat.isoDate)
      case "etat":
        return <StatusChip label={getEtatLabel(value)} status={value} theme={theme} size="small" />
      case "adresse":
        return <AddressSelector currentAddress={value} />
      default:
        return value
    }
  }

  const renderRow = (row: IUsager) => {
    return (
      <TrajetStyledRow
        key={row.id}
         style={{ cursor: "pointer" }}
      >

        {tableHead.slice(0, -2).map((column: any) => (
          <TableCell
            key={column.id}
            align={column.align || "left"}
            sx={{ whiteSpace: "nowrap", py: column.id === "etat" ? 0.2 : table.dense ? 0.5 : 1 }}
          >
            {renderCellContent(column.id, row[column.id as keyof IUsager])}
          </TableCell>
        ))}
        <TableCell align="center" sx={{ display: "flex" }}>
          <CustomTooltip title="Consulter usager" arrow>
            <IconButton onClick={() => openTrajetPage(row.id)} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faArrowUpRightFromSquare} width={14} />
            </IconButton>
          </CustomTooltip>
          <CustomTooltip title="Désaffecter usager" arrow>
            <IconButton onClick={() => handleDeleteDocument(row.id)} size="small" sx={ActionsIconButton}>
              <FontAwesome icon={faTrashCan} width={14} />
            </IconButton>
          </CustomTooltip>
        </TableCell>
      </TrajetStyledRow>
    )
  }

  const handleDeleteDocument = useCallback((userId: string) => {
    setUserToDelete(userId)
    setDeleteDialogOpen(true)
  }, [])

  const confirmDeleteDocument = useCallback(() => {
    if (userToDelete) {
      setSelectedUsers((prevUsers) => prevUsers.filter((userId) => userId !== userToDelete))
      setDeleteDialogOpen(false)
      setUserToDelete(null)
    }
  }, [userToDelete])

  const availableUsers = useMemo(() => {
    return filteredData.filter((user) => !selectedUsers.includes(user.id))
  }, [filteredData, selectedUsers])

  const handleUserSelection = useCallback((users: string[]) => {
    setSelectedUsers(users)
  }, [])

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="space-between" gap="8px" py={2}>
        <UserSelector users={availableUsers} selectedUsers={selectedUsers} onUserSelection={handleUserSelection} />

        <Stack direction="row" alignItems="center" gap="8px">
          <CustomTooltip title="Refresh" arrow>
            <IconButton onClick={handleResetFilters} sx={iconButtonStyles}>
              <FontAwesome icon={faRotate} width={16} />
            </IconButton>
          </CustomTooltip>
          <TableFilter
            onResetFilters={handleResetFilters}
            onFilters={handleFilterChange}
            initialColumns={tableHead}
            type="document"
          />
            <ExportButton
              tooltipTitle={"Exporter"}
              type={TableType.Usager}
              filteredData={dataToExport}
              tableHead={tableHead}
            />
        </Stack>
      </Stack>
      <TableManager
        filteredData={filteredData.filter((user) => selectedUsers.includes(user.id))}
        table={table}
        tableHead={tableHead}
        notFound={selectedUsers.length > 0 ? notFound : true}
        filters={filters}
        onFilterChange={handleFilterChange}
        renderRow={renderRow}
        sx={{ backgroundColor: 'primary.lighter' }}
        isTrajetTable={true}
        isWithoutTabs
      />
      <ConfirmDialog
        open={deleteDialogOpen}
        title="Confirmation de désaffectation"
        content="Êtes-vous sûr de vouloir désaffecter cet usager du circuit ?"
        onConfirm={confirmDeleteDocument}
        onCancel={() => setDeleteDialogOpen(false)}
      />
    </Box>
  )
}