import { useState } from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { collection, doc, writeBatch } from "firebase/firestore";

import { AppLayout } from "@/components/AppLayout";
import { Button } from "@/components/ui/button";
import { GroupsProvider } from "@/context/GroupsContext";
import { CONNECTORS_SEED } from "@/data/connectorsSeed";
import { db } from "@/lib/firebase";
import { CompartmentPage } from "@/pages/CompartmentPage";
import { GroupPage } from "@/pages/GroupPage";
import { HomePage } from "@/pages/Home";
import { PlaceholderPage } from "@/pages/PlaceholderPage";
import { NewPage } from "@/pages/NewPage";

const router = createBrowserRouter([
  {
    path: "/",
    element: <AppLayout />,
    children: [
      { index: true, element: <HomePage /> },
      { path: "groups/:groupId", element: <GroupPage /> },
      {
        path: "groups/:groupId/compartments/:compartmentId",
        element: <CompartmentPage />,
      },
      { path: "search", element: <PlaceholderPage title="Search" /> },
      { path: "new", element: <NewPage /> },
      { path: "account", element: <PlaceholderPage title="Account" /> },
      { path: "settings", element: <PlaceholderPage title="Settings" /> },
    ],
  },
]);

const CONNECTORS_COLLECTION = "connectors";

export function ConnectorsSeedControl() {
  const [busy, setBusy] = useState(false);
  const [notice, setNotice] = useState("");

  async function insertConnectors() {
    if (
      !window.confirm(
        `Insert ${CONNECTORS_SEED.length} new documents into Firestore collection "${CONNECTORS_COLLECTION}"? Each run creates new document IDs (duplicates if you run again).`,
      )
    ) {
      return;
    }

    setBusy(true);
    setNotice("");
    try {
      const col = collection(db, CONNECTORS_COLLECTION);
      const batch = writeBatch(db);
      for (const row of CONNECTORS_SEED) {
        batch.set(doc(col), { ...row });
      }
      await batch.commit();
      setNotice(`Inserted ${CONNECTORS_SEED.length} rows.`);
    } catch (e) {
      setNotice(
        e instanceof Error ? e.message : "Failed to write to Firestore.",
      );
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="fixed right-4 bottom-24 z-50 flex max-w-xs flex-col gap-2 rounded-lg border border-border bg-background/95 p-3 shadow-md backdrop-blur-sm">
      <p className="text-xs text-muted-foreground">
        Local only: push rows from{" "}
        <code className="text-foreground">connectorsSeed.ts</code> into{" "}
        <code className="text-foreground">{CONNECTORS_COLLECTION}</code>.
      </p>
      <Button
        type="button"
        size="sm"
        variant="secondary"
        disabled={busy}
        onClick={() => void insertConnectors()}
      >
        {busy ? "Inserting…" : "Insert connectors"}
      </Button>
      {notice ? (
        <p className="text-xs text-muted-foreground wrap-break-word">
          {notice}
        </p>
      ) : null}
    </div>
  );
}

function App() {
  return (
    <GroupsProvider>
      {/* {import.meta.env.DEV ? <ConnectorsSeedControl /> : null} */}
      <RouterProvider router={router} />
    </GroupsProvider>
  );
}

export default App;
