"use client";

import { useEffect, useState } from "react";
import { Form, Formik } from "formik";
import { useRouter } from "next/navigation";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import * as Yup from "yup";

import Input from "@/components/ui/Input";
import SelectInput from "@/components/ui/SelectInput";
import { registerForVolunteerOpportunity } from "@/features/opportunities/services/registrations";
import { registerWithConflictCheck } from "@/features/opportunities/scheduleConflict";
import { getApiErrorMessage, isApiSuccess, isBanRefusal } from "@/lib/api/errors";
import { NAV_STATE_KEYS, setNavState } from "@/lib/navigationState";
import { useLanguageStore } from "@/store/languageStore";
import { UNASSIGNED_ROLE_VALUE } from "../roleCapacity";
import { useOpportunityRolePicker } from "./useOpportunityRolePicker";

export const VOLUNTEER_ROLE_REGISTRATION_FORM_ID =
  "volunteer-role-registration-form";

export interface OpportunityRegistrationDetails {
  title_ar?: string;
  title_en?: string;
  start_date?: string;
  daily_hours?: number | string | null;
  /** The opportunity's own WhatsApp contact, for the «تم تسجيلك» page. */
  whatsapp_link?: string | null;
}

interface VolunteerRegisterRoleModalProps {
  opportunityId: string;
  organizationId?: string;
  onLoadingChange: (isLoading: boolean) => void;
  onClose: () => void;
  opportunityDetails: OpportunityRegistrationDetails;
}

interface RoleOption {
  label: string;
  value: string;
  remaining_slots?: number;
  instructions?: string;
}

export default function VolunteerRegisterRoleModal({
  opportunityId,
  organizationId,
  onLoadingChange,
  onClose,
  opportunityDetails,
}: VolunteerRegisterRoleModalProps) {
  const { t } = useTranslation();
  const router = useRouter();
  const queryClient = useQueryClient();
  const selectedLanguage = useLanguageStore((s) => s.language);

  const [selectedRole, setSelectedRole] = useState<RoleOption | null>(null);

  const registerMutation = useMutation({
    mutationFn: registerForVolunteerOpportunity,
  });

  const { roleOptions, rolesLoading, handleMenuScroll } =
    useOpportunityRolePicker({ opportunityId, selectedLanguage });

  useEffect(() => {
    onLoadingChange?.(registerMutation.isPending);
  }, [registerMutation.isPending, onLoadingChange]);

  const validationSchema = Yup.object().shape({
    role: Yup.string().required(t("COMMON.REQUIRED.FIELD")),
  });

  const handleSubmit = async (values: { role: string }) => {
    try {
      const response = await registerWithConflictCheck((extra) =>
        registerMutation.mutateAsync({
          ...(organizationId ? { organization_id: organizationId } : {}),
          opportunity_id: opportunityId,
          ...(values.role === UNASSIGNED_ROLE_VALUE ? {} : { role_id: values.role }),
          ...extra,
        })
      );
      // Kept the registration that clashes: nothing to register.
      if (response === null) {
        onClose();
        return;
      }

      // The API also rejects with HTTP 200 + `key: "fail"`, so the envelope —
      // not the status — decides, and its `msg` is the reason to show
      // ("this opportunity is for a different age group", …).
      if (!isApiSuccess(response)) {
        toast.error(
          getApiErrorMessage(
            response,
            selectedLanguage,
            t("COMMON.TOAST.REGISTRATION_FAILED"),
          ),
        );
        return;
      }

      // A16: free registration sends no email — «تم تسجيلك بنجاح» only.
      toast.success(t("COMMON.YOU_ARE_REGISTERED"));
      // The detail is cached per viewer; without this, coming back within the
      // stale time still offered «تسجيل» to someone already registered.
      void queryClient.invalidateQueries({ queryKey: ["volunteer-opportunity", opportunityId] });
      setNavState(NAV_STATE_KEYS.opportunityThankyou, opportunityDetails);
      router.push("/register-now");
      onClose();
    } catch (error) {
      // The ban popup already explains the refusal (PDF p.43).
      if (isBanRefusal(error)) {
        onClose();
        return;
      }
      toast.error(
        getApiErrorMessage(
          error,
          selectedLanguage,
          t("COMMON.TOAST.REGISTRATION_FAILED"),
        ),
      );
    }
  };

  return (
    <Formik
      initialValues={{ role: "" }}
      validationSchema={validationSchema}
      onSubmit={handleSubmit}
    >
      {({ setFieldValue }) => (
        <div className="md:w-[100%] rounded-lg bg-white pb-[20px] filtermodal">
          <Form id={VOLUNTEER_ROLE_REGISTRATION_FORM_ID}>
            <div className="flex mobilescreen:flex-col gap-[50px] mobilescreen:gap-[0px] relative">
              <div className="w-1/3 mobilescreen:w-full">
                <p className="text-secondary-100 2xl:text-[25px] lg:text-lg md:text-lg xss:text-sm font-semibold pb-3 mobilescreen:pb-1">
                  {t("COMMON.CHOOSE.YOUR.ROLE")}
                </p>
                <div className="space-y-0 flex gap-4 items-center xsmall:flex-col selectfiled">
                  <SelectInput
                    name="role"
                    label={t("COMMON.SELECT.ROLE")}
                    options={roleOptions}
                    onMenuScrollToBottom={handleMenuScroll}
                    disabled={rolesLoading}
                    onChange={(option) => {
                      setFieldValue("role", option?.value || "");
                      setSelectedRole((option as RoleOption | null) ?? null);
                    }}
                  />
                </div>
              </div>

              <div className="selectfiled w-1/4 mobilescreen:w-full">
                <p className="text-secondary-100 2xl:text-[25px] lg:text-lg md:text-lg xss:text-sm font-semibold pb-3 mobilescreen:pb-1">
                  {t("COMMON.REMAINING")}
                </p>
                <Input
                  name="remaining"
                  type="text"
                  placeholder=""
                  readOnly
                  value={selectedRole?.remaining_slots || 0}
                />
              </div>
            </div>
            {selectedRole?.instructions && (
              <div>
                <p className="text-secondary-100 2xl:text-[25px] lg:text-lg md:text-lg xss:text-sm font-semibold pb-2 mobilescreen:pb-0">
                  {t("COMMON.INSTRUCTION")}
                </p>
                <p className="text-[#181822CC]/80 text-lg">
                  {selectedRole.instructions}
                </p>
              </div>
            )}
          </Form>
        </div>
      )}
    </Formik>
  );
}
