"use client";

import { useLanguageStore } from "@/store/languageStore";
import { Form, FormikProps } from "formik";
import { useTranslation } from "react-i18next";
import Input from "@/components/ui/Input";
import { Button } from "@/components/ui/Button";
import TextArea from "@/components/ui/TextArea";
import UploadDocument from "@/components/ui/UploadDocument";
import SelectInput from "@/components/ui/SelectInput";
import { useEffect } from "react";
import SponsorshipSupportFields from "./SponsorshipSupportFields";
import { useSponsorTypeFilters } from "./sponsorTypeFilters";
import { type SponsorshipFormValues } from "./SponsorshipForm";
import { SPONSOR_DOCUMENT_ACCEPT, SPONSOR_LOGO_ACCEPT } from "./sponsorshipFiles";

/**
 * The sponsorship form's fields.
 *
 * Separate from `SponsorshipForm`, which owns the three dropdown queries and
 * the submit: this half renders, and reads the Formik bag it is handed.
 */
interface SponsorshipFormInnerProps {
  formikProps: FormikProps<SponsorshipFormValues>;
  sponsorTypeOptions: { value: string; label: string; value_en?: string; value_ar?: string }[];
  orgTypeOptions: { value: string; label: string }[];
  allSupportTypeOptions: { value: string; label: string; value_en?: string; value_ar?: string }[];
  orgTypeLoading: boolean;
  sponsorTypeLoading: boolean;
  supportTypeLoading: boolean;
  /* Only `isPending` is read — the submit button's loading state. A full
     `UseMutationResult` would pin four generic parameters this component has no
     reason to know. */
  sponsorsMutation: { isPending: boolean };
}

export default function SponsorshipFormInner({
  formikProps,
  sponsorTypeOptions,
  orgTypeOptions,
  allSupportTypeOptions,
  orgTypeLoading,
  sponsorTypeLoading,
  supportTypeLoading,
  sponsorsMutation,
}: SponsorshipFormInnerProps) {
  const { setFieldValue, values, isSubmitting } = formikProps;
  const { t } = useTranslation();
  const language = useLanguageStore(state => state.language);

  const { filteredSupportTypeOptions } = useSponsorTypeFilters({
    sponsorTypeOptions,
    allSupportTypeOptions,
    sponsorType: values.sponsor_type,
  });

  useEffect(() => {
    setFieldValue("type_of_support", "");
  }, [values.sponsor_type, setFieldValue]);

  return (
    <Form dir={language === "ar" ? "rtl" : "ltr"} className="selectfiled" noValidate>
      <div className="flex gap-6 mobilescreen:gap-1 mobilescreen:flex-col">
        <Input
          name="org_name"
          label={t("COMMON.ORGANIZATION_NAME")}
          type="text"
        />
        <SelectInput
          name="org_type"
          label={t("COMMON.TYPE_OF_ORGANIZATION")}
          options={orgTypeOptions}
          onChange={(selectedOption) =>
            setFieldValue("org_type", selectedOption?.value || "")
          }
          disabled={orgTypeLoading}
        />
      </div>
      <div className="flex gap-6 mobilescreen:gap-1 mobilescreen:flex-col">
        <Input
          name="person_name"
          label={t("COMMON.CONTACT_PERSON_NAME")}
          type="text"
        />
        <Input
          name="email"
          label={t("COMMON.EMAIL_ADDRESS")}
          type="email"
          dir="ltr"
          className="!text-left"
        />
      </div>

      <SponsorshipSupportFields
        formikProps={formikProps}
        sponsorTypeOptions={sponsorTypeOptions}
        sponsorTypeLoading={sponsorTypeLoading}
        filteredSupportTypeOptions={filteredSupportTypeOptions}
        supportTypeLoading={supportTypeLoading}
      />

      <TextArea
        name="sponsorship_details"
        label={t("COMMON.SPONSORSHIP_DETAILS")}
        rows={5}
      />

      <TextArea
        name="why_interested"
        label={t("COMMON.SPONSOR_WHY_INTERESTED")}
        rows={3}
      />

      <TextArea
        name="resources_expected"
        label={t("COMMON.SPONSOR_RESOURCES_EXPECTED")}
        rows={3}
      />

      <div className="pb-4">
        <UploadDocument
          name="new_sponsor_documents"
          label={t("COMMON.UPLOAD_DOCUMENTS")}
          instructions={[
            t("COMMON.OFFICIAL_SPONSORSHIP_LETTER"),
            t("COMMON.COMMERCIAL_REGISTRATION_COPY"),
          ]}
          multiple={true}
          accept={SPONSOR_DOCUMENT_ACCEPT}
          setFieldValue={setFieldValue}
          onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
            event.preventDefault();
            const newFiles = event.target.files
              ? Array.from(event.target.files)
              : [];
            const updatedFiles = [
              ...(values.new_sponsor_documents || []),
              ...newFiles,
            ];
            setFieldValue("new_sponsor_documents", updatedFiles);
          }}
        />
      </div>
      <div>
        <UploadDocument
          name="sponsor_logo"
          label={t("COMMON.UPLOAD_LOGO")}
          instructions={[t("COMMON.HIGH_QUALITY_LOGO")]}
          multiple={false}
          accept={SPONSOR_LOGO_ACCEPT}
          setFieldValue={setFieldValue}
          onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
            event.preventDefault();
            const file = event.target.files
              ? event.target.files[0]
              : null;
            setFieldValue("sponsor_logo", file);
          }}
        />
      </div>
      <div className="flex justify-center 2xl:pt-[70px] laptopmain:2xl:pt-[40px] laptop:pt-[40px] pt-[40px]">
        <Button
          type="submit"
          variant="primary"
          size="medium"
          disabled={isSubmitting || sponsorsMutation.isPending}
        >
          {t("COMMON.SUBMIT")}
        </Button>
      </div>
    </Form>
  );
}
