"use client";
import React, { useEffect, useState } from "react";
import { CreateComponent } from "./CreateComponent";
import { UpdateComponent } from "./UpdateComponent";
import { ViewComponent } from "./ViewComponent";
import { FormDisplayProps } from "./types";

export function FormDisplay<T>({
  initialData,
  mode,
  refetch,
  setMode,
  setSelectedItem,
  onCancel,
  lang,
  translations,
  formProps = {},
  apiUrl,
}: FormDisplayProps<T>) {
  const [enhancedFormProps, setEnhancedFormProps] = useState(formProps);

  // Update form props when language or mode changes
  useEffect(() => {
    const updateFormProps = async () => {
      try {
        // Check if schemaPath is provided in formProps
        if (formProps.schemaPath) {
          // Dynamic import of the schema module
          const schemaModule = await import(formProps.schemaPath);

          // Get the appropriate field definitions based on mode
          let fieldDefs;
          if (schemaModule.fieldDefinitions?.getDefinitionsByMode) {
            fieldDefs = schemaModule.fieldDefinitions.getDefinitionsByMode(mode);
          } else if (mode === "create" && schemaModule.createFieldDefinitions) {
            fieldDefs = schemaModule.createFieldDefinitions;
          } else if (mode === "update" && schemaModule.updateFieldDefinitions) {
            fieldDefs = schemaModule.updateFieldDefinitions;
          } else if (mode === "view" && schemaModule.viewFieldDefinitions) {
            fieldDefs = schemaModule.viewFieldDefinitions;
          }

          // Get the appropriate validation schema based on mode and language
          let validationSchema;
          if (mode === "create" && schemaModule.getCreateApplicationSchema) {
            // Use language-aware schema factory function
            validationSchema = schemaModule.getCreateApplicationSchema(lang as "en" | "tr");
          } else if (mode === "update" && schemaModule.getUpdateApplicationSchema) {
            // Use language-aware schema factory function
            validationSchema = schemaModule.getUpdateApplicationSchema(lang as "en" | "tr");
          } else if (mode === "view" && schemaModule.ViewApplicationSchema) {
            validationSchema = schemaModule.ViewApplicationSchema;
          } else if (schemaModule.ApplicationSchema) {
            validationSchema = schemaModule.ApplicationSchema;
          }

          // Get the grouped field definitions structure if available
          const groupedFieldDefs = schemaModule.baseFieldDefinitions || {};

          // Update form props with schema information and current language
          setEnhancedFormProps({
            ...formProps,
            fieldDefinitions: fieldDefs || {},
            validationSchema,
            fieldsByMode: schemaModule.fieldsByMode || {},
            groupedFieldDefinitions: groupedFieldDefs,
            // Add current language to force child components to recognize changes
            currentLang: lang,
            // Add schema path for dynamic imports in child components
            schemaPath: formProps.schemaPath
          });
        } else {
          // If no schema path, just update with current language
          setEnhancedFormProps({
            ...formProps,
            currentLang: lang
          });
        }
      } catch (error) {
        console.error("Error loading schema definitions:", error);
        // Even on error, update the language
        setEnhancedFormProps({
          ...formProps,
          currentLang: lang
        });
      }
    };

    updateFormProps();
  }, [formProps, mode, lang]); // Lang dependency ensures re-fetch when language changes

  // Debug the props received by FormDisplay
  // FormDisplay component renders different form modes based on the mode prop

  // Render the appropriate component based on the mode
  switch (mode) {
    case "create":
      return (
        <CreateComponent<T>
          key={`create-${lang}`} // Add key with lang to force re-render on language change
          refetch={refetch}
          setMode={setMode}
          setSelectedItem={setSelectedItem}
          onCancel={onCancel}
          lang={lang}
          translations={translations}
          formProps={enhancedFormProps}
          apiUrl={apiUrl}
        />
      );
    case "update":
      // Create a stable key for the component to ensure proper re-rendering
      const updateKey = `update-${lang}-${(initialData as any)?.uu_id || 'new'}`;

      return initialData ? (
        <UpdateComponent<T>
          key={updateKey} // Add key with lang and item ID to force re-render
          initialData={initialData}
          refetch={refetch}
          setMode={setMode}
          setSelectedItem={setSelectedItem}
          onCancel={onCancel}
          lang={lang}
          translations={translations}
          formProps={enhancedFormProps}
          apiUrl={apiUrl}
        />
      ) : null;
    case "view":
      return initialData ? (
        <ViewComponent<T>
          key={`view-${lang}`} // Add key with lang to force re-render on language change
          initialData={initialData}
          refetch={refetch}
          setMode={setMode}
          setSelectedItem={setSelectedItem}
          onCancel={onCancel}
          lang={lang}
          translations={translations}
          formProps={enhancedFormProps} // Changed from formProps to enhancedFormProps for consistency
        />
      ) : null;
    default:
      return null;
  }
}
