import React, { useEffect, useState } from "react";
import { Select } from "../../Select";
import { Input } from "../../Input";
import { Button } from "../../Button";
import { DatePicker } from "../../DatePicker";
import { DateRangePicker } from "../../DateRangePicker";
import { useController } from "react-hook-form";
import DeleteOutlineOutlinedIcon from "@mui/icons-material/DeleteOutlineOutlined";
import {
  NON_TEXT_FILTER_OPTIONS,
  TEXT_FILTER_OPTIONS,
  DATE_FILTER_OPTIONS,
  convertToOptions,
} from "../../../utils/helper";
import {
  findColumnDef,
  getDefaultOperationForColumn,
  getOperatorListForColumn,
} from "../filterUtils";
import moment from "moment";

const NewAdvanceSearchModalItem = ({
  colDefs,
  control,
  index,
  field,
  remove,
  filteredColumnsInitialOptions,
  activeSearchType,
  isLastVisible,
  currentColumnId,
  getValues,
  fields,
  ...args
}) => {
  // UI States - dropdown open/close states
  const [isColumnOptionsOpen, setIsColumnOptionsOpen] = useState(false);
  const [isOperationOptionsOpen, setIsOperationOptionsOpen] = useState(false);
  const [isThirdOptionDropdownOpen, setIsThirdOptionDropdownOpen] =
    useState(false);

  // UI States - current options for dropdowns
  const [currentOperationOptions, setCurrentOperationOptions] = useState([]);
  const [
    currentThirdOptionDropdownOptions,
    setCurrentThirdOptionDropdownOptions,
  ] = useState([]);
  const [currentColumnDef, setCurrentColumnDef] = useState(null);

  // Form controllers
  const { field: columnField } = useController({
    name: `filters.${index}.column`,
    control,
    rules: {
      required: true,
    },
  });

  const { field: operationField } = useController({
    name: `filters.${index}.operation`,
    control,
    rules: { required: activeSearchType !== "advanceSearch" && true },
  });

  const { field: valueField } = useController({
    name: `filters.${index}.value`,
    control,
    rules: {
      required: true,
    },
  });

  // Update operation options when column changes
  useEffect(() => {
    if (!columnField?.value?.value) return;

    // Find column definition using imported utility
    const columnDef = findColumnDef(colDefs, columnField.value.value);
    setCurrentColumnDef(columnDef);

    // Get operator list for this column
    const operatorList = getOperatorListForColumn(columnDef);
    setCurrentOperationOptions(operatorList);

    // Auto-select default operation if needed
    const shouldAutoSelect =
      activeSearchType === "advanceSearch" &&
      operatorList?.length > 0 &&
      !operationField.value;

    if (shouldAutoSelect) {
      const defaultOperation = getDefaultOperationForColumn(columnDef);
      operationField.onChange(defaultOperation);
    }
  }, [columnField?.value, colDefs, activeSearchType]);

  // Update third option dropdown options when column and operation change
  useEffect(() => {
    if (currentColumnDef?.thirdOptionAsDropdown && operationField?.value) {
      if (currentColumnDef?.toShowDuplicateColumnInAdvanceSearch) {
        const currentOptions = currentColumnDef.currentColumnField?.endsWith(
          "1"
        )
          ? currentColumnDef?.thirdOptionDropdownOptions1
          : currentColumnDef?.thirdOptionDropdownOptions2;
        setCurrentThirdOptionDropdownOptions(currentOptions);
      } else {
        setCurrentThirdOptionDropdownOptions(
          currentColumnDef?.thirdOptionDropdownOptions
        );
      }
    }
  }, [currentColumnDef, operationField]);

  // Auto-set operation for search mode
  useEffect(() => {
    if (
      activeSearchType === "search" &&
      !operationField.value &&
      columnField?.value &&
      currentOperationOptions.length > 0
    ) {
      // For date range picker, use "inRange" operator
      if (currentColumnDef?.thirdOptionAsDateRangePicker) {
        operationField.onChange({ label: "In range", value: "inRange" });
      }
      // For date picker, default to "Equals" instead of "Contains"
      else if (currentColumnDef?.filter === "agDateColumnFilter") {
        const equalsOption = currentOperationOptions.find(
          (opt) => opt.value === "equals"
        );
        if (equalsOption) {
          operationField.onChange(equalsOption);
        } else {
          operationField.onChange(currentOperationOptions[0]);
        }
      } else {
        // For other columns, default to "Contains"
        const containsOption = currentOperationOptions.find(
          (opt) => opt.value === "contains"
        );
        if (containsOption) {
          operationField.onChange(containsOption);
        } else {
          operationField.onChange(currentOperationOptions[0]);
        }
      }
    }
  }, [
    columnField?.value,
    currentOperationOptions,
    activeSearchType,
    currentColumnDef,
  ]);

  // Auto-select column when currentColumnId matches and column is not set
  // This handles the case when the modal adds a new filter with the column
  // Only run this for the first filter (index === 0) to avoid auto-selecting when adding new filters
  useEffect(() => {
    if (
      currentColumnId &&
      index === 0 && // Only auto-select for the first filter
      !columnField?.value &&
      columnField?.value?.value !== currentColumnId
    ) {
      const columnOption = filteredColumnsInitialOptions?.find(
        (opt) => opt.value === currentColumnId
      );

      // Also check in all available options (not just filtered)
      const allOptions = convertToOptions(colDefs || []);
      const columnOptionFromAll = allOptions.find(
        (opt) => opt.value === currentColumnId
      );

      const optionToSelect = columnOption || columnOptionFromAll;

      if (optionToSelect) {
        columnField.onChange(optionToSelect);
      }
    }
  }, [
    currentColumnId,
    index,
    columnField?.value,
    filteredColumnsInitialOptions,
    colDefs,
  ]);

  // Handle click outside to close dropdowns
  const handleClickOutside = (event) => {
    if (
      isColumnOptionsOpen ||
      isThirdOptionDropdownOpen ||
      (isOperationOptionsOpen &&
        !event.target.closest(".ia-table-search-content-body"))
    ) {
      setIsColumnOptionsOpen(false);
      setIsThirdOptionDropdownOpen(false);
      setIsOperationOptionsOpen(false);
    }
  };

  useEffect(() => {
    document.addEventListener("click", handleClickOutside);
    return () => {
      document.removeEventListener("click", handleClickOutside);
    };
  }, [isColumnOptionsOpen, isThirdOptionDropdownOpen, isOperationOptionsOpen]);
  // TODO: Remove this effect if not needed after the refactoring is done
  // useEffect(() => {
  //   if (columnField?.value) {
  //     // Recursively find the column definition
  //     const findColumnDef = (cols, field) => {
  //       for (const col of cols) {
  //         if (col.children) {
  //           const found = findColumnDef(col.children, field);
  //           if (found) return found;
  //         }
  //         if (
  //           col.toShowDuplicateColumnInAdvanceSearch &&
  //           col.columnFieldsInAdvanceSearch
  //         ) {
  //           const index = col.columnFieldsInAdvanceSearch?.indexOf(field);
  //           if (index !== -1) {
  //             return {
  //               ...col,
  //               currentColumnField: `${field}${index + 1}`, // add index + 1
  //             };
  //           }
  //         } else if (col.colId === field || col.field === field) {
  //           return col;
  //         }
  //       }
  //       return null;
  //     };

  //     const columnDef = findColumnDef(colDefs, columnField.value.value);
  //     setCurrentColumnDef(columnDef);
  //     const operatorList = columnDef?.operationFilterOptions
  //       ? columnDef.operationFilterOptions
  //       : columnDef?.filter === "agNumberColumnFilter"
  //       ? NON_TEXT_FILTER_OPTIONS
  //       : TEXT_FILTER_OPTIONS;
  //     setCurrentOperationOptions(operatorList);
  //   }
  // }, [columnField?.value, colDefs]);

  return (
    <div className="ia-table-search-content-body">
      <div style={{ display: "flex", flexDirection: "column", flex: 1 }}>
        <Select
          name={`filters.${index}.column`}
          placeholder="Select"
          isOpen={isColumnOptionsOpen}
          setIsOpen={setIsColumnOptionsOpen}
          currentOptions={filteredColumnsInitialOptions || []}
          setCurrentOptions={() => {}} // No-op, handled by parent
          selectedOptions={columnField?.value || null}
          setSelectedOptions={(option) => {
            // Check for duplicate column selection
            if (option && getValues) {
              const formValues = getValues();
              const existingFilters = formValues?.filters || [];

              // Check if this column is already selected in another filter
              const isDuplicate = existingFilters.some(
                (filter, idx) =>
                  idx !== index &&
                  filter?.column?.value === option.value &&
                  filter?.column?.value !== null &&
                  filter?.column?.value !== ""
              );

              if (isDuplicate) {
                // Column already selected, don't allow duplicate
                return;
              }
            }

            columnField.onChange(option);

            // Clear operation and value when column changes
            operationField.onChange(null);
            valueField.onChange("");
          }}
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
          }}
          initialOptions={filteredColumnsInitialOptions || []}
          minWidth={activeSearchType !== "advanceSearch" ? 400 : undefined}
          withPortal={true}
        />
      </div>

      {activeSearchType === "advanceSearch" && (
        <div style={{ display: "flex", flexDirection: "column", flex: 1 }}>
          <Select
            name={`filters.${index}.operation`}
            placeholder="Select"
            isOpen={isOperationOptionsOpen}
            setIsOpen={setIsOperationOptionsOpen}
            currentOptions={currentOperationOptions}
            setCurrentOptions={setCurrentOperationOptions}
            selectedOptions={operationField?.value || null}
            setSelectedOptions={(option) => {
              operationField.onChange(option);
            }}
            initialOptions={currentOperationOptions}
            disabled={!columnField.value}
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
            }}
            withPortal={true}
            isDisabled={
              currentColumnDef?.isThirdOptionDropdownIsBoolean ||
              currentColumnDef?.thirdOptionAsDateRangePicker
                ? true
                : !columnField.value
            }
          />
        </div>
      )}

      <div style={{ display: "flex", flexDirection: "column", flex: 1 }}>
        {currentColumnDef?.thirdOptionAsDropdown &&
        currentThirdOptionDropdownOptions?.length > 0 ? (
          <Select
            name={`filters.${index}.value`}
            placeholder="Select value"
            isOpen={isThirdOptionDropdownOpen}
            setIsOpen={setIsThirdOptionDropdownOpen}
            initialOptions={currentThirdOptionDropdownOptions}
            currentOptions={currentThirdOptionDropdownOptions}
            setCurrentOptions={setCurrentThirdOptionDropdownOptions}
            selectedOptions={valueField?.value || null}
            setSelectedOptions={(option) => {
              valueField.onChange(option);
            }}
            minWidth={activeSearchType !== "advanceSearch" ? 344 : undefined}
            withPortal={true}
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
            }}
            isDisabled={!operationField.value}
          />
        ) : currentColumnDef?.thirdOptionAsDatePicker ? (
          <DatePicker
            selectedDate={
              valueField?.value ? moment(valueField?.value) : undefined
            }
            setSelectedDate={(date) => {
              valueField?.onChange(date);
            }}
            placeholder="Select date"
            name={`filters.${index}.value`}
            isDisabled={!operationField?.value}
            withPortal={true}
            fullWidth
            {...currentColumnDef?.thirdOptionAsDatePickerProps}
          />
        ) : currentColumnDef?.thirdOptionAsDateRangePicker ? (
          <DateRangePicker
            isDisabled={!operationField.value}
            startDate={
              valueField.value?.startDate
                ? moment.isMoment(valueField.value.startDate)
                  ? valueField.value.startDate
                  : moment(valueField.value.startDate)
                : currentColumnDef?.thirdOptionAsDateRangePickerProps?.startDate
                ? moment.isMoment(
                    currentColumnDef.thirdOptionAsDateRangePickerProps.startDate
                  )
                  ? currentColumnDef.thirdOptionAsDateRangePickerProps.startDate
                  : moment(
                      currentColumnDef.thirdOptionAsDateRangePickerProps
                        .startDate
                    )
                : null
            }
            endDate={
              valueField.value?.endDate
                ? moment.isMoment(valueField.value.endDate)
                  ? valueField.value.endDate
                  : moment(valueField.value.endDate)
                : currentColumnDef?.thirdOptionAsDateRangePickerProps?.endDate
                ? moment.isMoment(
                    currentColumnDef.thirdOptionAsDateRangePickerProps.endDate
                  )
                  ? currentColumnDef.thirdOptionAsDateRangePickerProps.endDate
                  : moment(
                      currentColumnDef.thirdOptionAsDateRangePickerProps.endDate
                    )
                : null
            }
            setStartDate={() => {}}
            setEndDate={() => {}}
            handleDatesChange={(startDate, endDate) => {
              // Ensure both dates are moment objects before storing
              const formattedValue = {
                startDate: startDate
                  ? moment.isMoment(startDate)
                    ? startDate
                    : moment(startDate)
                  : null,
                endDate: endDate
                  ? moment.isMoment(endDate)
                    ? endDate
                    : moment(endDate)
                  : null,
              };
              valueField.onChange(formattedValue);
            }}
            withPortal={true}
            name={`filters.${index}.value`}
            fullWidth
            {...(() => {
              // Filter out startDate and endDate from props to prevent overriding our moment objects
              const {
                startDate: _,
                endDate: __,
                ...restProps
              } = currentColumnDef?.thirdOptionAsDateRangePickerProps || {};
              return restProps;
            })()}
          />
        ) : (
          <Input
            placeholder="Enter text"
            name={`filters.${index}.value`}
            value={valueField?.value || ""}
            onChange={(e) => {
              valueField.onChange(e.target.value);
            }}
            isDisabled={
              activeSearchType === "advanceSearch" && !operationField.value
            }
          />
        )}
      </div>

      <Button
        variant="tertiary"
        size="large"
        onClick={(e) => {
          e.preventDefault();
          e.stopPropagation();
          // Use the field's fieldId to ensure we remove the correct item
          // This prevents React from removing the wrong item due to key mismatches
          const fieldId = field?.fieldId || field?.id;
          if (fieldId !== undefined) {
            // Find the actual index using fieldId to ensure correct removal
            const actualIndex = fields.findIndex(
              (f) => (f.fieldId || f.id) === fieldId
            );
            if (actualIndex !== -1) {
              remove(actualIndex);
            }
          } else {
            // Fallback to index if fieldId is not available
            remove(index);
          }
        }}
        type="button"
        disabled={isLastVisible}
      >
        <DeleteOutlineOutlinedIcon />
      </Button>
    </div>
  );
};

export default NewAdvanceSearchModalItem;
