  "use client"

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

  interface UserSelectorProps {
    users: UsagerSelector[]
    selectedUsers: string[]
    onUserSelection: (users: string[]) => void
    loading?: boolean
  }

  export default function UserSelector({ users, selectedUsers, onUserSelection, loading = false }: 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
          />

          <ConditionalComponent isValid={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 - 510px)",
                overflowY: "auto",
              }}
            >
              <ConditionalComponent isValid={!loading}
              defaultComponent={<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", py: 4 }}>
                  <CircularProgress size={24} />
                </Box>}
              >
                <ConditionalComponent isValid={filteredUsers.length > 0}
                defaultComponent={<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", py: 4, color: "text.secondary" }}>
                  Aucun usager trouvé
                </Box>}
                >
                  {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>
                  )
                })}
                </ConditionalComponent>
              </ConditionalComponent>
            </ScrollBox>
          </ConditionalComponent>
        </Box>
        <CustomTooltip title="Appliquer l'affectation" arrow>
        <AddButton
          variant="contained"
          onClick={() => {
            onApplySelection()
            setIsFocused(false)
          }}
          disabled={loading}
          sx={{ maxHeight: 36, px: 2, mt: 1 }}
        >
          Appliquer
        </AddButton>
        </CustomTooltip>
      </Box>
    )
  }

