import React, { useState, useEffect } from "react";
import { Grid, Card, Typography, TextField, Button, Box, MenuItem, FormControlLabel, Checkbox } 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 axios from "axios";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { useNotifier } from "../../../Core/Notifier";
import CircularProgress from "@mui/material/CircularProgress";

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

const EditExpenseForm = () => {
  const { id } = useParams(); // Get the expense ID from the URL
  const navigate = useNavigate();
  const API_URL = process.env.REACT_APP_API_URL;
  const classes = useStyles();
    const location = useLocation();
  const projectId = location.state?.projectId;
  const [isHST, setIsHST] = useState(false);
  const [total, setTotal] = useState(0);
  const [hstAmount, setHstAmount] = useState(0);
  const { showErrorMessage, showMessage } = useNotifier();
  const [loading, setLoading] = useState(false); 
  const [expense, setExpense] = useState<any>(null); // State to store fetched expense data
  const [category_name, setCategory_name] = useState('');
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);
  const [selectedSubCategoryId, setSelectedSubCategoryId] = useState<number | null>(null);
  const [categoryList, setCategoryList] = useState<Expense[]>([]); 
 const [subCategories, setSubCategories] = useState<Expense[]>([]);

  
   useEffect(() => {
      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);
        }
      };
      fetchExpenses();
    }, [API_URL]);
 
  const formik = useFormik({
    initialValues: {
      category_name: expense?.category_name || "",
      mainCatId: expense?.mainCatId || null,
     
    },
    validationSchema: yup.object({
      category_name: yup.string().required("Category name is required"),
    }),
    
    onSubmit: async (values) => { 
      setLoading(true);
      try {
        const formData = new FormData();
      
        formData.append("category_name", values.category_name);
        formData.append("projectId", projectId);

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

        showMessage("Expense Category updated successfully!");
        navigate(`/expense/list/${projectId}`); 
        //  formik.resetForm();
        // navigate(`/expense-category/list`); // Redirect after update
      } catch (error) {
        showErrorMessage("An error occurred while updating the expense category.");
      } finally {
        setLoading(false);
      }
    },
  });
  

  useEffect(() => {
    // Fetch expense details based on ID
    const fetchExpenseData = async () => {
      setLoading(true);
      try {
        const response = await axios.get(`${API_URL}/expense-category/${id}`);
        const fetchedExpense = response.data; // Populate the form with fetched data
        setExpense(fetchedExpense);
         setSelectedCategoryId(fetchedExpense.mainCatId);
        setCategory_name(fetchedExpense.category_name);
      
  
        // Set formik values manually if expense is loaded
        formik.setValues({
          category_name: fetchedExpense.category_name,
          mainCatId: fetchedExpense.mainCatId,
          
        });
        
      } catch (error) {
        showErrorMessage("Failed to fetch expense category data.");
      } finally {
        setLoading(false);
      }
    };
  
    if (id) {
      fetchExpenseData();
    }
  }, []);

  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}>Edit 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 }}>


              <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>
)}


            
                    {/* Date Field */}
                    <Grid item xs={7}>
                      <Typography variant="subtitle1">Category Name</Typography>
                      <TextField
                        placeholder="Enter category name"
                        size="small"
                        {...formik.getFieldProps("category_name")}
                      
                        fullWidth
                      />
                    </Grid>
                    {/* Description Field */}
                   
                  </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={() => formik.resetForm()}
                        onClick={() =>navigate(`/expense/list/${projectId}`)}
                      >
                        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 EditExpenseForm;
