"use client";
import {
  roleFormInitialValues,
  type RoleFormValues,
} from "./roleFormInitialValues";
import { Form, Formik, FormikHelpers } from "formik";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import * as Yup from "yup";
import ModalInput from "@/components/ui/ModalInput";
import ModalTextarea from "@/components/ui/ModalTextarea";
import { Button } from "@/components/ui/Button";
import Loader from "@/components/ui/Loader";
import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import {
  getRolesOfOpportunity,
  createVolunteerOpportunityRole,
  getVolunteerOpportunityRoleById,
  updateVolunteerOpportunityRole,
} from "@/features/opportunities/services/roles";
import { getAllPages } from "@/features/opportunities/services/payments";
import { getOpportunityById } from "@/features/opportunities/services/opportunities";
import { ROLE_FIELD_ALIASES, ROLE_FORM_FIELDS, volunteerRoleRequestBody } from "./roleRequestBody";
import { YupRequiredString, YupStringMaxLength } from "@/features/shared/schemas";
import { useLanguageStore } from "@/store/languageStore";
import { splitFormApiErrors } from "@/features/shared/splitFormApiErrors";

interface CreateRoleModalProps {
  oppurtunityId: string;
  /** The role's integer id when editing; null/absent when adding. */
  roleId?: number | null;
  setOpenForm: () => void;
  refetch: () => void;
  dropdownRefetch?: () => void;
  participantsStillNeeded?: number;
}

