import React, { useRef, useEffect } from "react";
import { TabView, TabPanel } from "primereact/tabview";
import FormFieldRenderer from "@/Components/FormFieldRenderer";

/**
 * Generic tabbed step form – works with any steps config.
 * Renders TabView with one panel per step and FormFieldRenderer for each step's fields.
 * Pass stepsConfig from formConfigs (e.g. lcModuleStepsConfig) or your own config.
 */
export default function TabStepForm({
  stepsConfig,
  activeIndex,
  onTabChange,
  completedSteps = [],
  control,
  errors = {},
  formData = {},
  setFormData = () => { },
  className = "tab-step-form",
  stepGridClassName = "grid grid-cols-12 gap-x-4 gap-y-6 mt-8",
  stepContext: stepContextFromParent = {},
}) {
  const wrapperRef = useRef(null);

  useEffect(() => {
    const applyActiveBar = () => {
      const wrapper = wrapperRef.current;
      if (!wrapper) return;
      const nav = wrapper.querySelector(".p-tabview-nav");
      if (!nav) return;
      const tabs = nav.querySelectorAll(":scope > li");
      tabs.forEach((li, index) => {
        li.setAttribute("data-lc-active", index === activeIndex ? "true" : "false");
      });
    };
    applyActiveBar();
    const t = requestAnimationFrame(() => {
      applyActiveBar();
    });
    return () => cancelAnimationFrame(t);
  }, [activeIndex]);

  if (!stepsConfig || !Array.isArray(stepsConfig) || stepsConfig.length === 0) {
    return null;
  }

  return (
    <div ref={wrapperRef} className="lc-module-tabs-wrapper" data-active-index={activeIndex}>
      <TabView
        activeIndex={activeIndex}
        onTabChange={onTabChange}
        className={className}
      >
      {stepsConfig.map((step) => {
        const context = {
          control,
          step,
          stepIndex: step.stepIndex,
          ...stepContextFromParent,
        };
        return (
          <TabPanel
            key={step.stepIndex}
            header={
              <span
                className={
                  completedSteps.includes(step.stepIndex)
                    ? "text-green-600 font-semibold"
                    : ""
                }
              >
                <i
                  className={`pi ${completedSteps.includes(step.stepIndex)
                    ? "pi-check-circle"
                    : "pi-circle"
                    } mr-2`}
                />
                {step.title}
              </span>
            }
          >
            {step.description && step.fields?.length === 0 && (
              <div className="mb-3 text-sm text-gray-600">
                {step.description}
              </div>
            )}
            <div className={step.gridClassName ?? stepGridClassName}>
              <FormFieldRenderer
                config={step.fields}
                formData={formData}
                setFormData={setFormData}
                errors={errors}
                context={context}
                className="h-11 w-full"
              />
            </div>
          </TabPanel>
        );
      })}
      </TabView>
    </div>
  );
}
