import { Link } from "react-router-dom";
import { actionSearch } from "../actions/actionSearch";
import { connect } from "react-redux";
import { useState } from "react";

const Search = ({onSearch , snippets}) => {
    const [request, setRequest] = useState('');
  return (
    <>
      <Link to="/">
          <button className="float-left btn-secondary d-inline-block mt-2 ml-2">
              <span>&#8617;</span>Back to Main Page
          </button>
      </Link>
        <br/>
        <br/>
        <div style ={{textAlign: "center" , alignItems:"center", justifyContent:'center'}}>
        <input value={request} onChange={(e) => setRequest(e.target.value)} className="form-control d-inline-block w-50 mt-2"
        type="search" placeholder="Name of project" aria-label="Search"
        />
      <br/>
      <button
        className="btn btn-outline-success border-success mt-4 mb-4" onClick = {() => onSearch(request)}
      >
        Search
      </button>
    </div>

  {snippets?.map((key, index) => (
    <div style={{ textAlign: "center", alignItems: "center" }}>
      <div className="card w-50 ml-auto mr-auto mt-3 mb-5">
        <div className="card-body" style={{ textAlign: "center" }}>
          <h3 className="card-title mb-4 text-info">
            {snippets?.[index]?.title || "Project without name"}
          </h3>
          <p className="card-text">
            <span className="text-muted">Description</span>&nbsp;
            {snippets?.[index]?.description || ""}
          </p>
          <p>{`Owner: ${snippets?.[index]?.owner?.login}`}</p>
          <Link to={"/project/" + snippets?.[index]?._id}>
            <button className="btn btn-primary mt-3">Open project</button>
          </Link>
        </div>
      </div>
    </div>
  ))}
</>
  )
};

const CSearch = connect(state => ({snippets:state?.promise?.searchSnippet?.payload?.data?.SnippetFind}) , {onSearch:actionSearch})(Search)

export default CSearch;
