import { useFieldArray, useForm } from "react-hook-form";
import { Modal } from "../../Modal";
import { ButtonGroup } from "../../ButtonGroup";
import { Button } from "../../Button";
import { AddOutlined } from "@mui/icons-material";
import React, { useMemo, useState, useEffect } from "react";
import NewAdvanceSearchModalItem from "./NewAdvanceSearchModalItem";
import { convertToOptions } from "../../../utils/helper";

const filterInitialValues = {
  column: { label: "", value: "", type: "text" },
  operation: null,
  value: null,
};

const NewAdvanceSearchModal = ({
  isAdvanceSearch,
  actualRef,
  onSearchApplyClick,
  toggleAdvanceSearch,
  initialFilters,
  setInitialFilters,
  colDefs = [],
  currentColumnId,
  ...args
}) => {
  const [activeSearchType, setActiveSearchType] = useState("advanceSearch");

  const onChangeSearchType = (e, val) => {
    e.preventDefault();
    setActiveSearchType(val);
  };

  const formMethods = useForm({
    defaultValues: {
      filters: initialFilters,
    },
    rules: {
      required: true,
    },
  });

  const {
    control,
    handleSubmit,
    watch,
    formState: { isValid: isFormValid },
    setValue,
    getValues,
    reset,
  } = formMethods;
  const { fields, append, remove } = useFieldArray({
    control,
    name: "filters",
    keyName: "fieldId",
  });

  // Compute filtered column options - exclude already selected columns
  const formValues = watch();
  const filteredColumnsInitialOptions = useMemo(() => {
    const selectedValues = (formValues?.filters || [])
      .map((f) => f?.column?.value)
      .filter(Boolean);

    return convertToOptions(colDefs || []).filter(
      (opt) => !selectedValues.includes(opt.value)
    );
  }, [colDefs, formValues?.filters]);

  // Track if we've already initialized with currentColumnId to prevent re-running
  const [hasInitializedWithColumnId, setHasInitializedWithColumnId] =
    useState(false);
  const prevIsAdvanceSearchRef = React.useRef(false);

  // Reset form when modal opens with initialFilters
  useEffect(() => {
    // Only reset when modal is opening (transitioning from closed to open)
    const isOpening = isAdvanceSearch && !prevIsAdvanceSearchRef.current;
    if (isOpening && initialFilters !== undefined) {
      // Reset form with initialFilters when modal opens
      reset({
        filters:
          initialFilters.length > 0 ? initialFilters : [filterInitialValues],
      });
      setHasInitializedWithColumnId(false); // Reset flag so auto-add can run if needed
    }
    // Update ref for next render
    prevIsAdvanceSearchRef.current = isAdvanceSearch;
  }, [isAdvanceSearch, initialFilters, reset]);

  // Auto-add column filter when modal opens with currentColumnId
  // Only run if there are no valid filters already in initialFilters
  useEffect(() => {
    if (
      isAdvanceSearch &&
      currentColumnId &&
      !hasInitializedWithColumnId &&
      initialFilters
    ) {
      // Check if we have any valid filters in initialFilters
      const hasValidFilters = initialFilters.some(
        (f) =>
          f?.column?.value &&
          f?.column?.value !== null &&
          f?.column?.value !== ""
      );

      // Only auto-add if there are no valid filters
      if (!hasValidFilters) {
        const formValues = getValues();
        const existingFilters = formValues?.filters || [];

        // Check if currentColumnId already exists in filters
        const columnExists = existingFilters.some(
          (filter) => filter?.column?.value === currentColumnId
        );

        // If column doesn't exist, add it as a new filter
        if (!columnExists) {
          const columnOption = convertToOptions(colDefs || []).find(
            (opt) => opt.value === currentColumnId
          );

          if (columnOption) {
            if (
              existingFilters.length > 0 &&
              !existingFilters[0]?.column?.value
            ) {
              // Replace the first empty filter with the new column
              setValue(`filters.0.column`, columnOption);
            } else {
              // Append a new filter with the column pre-selected
              append({
                column: columnOption,
                operation: null,
                value: null,
              });
            }
          }
        }
      }
      setHasInitializedWithColumnId(true);
    }
  }, [
    isAdvanceSearch,
    currentColumnId,
    colDefs,
    getValues,
    setValue,
    append,
    hasInitializedWithColumnId,
    initialFilters,
  ]);

  // Reset initialization flag when modal closes
  useEffect(() => {
    if (!isAdvanceSearch) {
      setHasInitializedWithColumnId(false);
    }
  }, [isAdvanceSearch]);

  const onCloseModal = () => {
    toggleAdvanceSearch();
  };

  const handleSearchApplyClick = () => {
    const formValues = formMethods.getValues().filters || [];
    const validFilters = formValues.filter((filter) => {
      const hasColumn =
        filter?.column?.value &&
        filter?.column?.value !== null &&
        filter?.column?.value !== "";

      // For advance search, operation is required
      if (activeSearchType === "advanceSearch") {
        return (
          hasColumn &&
          filter?.operation?.value &&
          filter?.operation?.value !== null &&
          filter?.operation?.value !== ""
        );
      }

      // For normal search, only column is required
      return hasColumn;
    });
    onSearchApplyClick(validFilters);
  };
  const onClearAttributeValue = () => {
    const updatedFilters = formMethods
      .getValues()
      .filters.map((filter) => ({ ...filter, value: null }));
    formMethods.reset({
      filters: updatedFilters,
    });
  };
  const onClearAll = () => {
    // Only clear the form UI - don't apply to grid yet
    // The filters will be cleared when user clicks "Apply"
    formMethods.reset({
      filters: [filterInitialValues],
    });
  };

  return (
    <Modal
      className="ia-table-search-modal"
      onClose={onCloseModal}
      onPrimaryButtonClick={handleSearchApplyClick}
      onSecondaryButtonClick={(e) => {
        e.preventDefault();
        onCloseModal();
      }}
      primaryButtonProps={{
        type: "submit",
        // disabled: !isFormValid,
      }}
      secondaryButtonProps={{
        disabled: !isFormValid,
      }}
      primaryButtonLabel="Apply"
      secondaryButtonLabel={args?.onSearchSaveClick ? "Save search" : null}
      size="small"
      title="Search"
      width={850}
      height={400}
      open={isAdvanceSearch}
    >
      <div className="ia-table-search-header">
        <ButtonGroup
          options={[
            {
              label: "Search",
              value: "search",
            },
            {
              label: "Advance Search",
              value: "advanceSearch",
            },
          ]}
          selectedOption={activeSearchType}
          onChange={(e, val) => {
            e.preventDefault();
            onChangeSearchType(e, val);
            actualRef?.current?.api?.destroyFilter(null);
          }}
        />

        <Button
          variant="url"
          size="small"
          type="button"
          onClick={(e) => {
            e.preventDefault();
            onClearAll();
          }}
        >
          Clear all
        </Button>
      </div>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          handleSearchApplyClick();
        }}
        className="ia-table-search-content"
      >
        <div className="ia-table-search-content-title">
          Match all of the following rules
        </div>
        <>
          {fields.map((field, index) => (
            <NewAdvanceSearchModalItem
              key={field.fieldId || field.id}
              field={field}
              index={index}
              colDefs={colDefs}
              control={control}
              remove={remove}
              filteredColumnsInitialOptions={filteredColumnsInitialOptions}
              activeSearchType={activeSearchType}
              isLastVisible={fields.length === 1}
              currentColumnId={currentColumnId}
              getValues={getValues}
              fields={fields}
            />
          ))}
        </>

        <div className="ia-table-search-content-footer">
          <Button
            variant="secondary"
            size="large"
            onClick={onClearAttributeValue}
            type="button"
            // disabled={filteredColumnsInitialOptions?.length === 1}
          >
            Clear values
          </Button>
          <Button
            variant="tertiary"
            size="large"
            type="button"
            onClick={() => {
              // Add empty filter - let user decide what to select
              append({
                column: null,
                operation: null,
                value: null,
              });
            }}
            // disabled={visibleFields.length === allowedCols.length}
            icon={<AddOutlined />}
          >
            Add attribute
          </Button>
        </div>
      </form>
    </Modal>
  );
};

export default NewAdvanceSearchModal;
