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 { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
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 Typography from "@mui/material/Typography";
import LoadingButton from "@mui/lab/LoadingButton";
import { Controller } from "react-hook-form";
import { paths } from "@/routes/paths";
import { useRouter, useResponsive, useBoolean } from "@/hooks";
import { useSnackbar } from "@/components/snackbar";
import FormProvider, {
  RHFEditor,
  RHFSelect,
  RHFTextField,
} from "@/shared/components/hook-form";
import {
  IProjectItem,
  Participants,
  Project,
  collaborator,
} from "@/contexts/types/Project";
import LocalizationProvider from "@/shared/locales/localization-provider";
import { DatePicker } from "@mui/x-date-pickers";
import Avatar from "@mui/material/Avatar";
import RHFAutocomplete from "@/shared/components/hook-form/rhf-autocomplete";
import { _Participants } from "@/shared/_mock";
import {
  Button,
  Divider,
  InputAdornment,
  MenuItem,
  Tooltip,
} from "@mui/material";
import AutoFixNormalIcon from "@mui/icons-material/AutoFixNormal";
import RHFRadioGroup from "@/shared/components/hook-form/rhf-radio-group";
import { IconButton } from "yet-another-react-lightbox";
import { button } from "@/components/button";
import Iconify from "@/shared/components/iconify";
import RouterLink from "@/routes/router-link";

import AIDialog from "./dialog-chat-AI";
import ConditionalComponent from "@/shared/components/ConditionalComponent/ConditionalComponent";
import {
  createProject,
  updateProject,
  useGetCollaborators,
  useGetProjects,
} from "@/shared/api/project";
import { AxiosResponse } from "axios";
import { axiosInstance } from "@/utils/axios";
// ----------------------------------------------------------------------

type Props = {
  currentProject?: Project;
};

type FormValuesType = {
  name: string;
  description?: string;
  startDate?: Date;
  endDate?: Date | null;
  status?: string;
  type: string;
  collaboratorsIds?: collaborator[];
  responsibleId: number;
};

export default function ProjectNewEditForm({ currentProject }: Props) {
  const router = useRouter();
  const mdUp = useResponsive("up", "md");
  const { enqueueSnackbar } = useSnackbar();
  const share = useBoolean();
  const [collaboratorData, setCollaboratorData] = useState<collaborator[]>([]);
  const [managerData, setManagerData] = useState<collaborator[]>([]);
  const { projects } = useGetProjects();
  const agencyId = useMemo(() => localStorage.getItem("selectedAgency"), []);

  const [tableData, setTableData] = useState<Project[]>(projects);
  useEffect(() => {
    if (projects.length) {
      setTableData(projects);
    }
  }, [projects]);

  const NewProjectSchema = Yup.object().shape({
    name: Yup.string().required("Title is required"),
    description: Yup.string(),
    startDate: Yup.date(),
    endDate: Yup.date().nullable(),
    type: Yup.string().required("Type is required"),
    status: Yup.string(),
    collaboratorsIds: Yup.array(),
    responsibleId: Yup.number().required("Responsible ID is required"),
  });

  const defaultValues = useMemo(
    () => {
      const startDate = currentProject?.startDate
        ? new Date(currentProject.startDate)
        : new Date();
      
      const defaultEndDate = currentProject?.endDate
        ? new Date(currentProject.endDate)
        : new Date(startDate.getTime());
      defaultEndDate.setMonth(defaultEndDate.getMonth() + 3);  // Add 3 months to the start date

      return {
        name: currentProject?.name || "",
        description: currentProject?.description || "",
        startDate: startDate,
        endDate: defaultEndDate,
        status: currentProject?.status || "PENDING",
        type: currentProject?.type || "INTERNAL",
        collaboratorsIds:
          collaboratorData.filter((participant) =>
            currentProject?.collaboratorsIds?.includes(participant.id)
          ) || [],
        responsibleId: Number(currentProject?.responsibleId) || 0,
      };
    },
    [currentProject, collaboratorData]
  );

  const methods = useForm({
    resolver: yupResolver(NewProjectSchema),
    defaultValues,
  });

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

  const values = watch();

  useEffect(() => {
    if (currentProject) {
      reset(defaultValues);
    }
  }, [currentProject, defaultValues, reset]);

  const getCollaborators = async () => {
    try {
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/${agencyId}/collaborators`
      );
      setCollaboratorData(response.data);
    } catch (error) {
      console.error("Failed to fetch collaborators:", error);
    }
  };

  const getManagers = async () => {
    try {
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/${agencyId}/managers`
      );
      setManagerData(response.data);
    } catch (error) {
      console.error("Failed to fetch managers:", error);
    }
  };
  useEffect(() => {
    if (agencyId) {
      getCollaborators();
      getManagers();
    }
  }, [agencyId]);

  const onSubmit = async (data: FormValuesType) => {
    try {
      const payload = {
        ...data,
        agencyId: Number(agencyId),
        collaboratorsIds: data.collaboratorsIds?.map((collaborator) => collaborator.id) ?? [],
      };

      if (currentProject) {
        await updateProject(currentProject.id, payload);
      } else {
        await createProject(payload);
      }
      reset();
      enqueueSnackbar(currentProject ? "Update success!" : "Create success!");
      router.push(paths.dashboard.projects.recent);
    } catch (error) {
      enqueueSnackbar(
        currentProject ? "Failed to update project!" : "Failed to create project!",
        { variant: "error" }
      );
    }
  };

  const handleDescriptionGenerated = (description: string) => {
    setValue('description', description);
  };

  const renderDetails = (
    <Grid xs={12} md={12}>
      <Card>
        <CardHeader title="Details" sx={{ mb: 2 }} />
        <Divider sx={{ borderStyle: "dashed" }} />
        <Stack spacing={3} sx={{ p: 3 }}>
          <RHFTextField name="name" label="Project Name" />
          <RHFEditor 
            name="description" 
            placeholder="Description ..."
            sx={{
              '& .ql-editor': {
                minHeight: 200,
              },
              '& .ql-editor img': {
                cursor: 'pointer',
                '&:hover': {
                  boxShadow: '0 0 0 2px #B4D5FF'
                }
              }
            }}
            modules={{
              toolbar: [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'align': [] }],
                ['link', 'image'],
                ['clean']
              ],
              clipboard: {
                matchVisual: false
              }
            }}
          />
          <Tooltip title="Use Stunar AI to generate your description">
            <Iconify
              icon="fluent-emoji:magic-wand"
              onClick={share.onTrue}
              sx={{
                width: 27,
                height: 27,
                color: "grey",
                bottom: 10,
                right: 4,
                ml: 1,
                cursor: 'pointer'
              }}
            />
          </Tooltip>
          <Controller
            name="startDate"
            control={control}
            render={({ field, fieldState: { error } }) => (
              <DatePicker
                label="Start Date"
                value={field.value}
                onChange={(newValue) => field.onChange(newValue)}
                slotProps={{
                  textField: {
                    fullWidth: true,
                    error: !!error,
                    helperText: error?.message,
                  },
                }}
              />
            )}
          />
          <Controller
            name="endDate"
            control={control}
            render={({ field, fieldState: { error } }) => (
              <DatePicker
                label="End Date"
                value={field.value}
                onChange={(newValue) => field.onChange(newValue)}
                slotProps={{
                  textField: {
                    fullWidth: true,
                    error: !!error,
                    helperText: error?.message,
                  },
                }}
              />
            )}
          />
         <ConditionalComponent
  isValid={!!currentProject}