export default function CreateVolunteerRoleModal({
  setOpenForm,
  oppurtunityId,
  refetch,
  dropdownRefetch,
  roleId,
  participantsStillNeeded = 0,
}: CreateRoleModalProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const createRoleMutation = useMutation({
    mutationFn: createVolunteerOpportunityRole,
  });
  const updateRoleMutation = useMutation({
    mutationFn: updateVolunteerOpportunityRole,
  });

  const { data: roleData, isLoading: roleLoading, error: roleError, refetch: refetchRole } = useQuery({
    queryKey: ["volunteer-opportunity-role", roleId],
    queryFn: () => getVolunteerOpportunityRoleById(String(roleId)),
    enabled: Boolean(roleId),
  });
  const limits = useQuery({
    queryKey: ["role-capacity", oppurtunityId, roleId],
    queryFn: async () => {
      const [roles, opportunity] = await Promise.all([
        getAllPages((params) => getRolesOfOpportunity({ ...params, opportunity_id: oppurtunityId })),
        getOpportunityById(oppurtunityId),
      ]);
      const others = roles.filter(role => role.id !== roleId).reduce((sum, role) => sum + Number(role.participants_needed ?? 0), 0);
      return Math.max(0, Number(opportunity.data?.participants_needed ?? 0) - others);
    },
  });
  const initialValues = roleFormInitialValues({
    savedRole: roleData?.data,
    isEditing: Boolean(roleId),
    language: selectedLanguage,
    participantsStillNeeded,
  });

  const validationSchema = Yup.object({
    role_name: YupStringMaxLength(100).concat(YupRequiredString),
    instructions: Yup.string().concat(YupRequiredString),
    participants_needed: Yup.number().typeError(t("COMMON.REQUIRED.FIELD")).required(t("COMMON.REQUIRED.FIELD")).integer()
      .min(Math.max(1, Number(roleData?.data?.assigned_count ?? 0)), t("COMMON.ROLE_CAPACITY_ASSIGNED"))
      .max(limits.data ?? 0, t("COMMON.ROLE_CAPACITY_TOTAL")),
  });

  const handleSubmit = async (
    values: RoleFormValues,
    { resetForm, setFieldError }: FormikHelpers<RoleFormValues>
  ) => {
    try {
      /* See `volunteerRoleRequestBody` for why the body is built per
         language rather than with computed keys. */
      const payload = volunteerRoleRequestBody({
        roleName: values.role_name,
        instructions: values.instructions,
        participantsNeeded: values.participants_needed,
        opportunityId: oppurtunityId,
        language: selectedLanguage,
        savedRole: roleData?.data,
      });

      if (roleId) {
        /* `String(...)`: the id travels in the URL path. */
        await updateRoleMutation.mutateAsync({ id: String(roleId), data: payload });
        toast.success(t("COMMON.TOAST.UPDATE_OPPURTUNITY_ROLE_SUCCESS"));
      } else {
        await createRoleMutation.mutateAsync(payload);
        toast.success(t("COMMON.TOAST.CREATE_OPPURTUNITY_ROLE_SUCCESS"));
      }

      resetForm();
      setOpenForm();
      refetch();
      dropdownRefetch?.();
    } catch (err) {
      // PDF p.37: a field's error sits by the field (e.g. the capacity refusal
      // on `participants_needed`); only what no field can carry is toasted.
      const { mapped, rest } = splitFormApiErrors(err, selectedLanguage, ROLE_FORM_FIELDS, setFieldError, ROLE_FIELD_ALIASES);
      (rest.length > 0 ? rest : mapped > 0 ? [] : [t("COMMON.TOAST.CREATE_OPPURTUNITY_ROLE_FAILED")]).forEach(
        (message) => toast.error(message)
      );
    }
  };

  const submitLoading =
    createRoleMutation.isPending || updateRoleMutation.isPending;
  if (roleLoading || limits.isLoading) return <Loader />;
  if (roleError || limits.isError) return <QueryErrorNotice error={roleError ?? limits.error} onRetry={() => { if (roleError) void refetchRole(); if (limits.isError) void limits.refetch(); }} />;

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
      enableReinitialize
    >
      {({ dirty }) => (
        <div className="md:w-[100%] rounded-lg bg-white filtermodal">
          <Form>
            <div className="grid grid-cols-2 xss:grid-cols-1 xss:gap-0 md:grid-cols-2 gap-6 relative selectfiled">
              <div>
                <p className="text-secondary-100 2xl:text-[25px] lg:text-lg md:text-lg xss:text-sm font-semibold pb-2 mobilescreen:pb-2">
                  {t("VOLUNTEER.ENTER_ROLE")}
                </p>
                <ModalInput
                  name="role_name"
                  type="text"
                  placeholder={t("VOLUNTEER.ENTER_ROLE")}
                />
              </div>
              <div className="lg:w-1/3 md:w-1/2 xss:w-full">
                <p className="text-secondary-100 2xl:text-[25px] lg:text-lg md:text-lg xss:text-sm font-semibold pb-2 mobilescreen:pb-2">
                  {t("VOLUNTEER.NEEDED")}
                </p>
                <ModalInput
                  name="participants_needed"
                  type="text"
                  placeholder={t("COMMON.ENTER.NUMBER")}
                />
              </div>
            </div>
            <div>
              <p className="text-secondary-100 2xl:text-[25px] lg:text-lg md:text-lg xss:text-sm font-semibold pb-2 mobilescreen:pb-2">
                {t("VOLUNTEER.ENTER_INSTRUCTION")}
              </p>
              <ModalTextarea
                name="instructions"
                placeholder={t("VOLUNTEER.ENTER_INSTRUCTION")}
                className="ModalTextareaclr"
              />
            </div>
            <div className="flex xss:flex-col justify-center w-full gap-5 pt-4">
              <Button
                variant="primary"
                type="submit"
                size="medium"
                disabled={submitLoading || limits.isError || (!!roleId && !dirty)}
                className="xss:!w-full"
              >
                {t("COMMON.SAVE")}
              </Button>
              <Button
                variant="secondary"
                size="medium"
                type="button"
                className="xss:!w-full"
                disabled={submitLoading}
                onClick={() => setOpenForm()}
              >
                {t("COMMON.CANCEL")}
              </Button>
            </div>
          </Form>
        </div>
      )}
    </Formik>
  );
}
