import React, { useState, useMemo, useEffect } from "react";
import {
  Grid,
  Card,
  Typography,
  TextField,
  Button,
  Box,
  MenuItem,
} from "@mui/material";
import SaveAltIcon from "@mui/icons-material/SaveAlt";
import CloseIcon from "@mui/icons-material/Close";
import { useFormik } from "formik";
import * as yup from "yup";
import { useStyles } from "../../../theme/appStyles";
import CircularProgress from "@mui/material/CircularProgress";
import { useNotifier } from "../../../Core/Notifier";
import axios from "axios";
import { useNavigate, useParams } from 'react-router-dom';
import {
  useGetSubCategoryByArrayQuery,
} from "../../../Api/attoDeskApi";
import {
  ICategory,
} from "../../../Api/Interface/api.interface";

interface Expense {
  id: number;
  category_name: string;
  mainCatId: number;
}

const CategoryForm = () => {
  const API_URL = process.env.REACT_APP_API_URL;
  const { projectId } = useParams();
  const classes = useStyles();
  const [loading, setLoading] = useState(false);
  const { showErrorMessage, showMessage } = useNotifier();
  const navigate = useNavigate();
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);
 const [subCategories, setSubCategories] = useState<Expense[]>([]);


  const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<number | null>(null);

    
   const [categoryList, setCategoryList] = useState<Expense[]>([]); 
      


  const formik = useFormik({
    initialValues: {
      categoryName: "",
    },
    validationSchema: yup.object({
      categoryName: yup
        .string()
        .required("Category name is required")
        .max(50, "Category name must not exceed 50 characters"),
    }),
 onSubmit: async (values) => {
  setLoading(true);

  try {
    const formData = new FormData();
    formData.append("category_name", values.categoryName);
    formData.append(
      "mainCatId",
      selectedCategoryId !== null ? String(selectedCategoryId) : ""
    );

    const response = await axios.post(
      `${API_URL}/save-expense-category/${projectId}`,
      formData,
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    showMessage("Category saved successfully!");
    formik.resetForm();
      setSelectedCategoryId(null);
    setSelectedSubCategoryId(null);
    fetchExpenses();
  } catch (error: any) {
  // Now TypeScript knows 'error' can have properties
  if (error.response && error.response.data && error.response.data.errors) {
    const errorMessages = error.response.data.errors;
    if (errorMessages.category_name) {
      showErrorMessage(errorMessages.category_name[0]); // show first error
    } else {
      showErrorMessage("An error occurred while saving the category.");
    }
  } else {
    showErrorMessage("An error occurred while saving the category.");
  }


  } finally {
    setLoading(false);
  }
}

  });

  const fetchExpenses = async () => {
  try {
    const response = await axios.get(`${API_URL}/view-expense-category/${projectId}`);
    setCategoryList(response.data); // Set the fetched data to state
  } catch (error) {
    console.error("Failed to load expense category", error);
  }
};

useEffect(() => {
  fetchExpenses();
}, [API_URL, projectId]); 


    const handleMainCategoryChange = (
      event: React.ChangeEvent<{ value: unknown }>
    ) => {
      const categoryId = event.target.value as number;
      setSelectedCategoryId(categoryId);
      
     
        const filteredSubs = categoryList.filter(
    (cat) => cat.mainCatId === categoryId
  );

     setSubCategories(filteredSubs); 
     setSelectedSubCategoryId(null);
  
    };
  
   
  return (
    <div>
      <Grid container spacing={3}>
        <Grid item lg={3} md={3} sm={12} xs={12}>
          <Card>
            <Grid
              container
              justifyContent="space-between"
              sx={{ borderBottom: 2, padding: 2 }}
            >
              <Grid
                item
                lg={12}
                md={12}
                sm={12}
                xs={12}
                pt={2}
                alignContent={"center"}
              >
                <Typography className={classes.cardTitle}>
                  Create Expense Category
                </Typography>
              </Grid>
            </Grid>
          </Card>
        </Grid>

        <Grid item lg={9} md={9} sm={12} xs={12}>
          <form onSubmit={formik.handleSubmit}>
            <Grid container>
              <Grid item lg={12} md={12} sm={12} xs={12}>
                <Card>
                  <Grid container spacing={3} sx={{ padding: 3 }}>
                    {/* Category Name Field */}

          
                    <Grid item lg={7} md={7} sm={12} xs={12}>
                      <Grid container alignItems="center">
                        <Grid item lg={12} md={12} sm={12} xs={12}>
                          <Typography variant="subtitle1">
                            Main Category
                          </Typography>
                        </Grid>
                        <Grid
                          item
                          lg={12}
                          md={12}
                          sm={12}
                          xs={12}
                          display="flex"
                          alignItems="center"
                        >
                          <TextField
                            select
                            fullWidth
                            size="small"
                            className={classes.textField}
                            value={selectedCategoryId || null}
                            onChange={handleMainCategoryChange}
                            InputLabelProps={{ shrink: true }}
                          >
                            <MenuItem
                              value=""
                              disabled
                              style={{ color: "gray" }}
                            >
                              Select an option
                            </MenuItem>
                            {categoryList &&
                              categoryList.filter((category) => category.mainCatId === null).map((category) => (
                                <MenuItem key={category.id} value={category.id}>
                                  {category.category_name}
                                </MenuItem>
                              ))}
                          </TextField>
                        </Grid>
                      </Grid>
                    </Grid>

                    {selectedCategoryId && subCategories.length > 0 && (
  <Grid item lg={5} md={5} sm={12} xs={12}>
    <Typography variant="subtitle1">Sub Category</Typography>
    <TextField
      select
      fullWidth
      size="small"
      className={classes.textField}
      value={selectedSubCategoryId || ""}
      onChange={(e) =>
        setSelectedSubCategoryId(Number(e.target.value))
      }
      InputLabelProps={{ shrink: true }}
    >
      <MenuItem value="" disabled>
        Select a subcategory
      </MenuItem>
      {subCategories.map((sub) => (
        <MenuItem key={sub.id} value={sub.id}>
          {sub.category_name}
        </MenuItem>
      ))}
    </TextField>
  </Grid>
)}


                    {/* {selectedCategoryId && subCategoryList.length > 0 && (
                      <Grid item lg={6} md={6} sm={12} xs={12}>
                        <Grid container alignItems="center">
                          <Grid item lg={12} md={12} sm={12} xs={12}>
                            <Typography variant="subtitle1">
                              Sub Category
                            </Typography>
                          </Grid>
                          <Grid
                            item
                            lg={12}
                            md={12}
                            sm={12}
                            xs={12}
                            display="flex"
                            alignItems="center"
                          >
                            <TextField
                              select
                              fullWidth
                              size="small"
                              className={classes.textField}
                              value={
                                selectedSubCategoryId === null
                                  ? ""
                                  : selectedSubCategoryId
                              }
                              onChange={handleSubCategoryChange}
                              InputLabelProps={{ shrink: true }}
                            >
                              <MenuItem
                                value=""
                                disabled
                                style={{ color: "gray" }}
                              >
                                Select an option
                              </MenuItem>
                              {subCategoryList.map((subcategory) => (
                                <MenuItem
                                  key={subcategory.id}
                                  value={subcategory.id}
                                >
                                  {subcategory.categoryName}
                                </MenuItem>
                              ))}
                            </TextField>
                          </Grid>
                        </Grid>
                      </Grid>
                    )} */}

                    {/* {selectedCategoryId &&
                      selectedSubCategoryId &&
                      subToSubCategoryList.length > 0 && (
                        <Grid item lg={6} md={6} sm={12} xs={12}>
                          <Grid container alignItems="center">
                            <Grid item lg={12} md={12} sm={12} xs={12}>
                              <Typography variant="subtitle1">
                                Sub-to-Sub Category
                              </Typography>
                            </Grid>
                            <Grid
                              item
                              lg={12}
                              md={12}
                              sm={12}
                              xs={12}
                              display="flex"
                              alignItems="center"
                            >
                              <TextField
                                select
                                fullWidth
                                size="small"
                                className={classes.textField}
                                value={
                                  selectedSubToSubCategoryId === null
                                    ? ""
                                    : selectedSubToSubCategoryId
                                }
                                onChange={handleSubToSubCategoryChange}
                                InputLabelProps={{ shrink: true }}
                              >
                                <MenuItem
                                  value=""
                                  disabled
                                  style={{ color: "gray" }}
                                >
                                  Select an option
                                </MenuItem>
                                {subToSubCategoryList.map(
                                  (subToSubcategory) => (
                                    <MenuItem
                                      key={subToSubcategory.id}
                                      value={subToSubcategory.id}
                                    >
                                      {subToSubcategory.categoryName}
                                    </MenuItem>
                                  )
                                )}
                              </TextField>
                            </Grid>
                          </Grid>
                        </Grid>
                      )} */}
               
         



                 <Grid item lg={7} md={7} sm={12} xs={12}>
                      <Typography variant="subtitle1">Category Name</Typography>
                      <TextField
                        placeholder="Enter category name"
                        size="small"
                        {...formik.getFieldProps("categoryName")}
                        error={
                          formik.touched.categoryName &&
                          Boolean(formik.errors.categoryName)
                        }
                        helperText={
                          formik.touched.categoryName &&
                          formik.errors.categoryName
                        }
                        fullWidth
                      />
                    </Grid>
                  </Grid>
                </Card>
              </Grid>

              {/* Submit and Cancel Buttons */}
              <Grid item lg={12} md={12} sm={12} xs={12} pt={3}>
                <Card>
                  <Grid container spacing={3} sx={{ padding: 3 }}>
                    <Grid
                      item
                      lg={12}
                      md={12}
                      sm={12}
                      xs={12}
                      sx={{ display: "flex", justifyContent: "flex-end" }}
                    >
                      <Button
                        variant="outlined"
                        className={classes.addButton}
                        startIcon={<CloseIcon />}
                        onClick={() =>navigate(`/expense/list/${projectId}`)}
                        // onClick={() => formik.resetForm()}
                      >
                        Cancel
                      </Button>
                      <Box m={0.5}></Box>
                      <Button
                        variant="contained"
                        className={classes.addButton}
                        startIcon={<SaveAltIcon />}
                        type="submit"
                        disabled={loading}
                      >
                        {loading ? (
                          <CircularProgress size={24} />
                        ) : (
                          "Submit"
                        )}
                      </Button>
                    </Grid>
                  </Grid>
                </Card>
              </Grid>
            </Grid>
          </form>
        </Grid>
      </Grid>
    </div>
  );
};

export default CategoryForm;
