"use client";

import { ContactRecord } from "@/app/data";
import Form from "next/form";
import { use } from "react";
import { useRouter } from "next/navigation";

export default function Contact({
  contact
}: {
  contact: Promise<ContactRecord>
}) {
  const c = use(contact);
  const router = useRouter();

  return (
    <div id="contact">
      <div>
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          alt={`${c.first} ${c.last} avatar`}
          key={c.avatar}
          src={c.avatar}
        />
      </div>

      <div>
        <h1>
          {c.first || c.last ? (
            <>
              {c.first} {c.last}
            </>
          ) : (
            <i>No Name</i>
          )}
          <Favorite contact={c}/>
        </h1>

        {c.twitter ? (
          <p>
            <a
              href={`https://twitter.com/${c.twitter}`}
            >
              {c.twitter}
            </a>
          </p>
        ) : null}

        {c.notes ? <p>{c.notes}</p> : null}

        <div>
          <button
            type="button"
            onClick={() => router.push(`/contacts/${c.id}/edit`)}
          >
            Edit
          </button>

          <Form
            action="destroy"
            formMethod="post"
            onSubmit={(event) => {
              const response = confirm(
                "Please confirm you want to delete this record."
              );
              if (!response) {
                event.preventDefault();
              }
            }}
          >
            <button type="submit">Delete</button>
          </Form>
        </div>
      </div>
    </div>
  );
}

function Favorite({
  contact,
}: {
  contact: Pick<ContactRecord, "favorite">;
}) {
  const favorite = contact.favorite;

  return (
    <Form action="." formMethod="post">
      <button
        aria-label={
          favorite
            ? "Remove from favorites"
            : "Add to favorites"
        }
        name="favorite"
        value={favorite ? "false" : "true"}
      >
        {favorite ? "★" : "☆"}
      </button>
    </Form>
  );
}