"use client";

import * as Yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useMemo, useEffect, useState } from "react";
import Chip from "@mui/material/Chip";
import Card from "@mui/material/Card";
import Stack from "@mui/material/Stack";
import Grid from "@mui/material/Unstable_Grid2";
import CardHeader from "@mui/material/CardHeader";
import LoadingButton from "@mui/lab/LoadingButton";
import { Controller } from "react-hook-form";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { paths } from "@/routes/paths";
import { useRouter, useResponsive } from "@/hooks";
import { useSnackbar } from "@/components/snackbar";
import FormProvider, {
  RHFEditor,
  RHFTextField,
} from "@/shared/components/hook-form";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { DatePicker } from "@mui/x-date-pickers";
import Avatar from "@mui/material/Avatar";
import RHFAutocomplete from "@/shared/components/hook-form/rhf-autocomplete";
import { Container } from "@mui/material";
import { useSettingsContext } from "@/shared/components/settings";
import CustomBreadcrumbs from "@/components/custom-breadcrumbs";
import axiosInstancee from "@/utils/axios";
import { IGroupeAgency } from "@/shared/types/groupeAgency";

type Props = {
  currentGroup?: IGroupeAgency; // Current group for editing
};

export default function GroupNewEditView({ currentGroup }: Props) {
  const settings = useSettingsContext();
  const router = useRouter();
  const mdUp = useResponsive("up", "md");
  const { enqueueSnackbar } = useSnackbar();
  const date = new Date();

  const [agencyId, setAgencyId] = useState<string | null>(null);
  const [users, setUsers] = useState<any[]>([]);

  // Load Agency ID from localStorage
  useEffect(() => {
    const storedAgencyId = localStorage.getItem("selectedAgency");
    if (!storedAgencyId) {
      enqueueSnackbar("Agency ID is missing. Please select an agency.", {
        variant: "error",
      });
      router.push(paths.dashboard.agency.list);
    } else {
      setAgencyId(storedAgencyId);
    }
  }, [enqueueSnackbar, router]);

  // Fetch Users based on Agency ID
  useEffect(() => {
    if (agencyId) {
      axiosInstancee
        .get(`/api/user/users`, { params: { agencyId } })
        .then((response) => setUsers(response.data))
        .catch((error) => {
          console.error("Error fetching users:", error);
          enqueueSnackbar("Failed to load users.", { variant: "error" });
        });
    }
  }, [agencyId, enqueueSnackbar]);

  // Validation Schema
  const NewGroupSchema = Yup.object().shape({
    name: Yup.string().required("Name is required"),
    description: Yup.string(),
    participants: Yup.array(),
    createDate: Yup.date().required("Create date is required").nullable(),
  });

  // Default Values
  const defaultValues = useMemo(
    () => ({
      name: currentGroup?.name || "",
      description: currentGroup?.description || "",
      createDate: currentGroup?.createDate
        ? new Date(currentGroup.createDate) // Parse string date into Date object
        : null,
      participants: currentGroup?.participants || [],
    }),
    [currentGroup]
  );
  const methods = useForm({
    resolver: yupResolver(NewGroupSchema),
    defaultValues,
  });

  const {
    reset,
    watch,
    control,
    setValue,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  // Reset form when switching between edit and create mode
  useEffect(() => {
    if (currentGroup) {
      reset(defaultValues); // Ensure reset is only triggered when currentGroup changes
    }
  }, [currentGroup, reset]);

  // Handle Form Submission
  const onSubmit = handleSubmit(async (data) => {
    if (!agencyId) {
      enqueueSnackbar(
        "Agency ID is missing. Cannot create or update the group.",
        { variant: "error" }
      );
      return;
    }

    try {
      const payload = {
        name: data.name,
        description: data.description,
        agencyId: agencyId,
        // Format createDate to ISO 8601 (or your desired format)
        createDate: data.createDate
          ? data.createDate.toISOString().split("T")[0]
          : null,
        memberIds: (data.participants || []).map((user: any) => user.id),
      };

      if (currentGroup) {
        // Update existing group
        const response = await axiosInstancee.put(
          `/api/user/groups/${currentGroup.id}`,
          payload,
          {
            params: { agencyId },
          }
        );

        const groupId = response?.data?.id;
        if (groupId) {
          enqueueSnackbar("Group updated successfully!", {
            variant: "success",
          });
          router.push(paths.dashboard.agency.groupe.details(groupId));
        } else {
          throw new Error("Group ID not found in response");
        }
      } else {
        // Create new group
        const response = await axiosInstancee.post(
          `/api/user/groups`,
          payload,
          {
            params: { agencyId },
          }
        );

        const groupId = response?.data?.id;
        if (groupId) {
          enqueueSnackbar("Group created successfully!", {
            variant: "success",
          });
          router.push(paths.dashboard.agency.groupe.details(groupId));
        } else {
          throw new Error("Group ID not found in response");
        }
      }
    } catch (error) {
      console.error("Failed to save group:", error);
      enqueueSnackbar("Failed to save group. Please try again.", {
        variant: "error",
      });
    }
  });

  // Ensure agency ID is loaded
  if (!agencyId) {
    return <p>Loading...</p>;
  }

  return (
    <Container maxWidth={settings.themeStretch ? false : "lg"}>
      <CustomBreadcrumbs
        heading={currentGroup ? "Edit Group" : "New Group"}
        links={[
          { name: "Dashboard", href: paths.dashboard.root },
          { name: "Agency", href: paths.dashboard.agency.list },
          { name: currentGroup ? currentGroup.name : "New Group" },
        ]}
        sx={{ mb: { xs: 3, md: 5 } }}
      />
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <FormProvider methods={methods} onSubmit={onSubmit}>
          <Grid container spacing={3} sx={{ justifyContent: "center" }}>
            <Grid xs={12} md={8}>
              <Card>
                {!mdUp && <CardHeader title="Details" />}
                <Stack spacing={3} sx={{ p: 3 }}>
                  <RHFTextField name="name" label="Group Name" />
                  <RHFEditor
                    simple
                    name="description"
                    placeholder="Description ..."
                  />
                  
                  <RHFAutocomplete
                    multiple
                    name="participants"
                    placeholder="+ members"
                    disableCloseOnSelect
                    options={users}
                    value={values.participants}
                    onChange={(event, newValue) =>
                      setValue("participants", newValue)
                    }
                    getOptionLabel={(option) =>
                      `${option.firstName || ""} ${
                        option.lastName || ""
                      }`.trim() || option.email
                    }
                    isOptionEqualToValue={(option, value) =>
                      option.id === value.id
                    }
                    renderOption={(props, user) => (
                      <li {...props} key={user.id}>
                        <Avatar
                          alt={`${user.firstName} ${user.lastName}`}
                          src={user.picture}
                          sx={{ width: 24, height: 24, mr: 1 }}
                        />
                        <div>
                          <strong>{`${user.firstName} ${user.lastName}`}</strong>
                          <br />
                          <small>{user.email}</small>
                        </div>
                      </li>
                    )}
                    renderTags={(selected, getTagProps) =>
                      selected.map((user, index) => (
                        <Chip
                          {...getTagProps({ index })}
                          key={user.id}
                          size="small"
                          variant="soft"
                          label={`${user.firstName} ${user.lastName}`}
                          avatar={
                            <Avatar
                              alt={`${user.firstName}`}
                              src={user.avatarUrl}
                            />
                          }
                        />
                      ))
                    }
                  />
                </Stack>
              </Card>
            </Grid>
            <Grid xs={12} md={8}>
              <LoadingButton
                type="submit"
                variant="contained"
                size="large"
                loading={isSubmitting}
              >
                {currentGroup ? "Save Changes" : "Create Group"}
              </LoadingButton>
            </Grid>
          </Grid>
        </FormProvider>
      </LocalizationProvider>
    </Container>
  );
}
