Untitled
unknown
plain_text
10 months ago
9.4 kB
5
Indexable
import React, { useState } from "react"
import { useMutation, useQuery } from "@apollo/client"
import {
Box,
Button,
Checkbox,
InputAdornment,
List,
ListItem,
ListItemText,
Modal,
TextField,
} from "@mui/material"
import { ArrowDropDownIcon } from "@mui/x-date-pickers"
import { gql } from "../../__generated__"
import { CategoryTypesEnum } from "../../__generated__/graphql"
import { useAlert } from "../atoms/alertContext"
// Interfaces to avoid type "any"
interface AddCategoryModalProps {
open: boolean
onClose: () => void
}
interface Field {
categoryName: string
countryId: number[]
groupId: number | null
countryName: string[]
}
const regionCountry_Query = gql(/* GraphQL */ `
query regionCountry_Query {
whoami {
id
userCountries {
country {
id
name
frmlName
iso2CntryCd
iso3CntryCd
isoNum
}
}
regionUsers {
region {
regionCountries {
country {
id
name
}
}
}
}
}
}
`)
// Mutation for Save
const add_Category_Mutation = gql(/* GraphQL */ `
mutation add_Category_Mutation($input: [AddCategoryOrTopicInput!]!) {
addCategoryOrTopic(input: $input) {
success
message
}
}
`)
const AddCategoryModal: React.FC<AddCategoryModalProps> = ({
open,
onClose,
}) => {
const [searchTerm, setSearchTerm] = useState("")
const [showDropdown, setShowDropdown] = useState<boolean[]>([false])
const [fields, setFields] = useState<Field[]>([
{ categoryName: "", countryId: [], groupId: null, countryName: [] },
])
const [selectedCategory, setSelectedCategory] = useState<string>("")
const { showAlert } = useAlert()
const { data } = useQuery(regionCountry_Query)
const [saveCategory] = useMutation(add_Category_Mutation)
// Filtered country names based on the search term
const regionCountriesName =
data?.whoami?.userCountries
.flatMap((area: any) => area.country)
.filter((row: any) =>
row.name.toLowerCase().includes(searchTerm.toLowerCase()),
) ||
// .map((row: any) => ({ id: row.id, name: row.name }))
[]
// Handler for selecting/deselecting all items
const handleAllSelection = (index: number) => {
const updatedFields = [...fields]
if (
updatedFields[index].countryName.length === regionCountriesName.length
) {
updatedFields[index].countryId = []
updatedFields[index].countryName = []
} else {
updatedFields[index].countryId = regionCountriesName.map((c) => c.id)
updatedFields[index].countryName = regionCountriesName.map((c) => c.name)
}
setFields(updatedFields)
}
// Function to toggle dropdown visibility for a specific field
const toggleDropdown = (index: number) => {
const updatedDropdown = [...showDropdown]
updatedDropdown[index] = !updatedDropdown[index] // Toggle the visibility for the specific field
setShowDropdown(updatedDropdown)
}
// Function to handle Reset button
const handleReset = () => {
setSelectedCategory("")
setFields([
{ categoryName: "", countryId: [], groupId: null, countryName: [] },
]) // Reset fields to initial state
setShowDropdown([false]) // Reset dropdown visibility
setSearchTerm("") // Clear search term
}
// Function to handle cancel action
const handleCancel = () => {
setSelectedCategory("")
setFields([
{ categoryName: "", countryId: [], groupId: null, countryName: [] },
])
setShowDropdown([false]) // Reset dropdown visibility
setSearchTerm("") // Clear search term
onClose() // Close the modal
}
// Handle category name change
const handleCategoryChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSelectedCategory(e.target.value)
}
// Function to handle form submission
const handleAddSubmit = async () => {
// Construct the input for the mutation
const input = fields.map((field) => ({
name: selectedCategory,
countryId: field.countryId,
type: CategoryTypesEnum.Category,
}))
try {
const response = await saveCategory({
variables: { input },
})
if (response?.data!.addCategoryOrTopic.success) {
// Handle success response
showAlert("Association saved successfully!", "success")
handleReset() // Reset the form after successful submission
onClose()
} else {
// Handle error response
showAlert(response?.data!.addCategoryOrTopic.message, "error")
}
} catch {
// Handle any errors that occur during the mutation
showAlert("Error in Saving the Relation. Please try again.", "error")
}
}
return (
<Modal open={open} onClose={onClose}>
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: {
xs: '90%',
sm: 620,
md: 860
},
height: {
xs: '55vh',
sm: '350px',
md: '350px'
},
maxHeight: "95vh",
bgcolor: "background.paper",
boxShadow: 24,
p: 4,
borderRadius: 2,
overflowY: "auto",
alignItems: "center",
justifyContent: "center",
}}
>
<h2>Add Category</h2>
<TextField
label="Category"
fullWidth
value={selectedCategory} // Bind to selectedCategory state
onChange={handleCategoryChange} // Handle the change event
variant="outlined"
sx={{ mb: 2 }}
/>
{fields.map((field, index) => (
<div key={index}>
<TextField
fullWidth
label="Country"
name="name"
value={field.countryName.join(", ") || ""} // Show selected country names
onClick={() => toggleDropdown(index)}
slotProps={{
input: {
endAdornment: (
<InputAdornment sx={{ cursor: "pointer" }} position="end">
<ArrowDropDownIcon />
</InputAdornment>
),
},
}}
/>
{showDropdown[index] && (
<List
sx={{
border: "1px solid #ccc",
borderRadius: "15px",
maxHeight: "230px",
overflowY: "auto",
position: "absolute",
zIndex: 1000,
bgcolor: "background.paper",
}}
>
<TextField
fullWidth
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<ListItem
sx={{
cursor: "pointer",
}}
onClick={() => handleAllSelection(index)}
>
<Checkbox
checked={
field.countryName.length === regionCountriesName.length
}
/>
<ListItemText primary="Select All" />
</ListItem>
{regionCountriesName.map((country) => (
<ListItem
sx={{ cursor: "pointer" }}
key={country.id}
onClick={() => {
const updatedFields = [...fields]
const selectedCountries = updatedFields[index].countryName
if (selectedCountries.includes(country.name)) {
updatedFields[index].countryName =
selectedCountries.filter(
(name) => name !== country.name,
)
} else {
updatedFields[index].countryName.push(country.name)
updatedFields[index].countryId.push(country.id)
}
setFields(updatedFields)
}}
>
<Checkbox
checked={field.countryName.includes(country.name)}
/>
<ListItemText primary={country.name} />
</ListItem>
))}
</List>
)}
</div>
))}
<Box
sx={{ display: "flex", justifyContent: "flex-end", mt: 2, gap: 1 }}
>
<Button variant="contained" onClick={handleAddSubmit}>
Submit
</Button>
<Button variant="contained" onClick={handleReset}>
Reset
</Button>
<Button variant="contained" onClick={handleCancel}>
Cancel
</Button>
</Box>
</Box>
</Modal>
)
}
export default AddCategoryModal
Editor is loading...
Leave a Comment