import {actionPromise} from "../../reducers";
import {gql} from "../../actions";
import {useState} from "react";
import {Link} from "react-router-dom";
import {connect} from "react-redux";
import {CTrack} from "../track";

const actionTrackSearch = (word) => (
    actionPromise('trackFind', gql(`query trackById($q: String) {
      TrackFind(query: $q) {
          _id url originalFileName
      }
  }`, {q: JSON.stringify([
                {
                    $or: [{originalFileName: `/${word}/`}]
                },
                {
                    sort: [{originalFileName: 1}]
                }
            ])
        }
    ))
)


const TrackSearch = ({ onSearch }) => {
    const [value, setValue] = useState("");
    return (
        <div>
            <input
                type="text"
                placeholder="Поиск..."
                value={value}
                onChange={(e) => setValue(e.target.value)}
            />
            <Link to="/search">
                <button onClick={() => onSearch(value)}>Найти</button>
            </Link>
        </div>
    );
};

export const CTrackSearch = connect(null,{onSearch:actionTrackSearch})(TrackSearch)

const SearchResult = ({ trackFind }) => {
    return (
        <>
            {trackFind.map((track) => (
                <CTrack trackP={track} />
            ))}
        </>
    );
};
export const CSearchResult = connect((state) => ({
    trackFind: state.promise.trackFind?.payload || [],
}))(SearchResult);