import { createFileRoute, Link, Outlet } from '@tanstack/react-router';
import { getContacts } from "@/data";

async function fetchContacts() {
  const contacts = await getContacts();
  return { contacts };
}

export const Route = createFileRoute('/_sidebar')({
  component: Sidebar,
  loader: fetchContacts,
  notFoundComponent: () => <div>Not Found</div>,
});

function Sidebar() {
  const loaderData = Route.useLoaderData();
  if (loaderData === undefined) {
    console.log("SIDEBAR ERROR!?");
    return (
      <>
        <div id="sidebar">UNDEFINED LOADER DATA IN SIDEBAR</div>
        <div id={'detail'}>
          <Outlet/>
        </div>
      </>
    );
  }
  const { contacts } = loaderData;

  return (
    <>
      <div id="sidebar">
        <h1>
          <Link to="/about">TanStack Start Contacts</Link>
        </h1>
        <div>
          <form id="search-form" role="search">
            <input
              aria-label="Search contacts"
              id="q"
              name="q"
              placeholder="Search"
              type="search"
            />
            <div aria-hidden hidden={true} id="search-spinner"/>
          </form>
          <form method="post">
            <button type="submit">New</button>
          </form>
        </div>
        <nav>
          {contacts.length ? (
            <ul>
              {contacts.map((contact) => (
                <li key={contact.id}>
                  <Link to="/contacts/$contactId" params={{ contactId: contact.id }}>
                    {contact.first || contact.last ? (
                      <>
                        {contact.first} {contact.last}
                      </>
                    ) : (
                      <i>No Name</i>
                    )}
                    {contact.favorite ? (
                      <span>★</span>
                    ) : null}
                  </Link>
                </li>
              ))}
            </ul>
          ) : (
            <p>
              <i>No contacts</i>
            </p>
          )}
        </nav>
      </div>
      <div id={'detail'}>
        <Outlet/>
      </div>
    </>
  );
}