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

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 [selectedCategories, setSelectedCategories] = useState<Expense[]>([]); 
  const [groupedCategoryIds, setGroupedCategoryIds] = useState<number[]>([]);


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

  try {
      const payload = {
        group_name: values.group_name,
        // send selected categories as an array of IDs
        category_ids: selectedCategories.map((cat) => cat.id),
      };

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

    showMessage("Group saved successfully!");
    navigate(`/expense/list/${projectId}`);
    formik.resetForm();
    setSelectedCategories([]); // reset selected categories
    setSelectedCategoryId(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.group_name) {
      showErrorMessage(errorMessages.group_name[0]); // show first error
    } else {
      showErrorMessage("An error occurred while saving the group.");
    }
  } else {
    showErrorMessage("An error occurred while saving the group.");
  }


  } 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 fetchGroups = async () => {
  try {
    const res = await axios.get(`${API_URL}/view-expense-group/${projectId}`);

    const groupedIds = res.data.flatMap((g:any) => g.category_ids);

    setGroupedCategoryIds(groupedIds);

  } catch (error) {
    console.error("Failed to load groups", error);
  }
};

useEffect(() => {
  fetchGroups();
}, []);


  const handleAdd = () => {
    // Move selected items from left (available) to right (selected)
    const selectedToAdd = categoryList.filter(
      (cat) => !selectedCategories.find((sel) => sel.id === cat.id)
    );
    setSelectedCategories([...selectedCategories, ...selectedToAdd]);
  };

  const handleRemove = () => {
    // Remove all selected items
    setSelectedCategories([]);
  };

  // Available categories (not yet selected)

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}>
                  Create 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 }}>
                    {/* Category Name Field */}

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