"use client";

import { useFormState } from "react-dom";
import { addSong, searchSongs } from "./actions";

export default function SearchForm({
  className,
}: {
  className?: string | undefined;
}) {
  const [items, dispatch] = useFormState(searchSongs, []);
  const [_, dispatchAdd] = useFormState(addSong, undefined);
  return (
    <form className={className} action={dispatch}>
      <input
        name="name"
        type="text"
        placeholder="Search songs..."
        className="w-full border rounded-md px-4 py-2"
      />
      {items ? (
        <div className="bg-white rounded shadow-md p-4">
          {items.map((item) => (
            <div
              className="flex justify-between items-center py-2 border-b"
              key={item.id}
            >
              <span>
                {item.name} - {item.artist}
              </span>
              <button
                className="text-green-500 hover:text-green-700"
                onClick={() => {
                  dispatchAdd(item);
                }}
              >
                添加
              </button>
            </div>
          ))}
        </div>
      ) : null}
    </form>
  );
}