>
  <RHFSelect
    name="status"
    label="Project Status"
    sx={{ mb: 2 }}
  >
    <MenuItem value="PENDING">PENDING</MenuItem>
    <MenuItem value="IN_PROGRESS">IN PROGRESS</MenuItem>
    <MenuItem value="COMPLETED">COMPLETED</MenuItem>
  </RHFSelect>
</ConditionalComponent>
          <RHFAutocomplete
            multiple
            name="collaboratorsIds"
            placeholder="+ Participants"
            disableCloseOnSelect
            options={collaboratorData}
            value={values.collaboratorsIds}
            onChange={(event, newValue) =>
              setValue("collaboratorsIds", newValue)
            }
            getOptionLabel={(option) => {
              if (
                typeof option !== "string" &&
                option.user?.firstName &&
                option.user?.lastName
              ) {
                return `${option.user.firstName} ${option.user.lastName}`;
              }
              return "Unknown Collaborator";
            }}
            isOptionEqualToValue={(option, value) => {
              // Type guard to ensure value is an object with an id property
              return (
                typeof value === "object" &&
                "id" in value &&
                option.id === value.id
              );
            }}
            renderTags={(selected, getTagProps) =>
              selected.map((participant, index) => (
                <Chip
                  {...getTagProps({ index })}
                  key={participant.id}
                  size="small"
                  variant="soft"
                  label={
                    participant.user?.firstName && participant.user?.lastName
                      ? `${participant.user.firstName} ${participant.user.lastName}`
                      : "Unknown Collaborator"
                  }
                />
              ))
            }
          />

          <RHFAutocomplete
            name="responsibleId"
            placeholder="Select Responsible (Manager)"
            options={managerData || []}
            getOptionLabel={(option) => {
              if (
                typeof option !== "string" &&
                "user" in option &&
                option.user?.firstName &&
                option.user?.lastName
              ) {
                return `${option.user.firstName} ${option.user.lastName}`;
              }
              return "Unknown Manager";
            }}
            isOptionEqualToValue={(option, value) => {
              return (
                typeof value === "object" &&
                "id" in value &&
                option.id === value.id
              );
            }}
            onChange={(event, newValue) =>
              setValue(
                "responsibleId",
                typeof newValue === "object" &&
                  newValue !== null &&
                  "id" in newValue
                  ? newValue.id
                  : 0
              )
            }
            value={
              (managerData || []).find(
                (manager) => manager?.id === values?.responsibleId
              ) || null
            }
          />

          <Stack spacing={2}>
            <RHFRadioGroup
              row
              spacing={4}
              name="type"
              label="Type Project"
              options={[
                { value: "INTERNAL", label: "INTERNAL" },
                { value: "EXTERNAL", label: "EXTERNAL" },
              ]}
            />
          </Stack>
        </Stack>
        <Divider sx={{ borderStyle: "solid" }} />
        <Grid container justifyContent="flex-end" sx={{ p: 2 }}>
          <LoadingButton
            type="submit"
            variant="contained"
            size="small"
            loading={isSubmitting}
          >
            {currentProject ? "Save Changes" : "Create Project"}
          </LoadingButton>
        </Grid>
      </Card>
    </Grid>
  );

  return (
    <LocalizationProvider>
      <FormProvider methods={methods} onSubmit={methods.handleSubmit(onSubmit)}>
        <Grid container spacing={3} sx={{ justifyContent: "center" }}>
          <Grid xs={12} md={8}>
            {renderDetails}
          </Grid>
        </Grid>
      </FormProvider>
      <AIDialog 
        open={share.value} 
        onClose={share.onFalse}
        onDescriptionGenerated={handleDescriptionGenerated}
        systemPrompt="You are a helpful assistant that generates project descriptions in 3-5 concise lines. Focus on the main features and benefits without using titles or sections. Keep it natural and engaging."
        type="project"
      />
    </LocalizationProvider>
  );
}
