import { createFileRoute } from "@tanstack/react-router";
import { pb } from "@/lib/pocketbase";
import { useState } from "react";
import { RelationshipType, type Secret, type Session } from "@/lib/types";
import { RelationshipList } from "@/components/RelationshipList";
import { SessionForm } from "@/components/documents/session/SessionForm";

export const Route = createFileRoute("/_authenticated/document/$documentId")({
  loader: async ({ params }) => {
    const doc = await pb.collection("documents").getOne(params.documentId);
    return { document: doc };
  },
  component: RouteComponent,
});

function RouteComponent() {
  const { document: session }: { document: Session } = Route.useLoaderData();
  const [newSecret, setNewSecret] = useState("");
  const [adding, setAdding] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSaveSession(data: Session["data"]) {
    await pb.collection("documents").update(session.id, {
      data,
    });
  }

  return (
    <div className="max-w-xl mx-auto py-8">
      <SessionForm session={session as Session} onSubmit={handleSaveSession} />
      <RelationshipList
        root={session}
        relationshipType={RelationshipType.Secrets}
        renderRow={(secret) => (
          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              checked={!!(secret.data as any)?.secret?.discovered}
              onChange={async (e) => {
                const checked = e.target.checked;
                await pb.collection("documents").update(secret.id, {
                  data: {
                    ...secret.data,
                    secret: {
                      ...(secret.data as any).secret,
                      discovered: checked,
                    },
                  },
                });
                // Remove any existing discoveredIn relationship
                const rels = await pb
                  .collection("relationships")
                  .getList(1, 1, {
                    filter: `primary = "${secret.id}" && type = "discoveredIn"`,
                  });
                if (rels.items.length > 0) {
                  await pb.collection("relationships").delete(rels.items[0].id);
                }
                if (checked) {
                  await pb.collection("relationships").create({
                    primary: secret.id,
                    secondary: [session.id],
                    type: "discoveredIn",
                  });
                }
              }}
              className="accent-emerald-500 w-5 h-5"
              aria-label="Discovered"
            />
            <span>
              {(secret.data as any)?.secret?.text || (
                <span className="italic text-slate-400">(No secret text)</span>
              )}
            </span>
          </div>
        )}
        newItemForm={(onCreate) => (
          <form
            className="flex items-center gap-2 mt-4"
            onSubmit={async (e) => {
              e.preventDefault();
              if (!newSecret.trim()) return;
              setAdding(true);
              setError(null);
              try {
                console.debug("Creating new secret");
                // Create the secret document
                const secretDoc: Secret = await pb
                  .collection("documents")
                  .create({
                    campaign: session.campaign,
                    data: {
                      secret: {
                        text: newSecret,
                        discovered: false,
                      },
                    },
                  });
                setNewSecret("");
                await onCreate(secretDoc);
              } catch (e: any) {
                setError(e?.message || "Failed to add secret.");
              } finally {
                setAdding(false);
              }
            }}
          >
            <input
              type="text"
              className="flex-1 px-3 py-2 rounded bg-slate-800 text-slate-100 border border-slate-700 focus:outline-none focus:ring-2 focus:ring-violet-500"
              placeholder="Add a new secret..."
              value={newSecret}
              onChange={(e) => setNewSecret(e.target.value)}
              disabled={adding}
            />
            {error && <div className="text-red-400 mt-2 text-sm">{error}</div>}
            <button
              type="submit"
              className="px-4 py-2 rounded bg-emerald-600 hover:bg-emerald-700 text-white font-semibold transition-colors disabled:opacity-60"
              disabled={adding || !newSecret.trim()}
            >
              {adding ? "Adding..." : "Add Secret"}
            </button>
          </form>
        )}
      />
    </div>
  );
}
