/**
 *
 * CustomerSearchSection
 *
 */
import React, {
  useState, useCallback, useRef, useEffect,
} from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapAlert from '@capillarytech/cap-ui-library/CapAlert';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapCard from '@capillarytech/cap-ui-library/CapCard';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapLink from '@capillarytech/cap-ui-library/CapLink';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import { debounce } from 'lodash';
import './_customerSearch.scss';
import {
  FIRSTNAME,
  LASTNAME,
  INSTORE,
  NA,
  MINIMUM_IDENTIFIER_LENGTH,
} from './constants';
import {
  checkForData,
  removeExtraIdentifiers,
  identifiersHighlight,
  getNamingIcon,
} from './utils';
import messages from './messages';


const CustomerSearchSection = ({
  intl: { formatMessage },
  onCustomerSelect,
  onSearch,
  onClearSearch,
  onClearSelection,
  customers,
  isSearchingCustomer,
  searchError,
  selectedCustomer,
  hasSearched,
  disabled,
}) => {
  const [showDropdown, setShowDropdown] = useState(false);
  const [customerSearchValue, setCustomerSearchValue] = useState('');
  const [processedSearchData, setProcessedSearchData] = useState([]);

  const searchContainerRef = useRef(null);

  const debouncedSearch = useCallback(
    debounce((query) => {
      onSearch(query);
    }, 300),
    [onSearch],
  );

  const handleSearchChange = useCallback(
    (e) => {
      const { value } = e.target;
      setCustomerSearchValue(value);
      if (value?.trim()) {
        debouncedSearch(value.trim());
      } else {
        if (onClearSearch && typeof onClearSearch === 'function') {
          onClearSearch();
        }
        setShowDropdown(false);
      }
    },
    [debouncedSearch, onClearSearch],
  );

  const handleCustomerSelectItem = useCallback(
    (customer) => {
      setShowDropdown(false);
      onCustomerSelect(customer);
    },
    [onCustomerSelect],
  );

  const handleClickOutside = useCallback((event) => {
    if (
      searchContainerRef.current
      && !searchContainerRef.current.contains(event.target)
    ) {
      setShowDropdown(false);
    }
  }, []);

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [handleClickOutside]);

  useEffect(
    () => () => {
      debouncedSearch.cancel();
    },
    [debouncedSearch],
  );

  useEffect(() => {
    if (customerSearchValue.trim() === '') {
      setShowDropdown(false);
    } else if (isSearchingCustomer || hasSearched) {
      setShowDropdown(true);
    }
  }, [customerSearchValue, isSearchingCustomer, hasSearched]);

  // Compute search data when dependencies change
  useEffect(() => {
    const computedData = searchData();
    setProcessedSearchData(computedData);
  }, [isSearchingCustomer, customers, customerSearchValue]);

  const getCompleteName = (data) => {
    const { firstName = '', lastName = '' } = data?.[0] || {};
    return `${firstName} ${lastName}`.trim() || NA;
  };

  const searchData = () => {
    let finalSearchData;
    if (!isSearchingCustomer && customers?.length > 0) {
      finalSearchData = customers?.map((dataToFetch) => {
        const checkForInstoreData = checkForData(dataToFetch?.profiles, INSTORE);
        const identifiers = removeExtraIdentifiers(
          dataToFetch?.matchedIdentifiers,
          FIRSTNAME,
          LASTNAME,
        );
        const fullName = getCompleteName( checkForInstoreData?.length ? checkForInstoreData : dataToFetch?.profiles);
        return {
          customerId: dataToFetch?.userId,
          name: fullName,
          identifiers: identifiersHighlight(customerSearchValue, identifiers),
        };
      });
    }
    return finalSearchData || [];
  };

  const showIdentifiers = (data) => {
    if (!Array.isArray(data) || data.length === 0) return null;

    const renderLabel = (item, index, isLast) => (
      <CapLabel
        type="label1"
        key={`${item?.firstString || ''}-${item?.secondString || ''}-${item?.thirdString || ''}-${index}`}
        className={`identifiers-text ${data.length > MINIMUM_IDENTIFIER_LENGTH ? 'multiple-identifiers' : ''}`}
      >
        {item?.firstString}
        <span className="highlight-background-color">{item?.secondString}</span>
        {item?.thirdString}
        {!isLast && (
          <>
            ,
            <span className="comma-separated-align"> </span>
          </>
        )}
      </CapLabel>
    );

    if (data.length > MINIMUM_IDENTIFIER_LENGTH) {
      return data.map((item, index) => renderLabel(item, index, index === data.length - 1));
    }

    return renderLabel(data[0], 0, true);
  };

  const onClear = () => {
    setCustomerSearchValue('');
    onClearSelection();
  };

  return (
    <CapRow type="flex" vertical noWrap className="customer-search-section">
      <div ref={searchContainerRef}>
        <CapRow useLegacy className="search-container">
          {selectedCustomer ? (
            <SelectedCustomerView
              customer={selectedCustomer}
              onClear={onClear}
              showIdentifiers={showIdentifiers}
            />
          ) : (
            <SearchInput
              value={customerSearchValue}
              onChange={handleSearchChange}
              isLoading={isSearchingCustomer}
              error={searchError}
              disabled={disabled}
              placeholder={formatMessage(messages.searchPlaceholder)}
            />
          )}
          {showDropdown && !selectedCustomer && (
            <CapRow useLegacy className="search-dropdown-container">
              <CapRow type="flex" justify="center" align="middle">
                {(processedSearchData?.length === 0 && customerSearchValue != null && !isSearchingCustomer) && (
                  <CapCard className="validation-card">
                    <CapHeading type="h6">
                      {formatMessage(messages.noCustomersFound)}
                    </CapHeading>
                  </CapCard>
                )}
                {(isSearchingCustomer) && (
                  <CapCard className="validation-card">
                    <CapRow useLegacy className="spin-card-align">
                      <CapSpin />
                    </CapRow>
                  </CapCard>
                )}
              </CapRow>
              <CapRow type="flex" justify="center" align="middle">
                {processedSearchData?.length > 0 && (
                  <CapCard className="search-result-card scroll-bar">
                    {
                      <CapRow className="identifier-row">
                        {processedSearchData?.map((d) => (
                          <>
                            <CapLink
                              key={d?.customerId}
                              className="search-results-height link-result"
                              title={(
                                <>
                                  <CapRow type="flex" align="middle" gap={16}>
                                    <CapColumn data-testid="namingIcon">
                                      <CapRow className="customer-common-profile">{getNamingIcon(d?.name)}</CapRow>
                                    </CapColumn>
                                    <CapColumn>
                                      <CapRow type="flex" gap={12}>
                                        <CapColumn data-testid="searchResultName">
                                          <CapHeading className="search-text" type="h4">
                                            {d?.name}
                                          </CapHeading>
                                        </CapColumn>
                                      </CapRow>
                                      {(
                                        <CapRow type="flex">
                                          {showIdentifiers(d?.identifiers)}
                                        </CapRow>
                                      )}
                                    </CapColumn>
                                  </CapRow>
                                </>
                              )}
                              onClick={() => handleCustomerSelectItem(d)}
                            />
                          </>
                        ))}
                      </CapRow>
                    }
                  </CapCard>
                )}
              </CapRow>
            </CapRow>
          )}
        </CapRow>
      </div>
    </CapRow>
  );
};

