"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 { 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 { EquityStructureFormFields } from "@/components/equity/EquityStructureFormFields";
import { useEquityStructureForm, StructureFormField } from "@/hooks/useEquityStructureForm";

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

  const {
    formData,
    structureValues,
    footerData,
    amountDisplayValue,
    rows,
    currencies,
    isEditing,
    editId,
    loadingExisting,
    showBankModal,
    setShowBankModal,
    updateFormData,
    resetForm,
    validateField,
    validateForm,
    createPayload,
    addRow,
    removeRow,
    formatDate,
    pageTitle,
    saveLabel,
    savingLabel,
  } = useEquityStructureForm();


  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(() => {
        const firstErrorField = Object.keys(validationErrors)[0];
        const errorElement = document.querySelector(`[name="${firstErrorField}"], [data-field="${firstErrorField}"]`) ||
                            document.querySelector(`input[id*="${firstErrorField}"], select[id*="${firstErrorField}"]`);
        if (errorElement) {
          errorElement.scrollIntoView({ behavior: "smooth", block: "center" });
          if (errorElement instanceof HTMLElement && 'focus' in errorElement) {
            (errorElement as HTMLElement).focus();
          }
        }
      }, 100);
      
      return;
    }

    setErrors({});
    setIsSaving(true);

    const formElement = formRef.current || (e.currentTarget as HTMLFormElement);
    if (!formElement || !(formElement instanceof HTMLFormElement)) {
      showToast("error", "Form error. Please refresh the page.");
      setIsSaving(false);
      return;
    }

    const payload = createPayload();

    try {
      const url = isEditing && editId
        ? `/api/equity/structure/update?id=${encodeURIComponent(editId)}`
        : "/api/equity/structure/form";
      const method = isEditing ? "PUT" : "POST";
      
      const response = await fetch(url, {
        method,
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        const errorBody = await response.text();
        let errorMessage = `Structure ${isEditing ? "update" : "create"} failed with status ${response.status}`;
        try {
          const errorJson = JSON.parse(errorBody);
          errorMessage = errorJson.error || errorJson.message || errorMessage;
        } catch {
          errorMessage = errorBody || errorMessage;
        }
        
        showToast("error", errorMessage);
        setIsSaving(false);
        return;
      }

      const result = await response.json().catch(() => null);
      const isSuccess = result?.success === true || result?.status === "success";

      if (isSuccess) {
        showToast("success", isEditing ? "Structure updated successfully!" : "Structure saved successfully!");
        if (!isEditing) {
          resetForm();
        }
      } else {
        const errorMessage =
          result === null
            ? "Unexpected response received from the server."
            : typeof result?.message === "string"
            ? result.message
            : typeof result?.error === "string"
            ? result.error
            : "Unexpected response received from the server.";
        showToast("error", errorMessage);
      }
    } catch (error) {
      const fallbackMessage =
        error instanceof Error && error.message 
          ? error.message 
          : `Failed to ${isEditing ? "update" : "save"} Structure. Please check your connection and try again.`;
      showToast("error", fallbackMessage);
    } 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);
  }, []);

  const setSelectedFile = useCallback((file: File | null) => {
    updateFormData({ selectedFile: file });
  }, [updateFormData]);


  return (
    <>
      <ToastComponent toast={toast} />
      <LoadingOverlay isLoading={loadingExisting} message="Loading structure 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: "Structure", href: "/equity/structure" },
              { label: isEditing ? "Update Structure" : "Create New Structure" },
            ]}
          />

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

              <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 StructureForm() {
  return (
    <Suspense fallback={<div className="p-6 text-center text-sm text-slate-500">Loading form…</div>}>
      <StructureFormContent />
    </Suspense>
  );
}
