"use client"

import type React from "react"
import { useState, useRef, useEffect, useCallback, useMemo } from "react"
import { alpha, Box, Checkbox } from "@mui/material"
import { StyledTextField, ScrollBox } from "@/shared/theme/css"
import type { IUsager } from "@/shared/types/usager"
import { AddButton } from "@/shared/components/table/styles"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"

interface UserSelectorProps {
  users: IUsager[]
  selectedUsers: string[]
  onUserSelection: (users: string[]) => void
}

export default function UserSelector({ users, selectedUsers, onUserSelection }: UserSelectorProps) {
  const [search, setSearch] = useState("")
  const [isFocused, setIsFocused] = useState(false)
  const wrapperRef = useRef<HTMLDivElement>(null)
  const [localSelectedUsers, setLocalSelectedUsers] = useState<string[]>([])

  const filteredUsers = useMemo(
    () => users.filter((user) => `${user.nom} ${user.prenom}`.toLowerCase().includes(search.toLowerCase())),
    [users, search],
  )

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
        setIsFocused(false)
      }
    }

    document.addEventListener("mousedown", handleClickOutside)
    return () => document.removeEventListener("mousedown", handleClickOutside)
  }, [])

  const handleSelect = useCallback((userId: string) => {
    setLocalSelectedUsers((prev) => (prev.includes(userId) ? prev.filter((id) => id !== userId) : [...prev, userId]))
  }, [])

  const onApplySelection = useCallback(() => {
    onUserSelection([...selectedUsers, ...localSelectedUsers])
    setSearch("")
    setLocalSelectedUsers([])
  }, [selectedUsers, localSelectedUsers, onUserSelection])

  const handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value)
  }, [])

  const handleFocus = useCallback(() => setIsFocused(true), [])

  return (
    <Box sx={{ display: "flex", gap: 1, verticalAlign: "center", minWidth: "38%" }}>
      <Box ref={wrapperRef} sx={{ position: "relative", width: "100%" }}>
        <StyledTextField
          name="select-users"
          label="Sélectionner des usagers"
          placeholder="Nom Usager"
          InputLabelProps={{
            shrink: true,
          }}
          value={search}
          onChange={handleSearchChange}
          onFocus={handleFocus}
          fullWidth
        />

        {isFocused && (
          <ScrollBox
            sx={{
              position: "absolute",
              top: "100%",
              left: 5,
              right: 5,
              mt: 1,
              backgroundColor: "background.paper",
              border: "1px solid",
              borderColor: "divider",
              borderRadius: 2,
              boxShadow: 3,
              zIndex: 10,
              height: "calc(100vh - 490px)",
              overflowY: "auto",
            }}
          >
            {filteredUsers.map((user) => {
              const isChecked = localSelectedUsers.includes(user.id)
              return (
                <Box
                  key={user.id}
                  sx={{
                    p: 0.5,
                    pl: 1,
                    mx: 2,
                    my: 1,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    bgcolor: isChecked ? "primary.main" : "background.paper",
                    color: isChecked ? "white" : "text.primary",
                    borderRadius: 2,
                    "&:hover": {
                      bgcolor: (theme) => alpha(theme.palette.primary.main, 0.1),
                      color: "primary.main",
                    },
                  }}
                >
                  <span>{`${user.nom} ${user.prenom}`}</span>
                  <Checkbox
                    onClick={() => handleSelect(user.id)}
                    checked={isChecked}
                    sx={{
                      m: 0,
                      py: 1,
                      "&.Mui-checked": {
                        color: "white",
                      },
                      "& .MuiSvgIcon-root": {
                        fontSize: 18,
                      },
                    }}
                  />
                </Box>
              )
            })}
          </ScrollBox>
        )}
      </Box>
      <CustomTooltip title="Appliquer l'affectation" arrow>
      <AddButton
        variant="contained"
        onClick={() => {
          onApplySelection()
          setIsFocused(false)
        }}
        sx={{ maxHeight: 36, px: 2, mt: 1 }}
      >
        Appliquer
      </AddButton>
      </CustomTooltip>
    </Box>
  )
}