// Search Input Component
const SearchInput = ({
  value,
  onChange,
  isLoading,
  error,
  disabled,
  placeholder,
}) => (
  <CapRow useLegacy className="search-input-container">
    <CapInput
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      disabled={disabled || isLoading}
      status={error ? 'error' : undefined}
      allowClear
      autoComplete="off"
    />
    {error && (
      <CapRow useLegacy className="search-error">
        <CapAlert
          message={error}
          type="error"
          size="small"
          showIcon
        />
      </CapRow>
    )}
  </CapRow>
);

const SelectedCustomerView = ({ customer, onClear, showIdentifiers }) => (
  <div className="selected-customer-view">
    <CapRow type="flex" align="middle" gap={8}>
      <CapColumn>
        <CapRow className="customer-common-profile">{getNamingIcon(customer?.name)}</CapRow>
      </CapColumn>
      <CapColumn>
        <CapHeading className="search-text" type="h4">
          {customer.name}
        </CapHeading>
      </CapColumn>
      <CapColumn>
        <CapLabel type="label1" className="identifier-desc">
          {showIdentifiers(customer?.identifiers)}
        </CapLabel>
      </CapColumn>
    </CapRow>
    <CapIcon size="s" type="close" className="clear-icon" onClick={onClear} />
  </div>
);

SelectedCustomerView.propTypes = {
  customer: PropTypes.object.isRequired,
  onClear: PropTypes.func.isRequired,
  showIdentifiers: PropTypes.func.isRequired,
};

SearchInput.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
  isLoading: PropTypes.bool,
  error: PropTypes.string,
  disabled: PropTypes.bool,
  placeholder: PropTypes.string.isRequired,
};
SearchInput.defaultProps = {
  value: '',
  onChange: () => {},
  isLoading: false,
  error: null,
  disabled: false,
};

CustomerSearchSection.propTypes = {
  onCustomerSelect: PropTypes.func.isRequired,
  onSearch: PropTypes.func.isRequired,
  onClearSearch: PropTypes.func.isRequired,
  onClearSelection: PropTypes.func.isRequired,
  customers: PropTypes.array,
  isSearchingCustomer: PropTypes.bool,
  searchError: PropTypes.string,
  selectedCustomer: PropTypes.object,
  hasSearched: PropTypes.bool,
  disabled: PropTypes.bool,
  intl: PropTypes.object.isRequired,
};

CustomerSearchSection.defaultProps = {
  customers: [],
  isSearchingCustomer: false,
  searchError: null,
  selectedCustomer: null,
  hasSearched: false,
  disabled: false,
};

export default injectIntl(CustomerSearchSection);
