import React, { useEffect, useRef, useState } from 'react';
import { useRegionalizationContext } from '../context/RegionalizationContext';
import { Title } from '../components/Title';
import { PickupPoint } from '../components/PickupPoint';
import { PikcupPointType } from '../types/PikcupPointType';
import { Glass } from '../assets/Icons/Glass';
import { SetViewButton } from '../components/SetView';
import { Arrow } from '../assets/Icons/Arrow';

export const AllStoresScreen = () => {
  const { pickup, pickupPoints, textBackButton } = useRegionalizationContext();
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [filteredStores, setFilteredStores] =
    useState<PikcupPointType[]>(pickupPoints);

  useEffect(() => {
    setFilteredStores(pickupPoints);
  }, [pickupPoints]);

  const handleFilterStores = () => {
    setFilteredStores(
      pickupPoints.filter(({ name }) =>
        name.toLowerCase().includes(inputRef.current?.value.toLowerCase() ?? '')
      )
    );
  };

  return (
    <>
      <Title title={pickup?.title} />
      <div className="stores-filter">
        <p>{pickup?.labelFilter}</p>

        <div>
          <input
            type="text"
            placeholder="Loja"
            ref={inputRef}
            onKeyDown={(e) => e.key === 'Enter' && handleFilterStores()}
          />
          <button
            className="filter-ico-container"
            onClick={() => handleFilterStores()}
          >
            <Glass />
          </button>
        </div>

        <div className="divider">
          <span>{pickup?.divider}</span>
        </div>
      </div>
      <p className="stores-label">{pickup?.labelStores}</p>
      <div className="stores-container">
        {filteredStores.map((pickupPointInfos) => (
          <PickupPoint
            key={pickupPointInfos.id}
            pickupPointInfos={pickupPointInfos}
          />
        ))}
      </div>
      <br></br>
      <SetViewButton
        view="PostalCodeInputScreen"
        className="back-button-all-store"
      >
        <span>
          <Arrow />
        </span>
        {textBackButton}
      </SetViewButton>
    </>
  );
};
