import { getSession } from "~/sessions";
import { getMe } from "~/utils";
import { Link, useLoaderData } from "@remix-run/react";
import { prisma } from "~/db.server";
import { Form } from "@remix-run/react";
import { json } from "@remix-run/node";

const countys = [
  "Ahvenanmaa",
  "Etelä-Karjala",
  "Etelä-Pohjanmaa",
  "Kainuu",
  "Kanta-Häme",
  "Keski-Pohjanmaa",
  "Keski-Suomi",
  "Kymenlaakso",
  "Lappi",
  "Pirkanmaa",
  "Pohjanmaa",
  "Pohjois-Karjala",
  "Pohjois-Pohjanmaa",
  "Pohjois-Savo",
  "Päijat-Häme",
  "Satakunta",
  "Uusimaa",
  "Varsinais-Suomi",
];

export async function action({ request }) {
  const formData = await request.formData();
  const county = formData.get("county");

  if (!county || typeof county !== "string" || !countys.includes(county))
    throw new Error("bad county");

  const session = await getSession(request.headers.get("Cookie"));
  if (!session.has("userId"))
    throw new Error("OAuth token not found in cookie");

  const me = await getMe(session.get("userId"));

  const countySubmit = prisma.county.upsert({
    where: {
      name: county,
    },
    update: {
      players: {
        create: {
          playerName: me.username,
          rank: parseInt(me.statistics.global_rank),
        },
      },
    },
    create: {
      name: county,
      players: {
        create: {
          playerName: me.username,
          rank: parseInt(me.statistics.global_rank),
        },
      },
    },
  });

  return countySubmit
    ? json(countySubmit)
    : new Error("Something went wrong with creating the user");
}

export async function loader({ request }) {
  const countyData = await prisma.county.findMany({
    include: {
      players: {
        orderBy: {
          rank: "asc",
        },
      },
    },
  });
  const session = await getSession(request.headers.get("Cookie"));
  if (!session.has("userId")) return json({ countyData });

  const me = await getMe(session.get("userId"));

  const selfData = await prisma.player.findUnique({
    where: {
      playerName: me.username,
    },
  });

  return json({ me, countyData, selfData });
}

export default function Index() {
  const data = useLoaderData();

  return (
    <div className="container mx-auto flex min-h-screen flex-col">
      <header className="flex w-full flex-col items-center justify-between rounded-b-2xl border-b bg-slate-50 px-12 py-4 text-center md:flex-row">
        <h1 className="text-2xl tracking-tighter">Maakunta ranking</h1>
        {data.me ? (
          <div className="flex flex-col items-center justify-center">
            <img
              className="w-10 rounded-full outline"
              src={data.me.avatar_url}
              alt=""
            />
            <h1>{data.me.username}</h1>
            <Link
              className="text-sky-400 hover:text-sky-600 hover:underline"
              to={"/logout"}
            >
              Logout
            </Link>
          </div>
        ) : (
          <a
            href="https://osu.ppy.sh/oauth/authorize?client_id=20031&redirect_uri=http://localhost:3000/auth&response_type=code"
            referrerPolicy="noreferrer"
            className="rounded-full border bg-red-300 px-4 py-2 font-semibold shadow-lg hover:bg-red-400"
          >
            Authenticate with OSU account
          </a>
        )}
      </header>
      {data?.me?.username ? (
        data.selfData ? (
          <h1 className="p-4 text-center font-bold">
            Kiitos, että osallistuit maakunta rankingiin!
          </h1>
        ) : (
          <Form
            className="flex flex-col items-center justify-center space-y-4 p-4 text-center"
            method="post"
          >
            <label>
              <details>
                <summary className="cursor-pointer text-2xl font-semibold tracking-wide">
                  Valitse sinun tämän hetkinen maakunta
                </summary>
                <p className="text-sm">
                  Jos laitat vahingos väärän tai jotai nii pingaa juunas hyväs
                  mieles nii voin vaihtaa joo
                </p>
              </details>
            </label>
            <select
              className="rounded bg-white p-2 shadow"
              name="county"
              id="county"
            >
              {countys.map((county, index) => (
                <option key={index} value={`${county}`}>
                  {county}
                </option>
              ))}
            </select>
            <button
              className="rounded-full px-4 py-2 shadow hover:shadow-xl"
              type="submit"
            >
              Submit
            </button>
          </Form>
        )
      ) : (
        ""
      )}
      {data.countyData.length > 0 ? (
        <ul className="flex flex-grow flex-col items-center justify-center p-4 md:flex-row">
          {data.countyData.map((county) => (
            <li
              className="m-4 flex w-full max-w-md flex-col space-y-2 rounded border p-4 text-black shadow-lg"
              key={county.id}
            >
              <h1 className="text-center text-4xl tracking-tighter">
                {county.name}
              </h1>
              <table className="w-full text-left">
                <thead>
                  <tr className="border-b">
                    <th className="p-2">Player</th>
                    <th className="p-2">Rank</th>
                  </tr>
                </thead>
                <tbody>
                  {county.players.map((player) => (
                    <tr
                      key={player.id}
                      className="border-b odd:bg-slate-50 even:bg-white"
                    >
                      <td className="p-2">{player.playerName}</td>
                      <td className="p-2">#{player.rank}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </li>
          ))}
        </ul>
      ) : (
        <h1 className="flex-grow p-6 text-center text-4xl">No data yet</h1>
      )}
    </div>
  );
}
