'use client';

import React from 'react';
import { useFormContext } from './context';
import type { FormDependencyProps } from './types';

export const FormDependency = <
  TValues extends Record<string, any> = Record<string, any>,
>(
  props: FormDependencyProps<TValues>
) => {
  const { dependencies, render } = props;
  const { getFieldValue, subscribe } = useFormContext<TValues>();

  // 使用 useState 管理依赖字段的值
  const [dependencyValues, setDependencyValues] = React.useState<
    Record<string, any>
  >(() => {
    const result: Record<string, any> = {};
    dependencies.forEach((dep) => {
      result[dep] = getFieldValue(dep);
    });
    return result;
  });

  // 使用 useEffect 订阅依赖字段的变化
  React.useEffect(() => {
    const unsubscribes = dependencies.map((dep) =>
      subscribe(dep, () => {
        // 当依赖字段变化时，更新状态
        setDependencyValues((prev) => {
          const newValues: Record<string, any> = { ...prev };
          let hasChanged = false;

          dependencies.forEach((depName) => {
            const newValue = getFieldValue(depName);
            if (newValues[depName] !== newValue) {
              newValues[depName] = newValue;
              hasChanged = true;
            }
          });

          return hasChanged ? newValues : prev;
        });
      })
    );

    return () => {
      unsubscribes.forEach((unsub) => unsub());
    };
  }, [dependencies, subscribe, getFieldValue]);

  return <>{render({ values: dependencyValues })}</>;
};
