import React, { useState, useEffect } from "react";
import { Grid, Card, Typography, TextField, Button, Box, MenuItem, FormControlLabel,
  Checkbox, List, ListItem, ListItemText, Paper, IconButton } 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";
import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
import ReplayIcon from "@mui/icons-material/Replay";

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 [group_name, setGroup_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[]>([]);
  const [groupedCategoryIds, setGroupedCategoryIds] = useState<number[]>([]);
  const [selectedCategories, setSelectedCategories] = useState<Expense[]>([]);
  const [selectedGroup, setSelectedGroup] = useState<any>(null);
   
  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);
        }
      };
       const fetchGroup = async () => {
  try {
    const res = await axios.get(`${API_URL}/expense-group/${id}`);
    if (res.data) {
      const group = res.data;
     group.category_ids =
  typeof group.category_ids === "string"
    ? JSON.parse(group.category_ids)
    : Array.isArray(group.category_ids)
    ? group.category_ids
    : [];
      setSelectedGroup(group);
      setGroup_name(group.group_name);
      // Pre-select categories
      const preSelected = categoryList.filter(cat => group.category_ids.includes(cat.id));
      setSelectedCategories(preSelected);

        formik.setValues({
          group_name: group.group_name,
          
        });
    }
  } catch (error) {
    console.error("Failed to load group", error);
  }
};
    
      fetchExpenses();
      fetchGroup();
    }, [API_URL]);

   

// useEffect(() => {
//   if (categoryList.length) fetchGroup();
// }, [categoryList]);

useEffect(() => {
  if (selectedGroup && categoryList.length) {
    const preSelected = categoryList.filter(cat =>
      selectedGroup.category_ids.includes(cat.id)
    );
    setSelectedCategories(preSelected);
  }
}, [selectedGroup, categoryList]);
 
  const formik = useFormik({
    initialValues: {
      group_name: selectedGroup?.group_name || "",
     
    },
    validationSchema: yup.object({
      group_name: yup.string().required("Group name is required"),
    }),
    
    
    onSubmit: async (values) => { 
      setLoading(true);
      try {
      const payload = {
        group_name: values.group_name,
        projectId: projectId,
        category_ids: selectedCategories.map(cat => cat.id),
      };


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

        showMessage("Expense Group 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 group.");
      } finally {
        setLoading(false);
      }
    },
  });
  

 

    
const availableCategories = categoryList
 // .filter(cat => !groupedCategoryIds.includes(cat.id))
  .filter(cat => !selectedCategories.some(sel => sel.id === cat.id));
  

  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 Group</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}>
                                   <Typography variant="subtitle1">Name</Typography>
                                   <TextField
                                     placeholder="Enter Group name"
                                     size="small"
                                     {...formik.getFieldProps("group_name")}
                                     error={
                                       formik.touched.group_name &&
                                       Boolean(formik.errors.group_name)
                                     }
                                    //  helperText={
                                    //    formik.touched.group_name &&
                                    //    formik.errors.group_name
                                    //  }
                                     helperText={
    formik.touched.group_name && typeof formik.errors.group_name === "string"
      ? formik.errors.group_name
      : "" }
                                     fullWidth
                                   />
                                 </Grid>

                 {/* CATEGORY SELECTOR */}
            <Grid item xs={12}>
              <Grid container spacing={3} alignItems="center">

                {/* Available Categories */}
                <Grid item xs={12} md={5}>
                  <Typography variant="subtitle1" sx={{ mb: 1 }}>
                    Available Categories
                  </Typography>

                  <Paper
                    elevation={1}
                    sx={{
                      height: 300,
                      overflow: "auto",
                      p: 1
                    }}
                  >
                    <List dense>
                      {availableCategories.map((cat) => (
                        <ListItem
                          key={cat.id}
                        divider
                          secondaryAction={
                            <Button
                              variant="outlined"
                              size="small"
                             
                              onClick={() =>
                                setSelectedCategories([
                                  ...selectedCategories,
                                  cat,
                                ])
                              }
                                sx={{
    minWidth: 40,
    fontSize: "0.75rem",
    px: 0.8,
    py: 0.2
  }}
                            >
                              Add
                            </Button>
                          }
                        >
                          <ListItemText primary={cat.category_name} />
                        </ListItem>
                      ))}
                    </List>
                  </Paper>
                </Grid>

                {/* Spacer Arrow */}
                <Grid
                  item
                  xs={12}
                  md={2}
                  sx={{
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                  }}
                >
                  <Typography variant="h6">
                    <ArrowForwardIcon sx={{ fontSize: 30, color: "#666" }} />
                  </Typography>
                </Grid>

                {/* Selected Categories */}
                <Grid item xs={12} md={5}>
                  <Typography variant="subtitle1" sx={{ mb: 1 }}>
                    Selected Categories
                  </Typography>

                  <Paper
                    elevation={1}
                    sx={{
                      height: 300,
                      overflow: "auto",
                      p: 1
                    }}
                  >
                    <List dense>
                      {selectedCategories.map((cat) => (
                        <ListItem
                          key={cat.id}
                           divider
                          secondaryAction={
                            <IconButton
                              
                              color="error"
                              size="small"
                              onClick={() =>
                                setSelectedCategories(
                                  selectedCategories.filter(
                                    (c) => c.id !== cat.id
                                  )
                                )
                              }
                               sx={{
      backgroundColor: '#f8d7da',
      borderRadius: '50%',
      padding: '4px',
      '&:hover': {
        backgroundColor: '#f1b0b7',
      },
    }}
                            >
                              <ReplayIcon fontSize="small" />
                            </IconButton>
                          }
                        >
                          <ListItemText primary={cat.category_name} />
                        </ListItem>
                      ))}
                    </List>
                  </Paper>
                </Grid>

              </Grid>
            </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={() => 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;
