"use client";

import { Suspense, useCallback, useState, FormEvent } from "react";
import FloatingFooter from "@/components/FloatingFooter";
import { FormSectionHeading } from "@/components/ui/FormSectionHeading";
import { formatDateToString } from "@/lib/common";
import { scrollToFirstFormError } from "@/lib/form-utils";
import { submitOtherAsset } from "@/lib/other-assets-service";
import { useToast } from "@/hooks/useToast";
import { useFormState } from "@/hooks/useFormState";
import { ToastComponent } from "@/components/common/Toast";
import { LoadingOverlay } from "@/components/common/LoadingOverlay";
import BankModal from "@/components/common/BankModel";
import { OtherAssetsFormFields } from "@/components/alternativeinvest/OtherAssetsFormFields";
import { useOtherAssetsForm, OtherAssetsFormField } from "@/hooks/useOtherAssetsForm";

function OtherAssetsFormContent() {
  const { toast, showToast } = useToast();
  const { errors, setErrors, clearError, handleFieldBlur, formRef } = useFormState<OtherAssetsFormField>();
  const [isSaving, setIsSaving] = useState(false);

  const {
    formData,
    footerData,
    amountDisplayValue,
    isEditing,
    editId,
    loadingExisting,
    showBankModal,
    setShowBankModal,
    updateFormData,
    resetForm,
    validateField,
    validateForm,
    createPayload,
    pageTitle,
    saveLabel,
    savingLabel,
  } = useOtherAssetsForm();

  const handleSubmit = useCallback(
    async (e: FormEvent<HTMLFormElement>) => {
      e.preventDefault();

      const validationErrors = validateForm();
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        const errorCount = Object.keys(validationErrors).length;
        const errorFields = Object.keys(validationErrors).join(", ");
        showToast(
          "error",
          `Please fix ${errorCount} required field${errorCount > 1 ? "s" : ""}: ${errorFields}`
        );
        setTimeout(() => scrollToFirstFormError(validationErrors), 100);
        return;
      }

      setErrors({});
      setIsSaving(true);

      try {
        const payload = createPayload();
        const result = await submitOtherAsset(payload, isEditing, editId ?? undefined);
        if (result.success) {
          showToast("success", result.message);
          if (!isEditing) resetForm();
        } else {
          showToast("error", result.message);
        }
      } catch (error) {
        const fallback =
          error instanceof Error && error.message
            ? error.message
            : `Failed to ${isEditing ? "update" : "save"} other asset. Please check your connection and try again.`;
        showToast("error", fallback);
      } finally {
        setIsSaving(false);
      }
    },
    [isEditing, editId, validateForm, setErrors, showToast, formRef, createPayload, resetForm]
  );

  const handleSave = useCallback(() => {
    if (isSaving || !formRef.current) {
      if (!formRef.current) {
        showToast("error", "Form not ready. Please refresh the page.");
      }
      return;
    }

    formRef.current.requestSubmit();
  }, [isSaving, formRef, showToast, loadingExisting]);

  const handleCloseBankModal = useCallback(() => {
    setShowBankModal(false);
  }, [setShowBankModal]);

  return (
    <>
      <ToastComponent toast={toast} />
      <LoadingOverlay isLoading={loadingExisting} message="Loading other asset data..." />
      <div className="container mx-auto mt-6">
        <div className="bg-white rounded-lg shadow-md border-0">
          <FormSectionHeading
            title={pageTitle}
            eyebrow="Key Details"
            showBackButton
            icon={<i className="bx bx-line-chart" aria-hidden="true" />}
            breadcrumbs={[
              { label: "Home", href: "/" },
              { label: "Other Assets", href: "/alternativeinvest/otherassets" },
              { label: pageTitle },
            ]}
          />

          <div className="p-6 md:p-8 bg-slate-50/60">
            <form ref={formRef} onSubmit={handleSubmit} method="post">
              <OtherAssetsFormFields
                formData={formData}
                amountDisplayValue={amountDisplayValue}
                errors={errors}
                clearError={(field: string) => clearError(field as OtherAssetsFormField)}
                handleFieldBlur={handleFieldBlur}
                validateField={validateField}
                updateFormData={updateFormData}
                formatDateToString={formatDateToString}
                setShowBankModal={setShowBankModal}
              />

              <div className="pb-10">
                {/* Spacing for FloatingFooter */}
              </div>
            </form>
          </div>
        </div>
      </div>
      {showBankModal && (
        <BankModal
          isOpen={showBankModal}
          onClose={handleCloseBankModal}
        />
      )}
      <FloatingFooter
        data={footerData}
        onSave={handleSave}
        isSaving={isSaving || loadingExisting}
        saveLabel={saveLabel}
        savingLabel={savingLabel}
      />
    </>
  );
}

export default function OtherAssetsForm() {
  return (
    <Suspense fallback={<div className="p-6 text-center text-sm text-slate-500">Loading form…</div>}>
      <OtherAssetsFormContent />
    </Suspense>
  );
}
