Untitled

 avatar
unknown
plain_text
2 months ago
8.2 kB
4
Indexable
// Imports
import React, { useState } from "react"
import {
  Box,
  Button,
  Checkbox,
  List,
  ListItem,
  ListItemText,
  TextField,
  Modal,
  InputAdornment,
} from "@mui/material"
import { useQuery, useMutation } from "@apollo/client"
import { gql } from "../../__generated__"
import { useAlert } from "../atoms/alertContext"
import { ArrowDropDownIcon } from "@mui/x-date-pickers"
import { CategoryTypesEnum } from "../../__generated__/graphql"

interface AddCategoryModalProps {
  open: boolean
  onClose: () => void
}

//interfaces to avoid type "any"
interface Field {
  categoryName: string
  countryId: string
  countryName: string[]
}

const regionCountry_Query = gql(`
  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
    }
  }
`)

// Main component
const AddCategoryModal: React.FC<AddCategoryModalProps> = ({
  open,
  onClose,
}) => {
  const [searchTerm, setSearchTerm] = useState("")
  const [showDropdown, setShowDropdown] = useState<boolean[]>([false])
  const [fields, setFields] = useState<Field[]>([
      { categoryName: "", countryId: "", countryName: [] },
    ])
  const [selectedCategory, setSelectedCategory] = useState<string>("")
  const [selectedCountryName, setSelectedCountryName] = useState<string[]>([])

  const { showAlert } = useAlert()

  const { data } = useQuery(regionCountry_Query)

  const [saveCategory] = useMutation(add_Category_Mutation)

  // Filtered country name based on the search term
  const regionCountriesName =
    data?.whoami?.userCountries
      .flatMap((area: any) => area.country)
      .filter((row: any) =>
        row.name.toLowerCase().includes(searchTerm.toLowerCase()),
      ) || []
  
  // Handler for selecting/deselecting all items
  const handleAllSelection = (index: number) => {
    const currentFields = [...fields]
    if (
      currentFields[index].countryName.length ===
      regionCountriesName.length
    ) {
      // If all are selected, deselect all
      currentFields[index].countryName = []
    } else {
      // Select all
      currentFields[index].countryName = regionCountriesName.map(
        (ta) => ta.subTaName,
      )
    }
    setFields(currentFields)
  }

  // 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("")
    setSelectedCountryName([])
    setFields([{ categoryName: "", countryId: "", countryName: [] }]) // Reset fields to initial state
    setShowDropdown([false]) // Reset dropdown visibility
    setSearchTerm("") // Clear search term
  }

  // Function to handle cancel action
  const handleCancel = () => {
    setSelectedCategory("")
    setSelectedCountryName([]) // Reset fields to initial state
    setShowDropdown([false]) // Reset dropdown visibility
    setSearchTerm("") // Clear search term
    onClose() // Close the modal
  }

  const handleSubmit = async () => {
    //     Construct the input for the mutation
    const input = fields.map((field) => ({
      name: selectedCategory,
      countryId: parseInt(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
      } 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")
    }
  }

  // Handle selection of country name
  const handleSelectCountryName= (name: string) => {
    setSelectedCountryName((prev) => {
      if (prev.includes(name)) {
        // Deselect if already selected
        return prev.filter((name) => name !== name)
      } else {
        // Select
        return [...prev, name]
      }
    })
  }

  return (
    <Modal open={open} onClose={onClose}>
      <Box
        sx={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: 860,
          height: "600px",
          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}
          onChange={(e) => setSelectedCategory(e.target.value)}
          variant="outlined"
          sx={{ mb: 2 }}
        />
        {fields.map((field, index) => (
        <>
        <TextField
          fullWidth
          label="Country"
          name="name"
          value={selectedCountryName.join(", ")} // Show selected items
          
          onClick={() => toggleDropdown(index)}
          InputProps={{
            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((row : any) => (
              <ListItem
                sx={{ cursor: "pointer" }}
                key={row.id}
                onClick={() => handleSelectCountryName(row.name)}
              >
                <Checkbox
                  checked={selectedCountryName.includes(row.name)}
                />
                <ListItemText primary={row.name} />
              </ListItem>
            ))}
          </List>
        )}</>
      ))}
        <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 2 }}>
          <Button variant="contained" onClick={handleSubmit}>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