import { useOrganizations } from "@/super-admin/hooks/useOrganizations";
import { OrganizationPayload } from "@/shared/services/organizationsService";

import { useEffect, useState } from "react";
import { OrganizationDto } from "@/shared/dto/organization/organizationDto";
import OrganizationForm, { FormValues } from "./common/OrganizationForm";

interface EditOrganizationFormProps {
  id: string;
}

export const EditOrganizationForm: React.FC<EditOrganizationFormProps> = ({
  id,
}) => {
  const [organizationDetails, setOrganizationDetails] =
    useState<OrganizationDto>();
  const { editOrganization, isEditing, getOrganizationByDetails } =
    useOrganizations("Org");

  const fetchOrganizationDetails = () => {
    getOrganizationByDetails(id, {
      onSuccess: (organization: OrganizationDto) => {
        setOrganizationDetails(organization);
      },
    });
  };

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

  const onSubmit = (values: FormValues) => {
    const requestData: OrganizationPayload = {
      key: values.key,
      name: values.name,
      organizationTypeId: values.organizationTypeId,
      isGovernmentOrganization: values.isGovernmentOrganization,
    };
    if (values.parentId && values.parentId !== "") {
      requestData["parentId"] = values.parentId;
    }
    editOrganization({ id, payload: requestData });
  };

  return (
    <OrganizationForm
      isLoading={isEditing}
      onSubmit={(values: FormValues) => onSubmit(values)}
      type="Edit"
      organizationDetails={organizationDetails}
    />
  );
};
