  "use client"

  import type React from "react"
  import { useState, useRef, useEffect, useCallback, useMemo } from "react"
  import { alpha, Box, Checkbox, CircularProgress, debounce } 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 ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { usePassengersCircuitStore } from "@/shared/api/stores/circuit-service/passengerscircuitStore"
import { enqueueSnackbar } from "notistack"

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

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


    const {
      passengersWithNoCircuit,
      loadingPassengers,
      error: passengersError,
      searchPassengersWithNoCircuit
    } = usePassengersCircuitStore()
    
    const debouncedSearch = useMemo(() => {
    const searchFunction = async (searchTerm: string) => {
      if (!isFocused) return
      
      try {
        await searchPassengersWithNoCircuit(searchTerm.trim())
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors du chargement des passagers', {
          variant: 'error'
        })
      }
    }

    return debounce(searchFunction, 300)
  }, [searchPassengersWithNoCircuit, isFocused])

  useEffect(() => {
    if (isFocused) {
      debouncedSearch(search)
    }

    return () => {
      debouncedSearch.clear()
    }
  }, [search, isFocused, debouncedSearch])


    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([...localSelectedUsers])
      setSearch("")
      setLocalSelectedUsers([])
    }, [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={!(loadingPassengers || loading)}
              defaultComponent={<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", py: 4 }}>
                  <CircularProgress size={24} />
                </Box>}
              >
                <ConditionalComponent isValid={passengersWithNoCircuit.length > 0}
                defaultComponent={<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", py: 4, color: "text.secondary" }}>
                  Aucun usager trouvé
                </Box>}
                >
                  {passengersWithNoCircuit.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.lastName} ${user.firstName}`}</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 || loadingPassengers}
          sx={{ maxHeight: 36, px: 2, mt: 1 }}
        >
          Appliquer
        </AddButton>
        </CustomTooltip>
      </Box>
    )
  }

