"use client";

import { Formik, FormikHelpers } from "formik";
import { useTranslation } from "react-i18next";
import Title from "@/components/shared/Title";
import { HomepageBannerClient } from "@/features/home";
import SponsorshipFormInner from "./SponsorshipFormInner";
import { useLanguageStore } from "@/store/languageStore";
import { useMutation, useQuery } from "@tanstack/react-query";
import { createSponsors } from "@/features/partners/services/partnersApi";
import { getDropdownChoices } from "@/features/shared/services/dropdowns";
import { toast } from "sonner";
import { useRouter } from "next/navigation";

import type { ChoiceItem } from "@/lib/choices";
import {
  buildSponsorshipValidation,
  sponsorshipInitialValues,
} from "./sponsorshipFormSchema";
import { toastApiError } from "@/lib/api/toastApiError";
import { getApiFieldErrors, isApiSuccess } from "@/lib/api/errors";

export interface SponsorshipFormValues {
  org_name: string;
  org_type: string;
  person_name: string;
  email: string;
  phone_number: string;
  country_code: string;
  sponsor_type: string;
  type_of_support: string;
  sponsorship_details: string;
  /** «سبب الاهتمام» — optional. */
  why_interested: string;
  /** «الموارد المتوقعة» — optional. */
  resources_expected: string;
  new_sponsor_documents: File[];
  sponsor_logo: File | null;
}

export default function SponsorshipForm() {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const router = useRouter();

  const sponsorsMutation = useMutation({
    mutationFn: createSponsors,
  });

  const { data: orgTypeData, isLoading: orgTypeLoading } = useQuery({
    queryKey: ["dropdownChoices", "org_type"],
    queryFn: () => getDropdownChoices("org_type"),
    enabled: !!selectedLanguage,
  });

  const { data: sponsorTypeData, isLoading: sponsorTypeLoading } = useQuery({
    queryKey: ["dropdownChoices", "sponsor_type"],
    queryFn: () => getDropdownChoices("sponsor_type"),
    enabled: !!selectedLanguage,
  });

  const { data: supportTypeData, isLoading: supportTypeLoading } = useQuery({
    queryKey: ["dropdownChoices", "type_of_support"],
    queryFn: () => getDropdownChoices("type_of_support"),
    enabled: !!selectedLanguage,
  });

  const orgTypeOptions =
    orgTypeData?.data?.map((item: ChoiceItem) => ({
      label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
      value: String(item.id),
    })) || [];

  const sponsorTypeOptions =
    sponsorTypeData?.data?.map((item: ChoiceItem) => ({
      label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
      value: String(item.id),
      key: item.id,
      value_en: item.value_en,
      value_ar: item.value_ar,
    })) || [];

  const allSupportTypeOptions =
    supportTypeData?.data?.map((item: ChoiceItem) => ({
      label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
      value: String(item.id),
      key: item.id,
      value_en: item.value_en,
      value_ar: item.value_ar,
    })) || [];

  const validationSchema = buildSponsorshipValidation(t);

  const handleSubmit = async (
    values: SponsorshipFormValues,
    { resetForm, setErrors }: FormikHelpers<SponsorshipFormValues>,
  ) => {
    try {
      const formData = new FormData();
      formData.append("org_name", values.org_name);
      formData.append("org_type_id", values.org_type);
      formData.append("person_name", values.person_name);
      formData.append("email", values.email);
      formData.append("phone_number", values.phone_number);
      formData.append("country_code", values.country_code);
      formData.append("sponsor_type_id", values.sponsor_type);
      formData.append("type_of_support_id", values.type_of_support);
      formData.append("sponsorship_details", values.sponsorship_details);
      // Optional; sent only when filled. `preferred_language` is no longer
      // sent — the preference is cancelled (contract Round 3 #16).
      if (values.why_interested.trim()) formData.append("why_interested", values.why_interested.trim());
      if (values.resources_expected.trim()) formData.append("resources_expected", values.resources_expected.trim());

      values.new_sponsor_documents.forEach((file, index) => {
        formData.append(`new_sponsor_documents[${index}]`, file);
      });

      if (values.sponsor_logo) {
        formData.append("sponsor_logo", values.sponsor_logo);
      }

      const response = await sponsorsMutation.mutateAsync(formData);
      if (!isApiSuccess(response)) throw response;
      toast.success(t("COMMON.TOAST.SPONSORSHIP_APPLICATION_SUCCESS"));
      resetForm();
      router.push("/thankyou");
    } catch (err) {
      const fields = getApiFieldErrors(err, selectedLanguage);
      // `new_sponsor_documents.0` → the documents field.
      setErrors(Object.fromEntries(Object.entries(fields).map(([key, message]) => [key.replace(/^(org_type|sponsor_type|type_of_support)_id$/, "$1").replace(/^new_sponsor_documents\..*$/, "new_sponsor_documents"), message])));
      console.error("Registration failed:", err);
      toastApiError(err, selectedLanguage, t("COMMON.TOAST.SPONSORSHIP_APPLICATION_FAILED"));
    }
  };

  return (
    <>
      <HomepageBannerClient />
      <div className="2xl:w-[70%] lg:w-[80%] w-[90%] 2xl:pb-[70px] laptopmain:pb-[50px] laptop:pb-[40px] lg:pb-[40px] pb-[40px] mx-auto">
        <h2 className="">
          <Title
            text={t("COMMON.SPONSORSHIP_APPLICATION_FORM")}
            variant="default"
          />
        </h2>
        <Formik
          initialValues={sponsorshipInitialValues}
          validationSchema={validationSchema}
          onSubmit={handleSubmit}
        >
          {(formikProps) => (
            <SponsorshipFormInner
              formikProps={formikProps}
              sponsorTypeOptions={sponsorTypeOptions}
              orgTypeOptions={orgTypeOptions}
              allSupportTypeOptions={allSupportTypeOptions}
              orgTypeLoading={orgTypeLoading}
              sponsorTypeLoading={sponsorTypeLoading}
              supportTypeLoading={supportTypeLoading}
              sponsorsMutation={sponsorsMutation}
            />
          )}
        </Formik>
      </div>
    </>
  );
}
