"use client"

import type React from "react"

import { useState } from "react"
import Button from "@mui/material/Button"
import Menu from "@mui/material/Menu"
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"
import { StyledMenuItem } from "@/shared/theme/css"
import { ADRESSE } from "@/shared/_mock"

interface AddressSelectorProps {
  currentAddress: string
}

export function AddressSelector({ currentAddress }: AddressSelectorProps) {
  const [selectedAddress, setSelectedAddress] = useState(currentAddress)
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
  const open = Boolean(anchorEl)

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => {
    setAnchorEl(null)
  }

  const handleAddressSelect = (address: string) => {
    setSelectedAddress(address)
    handleClose()
  }

  return (
    <>
      <Button
        id="address-button"
        aria-controls={open ? "address-menu" : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleClick}
        endIcon={<KeyboardArrowDownIcon />}
        size="small"
        variant="text"
        sx={{ textTransform: "none", color: "text.primary", fontSize: "12px" }}
      >
        {selectedAddress || "Select address"}
      </Button>
      <Menu
        id="address-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        MenuListProps={{
          "aria-labelledby": "address-button",
        }}
      >
        {ADRESSE.map((address, index) => (
          <StyledMenuItem
            key={index}
            onClick={() => handleAddressSelect(address)}
            selected={selectedAddress === address}
          >
            {address}
          </StyledMenuItem>
        ))}
      </Menu>
    </>
  )
}
