import { CreateOrganization, SignIn } from "@clerk/tanstack-start";
import { getAuth } from "@clerk/tanstack-start/server";
import {
  createFileRoute,
  Link,
  RouteApi,
  useRouter,
} from "@tanstack/react-router";
import { createServerFn, useServerFn } from "@tanstack/start";
import { Button, Form, Input, Modal } from "antd";
import { set } from "lodash";
import { WithId } from "mongodb";
import { useState } from "react";
import GeneralHeader from "~/components/GeneralHeader";
import { getServerContext } from "~/db/getdb";
import { Application } from "~/db/schema";

const fetchApps = createServerFn("GET", async (_, ctx) => {
  const { db, user } = await getServerContext();

  const apps = db
    .collection<Application>("apps")
    .find({ owner: user.userId })
    .toArray();
  return apps;
});

const createApp = createServerFn("POST", async (appData: Application) => {
  const { db, user } = await getServerContext();

  const apps = db
    .collection("apps")
    .insertOne({ ...appData, owner: user.userId });
  return apps;
});
const deleteApp = createServerFn("POST", async (appData: WithId<Application>) => {
  const { db, user } = await getServerContext();

  const apps = db
    .collection("apps")
    .deleteOne({ _id: appData._id });
  return apps;
});

export const Route = createFileRoute("/_authed/dashboard")({
  component: Dashboard,
  loader: () => {
    return fetchApps();
  },
});

function Dashboard() {
  const apps = Route.useLoaderData();
  const router = useRouter();
  const addApplication = useServerFn(createApp);
  const [isModalVisible, setIsModalVisible] = useState(false);
  async function add() {}
  const [form] = Form.useForm();
  return (
    <>
      <Modal
        title="Create App"
        onCancel={() => setIsModalVisible(false)}
        open={isModalVisible}
        onOk={() => form.submit()}
      >
        <Form
          form={form}
          onFinish={(data) => {
            addApplication({
              displayName: data.displayName,
              owner: "ToBeReplaced",
              ownerType: "USER",
            }).then(() => {
              setIsModalVisible(false);
              router.invalidate();
            });
          }}
        >
          <Form.Item label="App Name" name="displayName">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <GeneralHeader />
      <div className="max-w-xl font-mono m-auto mt-52">
        <h1 className="text-3xl ">Apps</h1>
        <ul className="flex gap-y-3 flex-wrap mt-2">
          {apps.map((app) => (
            <li
              className="border-2 mr-2 rounded-sm w-24 border-gray-800 aspect-square p-4 inline-flex hover:bg-gray-800 hover:text-white"
              key={app._id + ""}
            >
              <Link to={`/apps/${app._id}`}>
                {app.displayName ?? "New App asdfasdf"}
              </Link>
            </li>
          ))}
          <li className="border-2 mr-2 rounded-sm w-24 border-gray-800 aspect-square p-4 inline-flex  hover:bg-gray-800 hover:text-white">
            <button
              className="aspect-square"
              onClick={() => setIsModalVisible(true)}
            >
              +
            </button>
          </li>
        </ul>
      </div>
    </>
  );
}
