Untitled

 avatar
unknown
plain_text
2 months ago
6.9 kB
7
Indexable
import React, { useState, useEffect } 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/icons-material/ArrowDropDown";
import { CategoryTypesEnum } from "../../__generated__/graphql";

interface AddCategoryModalProps {
  open: boolean;
  onClose: () => void;
  modalData: { id: string; name: string; countryIds: number[] } | null;
}

// Interface for state management
interface Field {
  categoryName: string;
  countryId: number[];
  countryName: string[];
}

// GraphQL Queries
const regionCountry_Query = gql(`
  query regionCountry_Query {
    whoami {
      id
      userCountries {
        country {
          id
          name
        }
      }
    }
  }
`);

const add_Category_Mutation = gql(`
  mutation add_Category_Mutation($input: [AddCategoryOrTopicInput!]!) {
    addCategoryOrTopic(input: $input) {
      success
      message
    }
  }
`);

const AddCategoryModal: React.FC<AddCategoryModalProps> = ({ open, onClose, modalData }) => {
  const { showAlert } = useAlert();
  const { data } = useQuery(regionCountry_Query);
  const [saveCategory] = useMutation(add_Category_Mutation);

  const [searchTerm, setSearchTerm] = useState("");
  const [showDropdown, setShowDropdown] = useState(false);
  const [fields, setFields] = useState<Field[]>([
    { categoryName: "", countryId: [], countryName: [] },
  ]);

  useEffect(() => {
    if (modalData) {
      setFields([
        {
          categoryName: modalData.name,
          countryId: modalData.countryIds,
          countryName:
            data?.whoami?.userCountries
              .flatMap((area: any) => area.country)
              .filter((c: any) => modalData.countryIds.includes(c.id))
              .map((c: any) => c.name) || [],
        },
      ]);
    } else {
      setFields([{ categoryName: "", countryId: [], countryName: [] }]);
    }
  }, [modalData, data]);

  // Filter country list based on search
  const regionCountries = data?.whoami?.userCountries
    .flatMap((area: any) => area.country)
    .filter((row: any) => row.name.toLowerCase().includes(searchTerm.toLowerCase())) || [];

  // Toggle dropdown visibility
  const toggleDropdown = () => setShowDropdown((prev) => !prev);

  // Handle selecting/deselecting countries
  const handleSelectCountry = (country: { id: number; name: string }) => {
    setFields((prev) =>
      prev.map((field) => {
        const selectedIndex = field.countryId.indexOf(country.id);
        if (selectedIndex !== -1) {
          return {
            ...field,
            countryId: field.countryId.filter((id) => id !== country.id),
            countryName: field.countryName.filter((name) => name !== country.name),
          };
        }
        return {
          ...field,
          countryId: [...field.countryId, country.id],
          countryName: [...field.countryName, country.name],
        };
      })
    );
  };

  // Handle selecting all countries
  const handleAllSelection = () => {
    setFields((prev) =>
      prev.map((field) =>
        field.countryId.length === regionCountries.length
          ? { ...field, countryId: [], countryName: [] }
          : {
              ...field,
              countryId: regionCountries.map((c) => c.id),
              countryName: regionCountries.map((c) => c.name),
            }
      )
    );
  };

  // Handle Submit
  const handleSubmit = async () => {
    const input = fields.map((field) => ({
      name: field.categoryName,
      countryId: field.countryId,
      type: CategoryTypesEnum.Category,
    }));

    try {
      const response = await saveCategory({ variables: { input } });
      if (response.data?.addCategoryOrTopic.success) {
        showAlert("Category saved successfully!", "success");
        onClose();
      } else {
        showAlert(response.data?.addCategoryOrTopic.message, "error");
      }
    } catch {
      showAlert("Error saving category. Please try again.", "error");
    }
  };

  return (
    <Modal open={open} onClose={onClose}>
      <Box
        sx={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: 500,
          bgcolor: "background.paper",
          boxShadow: 24,
          p: 4,
          borderRadius: 2,
        }}
      >
        <h2>{modalData ? "Edit Category" : "Add Category"}</h2>
        <TextField
          label="Category Name"
          fullWidth
          value={fields[0].categoryName}
          onChange={(e) =>
            setFields([{ ...fields[0], categoryName: e.target.value }])
          }
          sx={{ mb: 2 }}
        />

        <TextField
          label="Country"
          fullWidth
          value={fields[0].countryName.join(", ")}
          onClick={toggleDropdown}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <ArrowDropDownIcon sx={{ cursor: "pointer" }} />
              </InputAdornment>
            ),
          }}
        />

        {showDropdown && (
          <List
            sx={{
              border: "1px solid #ccc",
              borderRadius: "5px",
              maxHeight: "200px",
              overflowY: "auto",
              position: "absolute",
              width: "100%",
              zIndex: 1000,
              bgcolor: "background.paper",
            }}
          >
            <TextField
              fullWidth
              placeholder="Search..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              sx={{ p: 1 }}
            />
            <ListItem onClick={handleAllSelection} sx={{ cursor: "pointer" }}>
              <Checkbox
                checked={fields[0].countryId.length === regionCountries.length}
              />
              <ListItemText primary="Select All" />
            </ListItem>

            {regionCountries.map((country) => (
              <ListItem
                key={country.id}
                sx={{ cursor: "pointer" }}
                onClick={() => handleSelectCountry(country)}
              >
                <Checkbox checked={fields[0].countryId.includes(country.id)} />
                <ListItemText primary={country.name} />
              </ListItem>
            ))}
          </List>
        )}

        <Box sx={{ display: "flex", justifyContent: "flex-end", mt: 2 }}>
          <Button variant="contained" onClick={handleSubmit} sx={{ mr: 1 }}>
            Submit
          </Button>
          <Button variant="outlined" onClick={onClose}>
            Cancel
          </Button>
        </Box>
      </Box>
    </Modal>
  );
};

export default AddCategoryModal;
Editor is loading...
Leave a Comment