"use client";

import QueryErrorNotice from "@/components/shared/QueryErrorNotice";
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import Input from "@/components/ui/Input";
import SelectInput from "@/components/ui/SelectInput";
import { getBanks } from "@/features/shared/services/dropdowns";
import { useLanguageStore } from "@/store/languageStore";
import { getOrganizerProfile } from "@/features/profile/services/profileApi";
import { useAuthStore } from "@/store/authStore";
import type { LearnServeFormValues } from "./learnServeFormTypes";
import HolderReviewNotice, { HolderReviewStatus } from "@/features/trainer/components/HolderReviewNotice";

/**
 * Where a paid development opportunity's payout goes (client, 2026-10-10):
 * the platform keeps its cut and transfers the rest — `100 − fee` percent,
 * the fee coming from the dashboard — to the publisher's bank account.
 *
 * The account belongs to the **publisher**, not to the opportunity: it is
 * saved on the organization profile (`PATCH /organization-profile/`, the three
 * `bank_*` columns) right before the opportunity is submitted, so the next
 * paid opportunity finds it already filled in and hides the addition form.
 *
 * An individual trainer has no organization profile; their account is the one
 * given in the trainer request, which this form cannot edit — they get the
 * no additional bank section in the publishing form.
 *
 * `payout_bank_needed` is what the schema and the submit read: true only while
 * the fields are on screen.
 */
export default function PayoutBankFields({
  values,
  setFieldValue,
  setFieldTouched,
}: {
  values: LearnServeFormValues;
  setFieldValue: (field: string, value: unknown) => void;
  setFieldTouched: (field: string, touched: boolean) => void;
  platformFeePercent: number | null;
}) {
  const { t } = useTranslation();
  const isOrganization = useAuthStore((s) => s.user?.user_type === "organization");
  const { data: organizerProfile, isSuccess, isError, error, refetch } = useQuery({
    queryKey: ["organizer-profile"],
    queryFn: getOrganizerProfile,
    enabled: isOrganization,
    retry: false,
  });
  const profile = organizerProfile?.data;
  /* BE-187 — the resource never returns the IBAN, only its last four
     (`bank_account_iban_last4`) and `has_payout_bank_account`. Reading the
     absent `bank_account_number` treated every organization as having no
     account: the fields came back on each paid publish, and re-sending them
     to the profile is refused (`use_change_request`) once one is on file. */
  const last4 = profile?.bank_account_iban_last4 ?? profile?.bank_account_number?.slice(-4) ?? null;
  const saved =
    profile && (profile.has_payout_bank_account ?? Boolean(profile.bank_name && profile.bank_account_holder_name && last4))
      ? {
          bank: profile.bank_name ?? "",
          holder: profile.bank_account_holder_name ?? "",
          last4: last4 ?? "",
        }
      : null;

  // Only once the profile answered: a failed read is not proof that no account is on file.
  const showFields = isOrganization && isSuccess && !saved;

  const language = useLanguageStore((state) => state.language);
  const banks = useQuery({
    queryKey: ["banks"],
    queryFn: getBanks,
    enabled: showFields,
  });

  useEffect(() => {
    if (values.payout_bank_needed !== showFields) {
      setFieldValue("payout_bank_needed", showFields);
    }
  }, [showFields, values.payout_bank_needed, setFieldValue]);

  if (isOrganization && isError) {
    return <QueryErrorNotice error={error} onRetry={() => void refetch()} />;
  }
  if (!showFields) {
    // Keep any blocking review warning visible without the account section.
    return isOrganization && saved
      ? <HolderReviewStatus status={profile?.bank_holder_review_status} />
      : null;
  }

  return (
    <div className="col-span-full mb-4 rounded-2xl border border-[#29246D1A] bg-[#F7F8FD] p-4">
      <p className="mb-1 font-semibold text-primary-5">{t("COMMON.PAYOUT_ACCOUNT_TITLE")}</p>
      {showFields && (
        <div className="grid grid-cols-1 gap-x-6 md:grid-cols-3">
          <div>
            <SelectInput<number>
              name="payout_bank_id"
              label={t("COMMON.BANK_NAME")}
              options={(banks.data?.data ?? []).map((bank) => ({
                value: bank.id,
                label: language === "ar" ? bank.name_ar || bank.name_en : bank.name_en || bank.name_ar,
              }))}
              isSearchable
              isLoading={banks.isFetching}
              onChange={(option) => {
                const bank = banks.data?.data?.find((item) => item.id === option?.value);
                setFieldValue("payout_bank_name", bank?.name_en ?? "");
              }}
            />
            {banks.isError && <QueryErrorNotice error={banks.error} onRetry={() => void banks.refetch()} />}
          </div>
          <Input
            name="payout_bank_holder"
            label={t("COMMON.BANK_ACCOUNT_HOLDER_NAME")}
            onFocus={() => setFieldTouched("payout_bank_holder", true)}
          />
          <Input
            name="payout_iban"
            label={t("COMMON.IBAN")}
            dir="ltr"
            maxLength={34}
            onFocus={() => setFieldTouched("payout_iban", true)}
          />
        </div>
      )}
      {showFields && (
        <HolderReviewNotice kind="organization" holder={values.payout_bank_holder} registeredName={profile?.company_name} />
      )}
      {showFields && (
        <p className="text-xs text-secondary-102">
          {t("COMMON.PAYOUT_ACCOUNT_INITIAL_NOTE")} {t("COMMON.BANK_HOLDER_ORG_HINT")}
        </p>
      )}
    </div>
  );
}
