"use client";

import { useEffect, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";
import {
  Loader2,
  AlertCircle,
  ChevronDown,
  ChevronRight,
  Database,
  CircleDot,
} from "lucide-react";
import { DatabaseTableTree } from "@/components/project/database-table-tree";
import { TableViewer } from "@/components/project/table-viewer";
import { useAnatomy } from "@/components/project/use-anatomy";

type Selection = {
  kind: "table";
  dbUuid: string;
  schema: string;
  name: string;
} | null;

export default function DataTablesPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const projectId = params.projectId as string;
  const targetDbId = searchParams.get("db");

  const { anatomy, loading, error } = useAnatomy(projectId);

  const databases = anatomy?.infrastructure?.databases ?? [];

  // If targetDbId is in the URL, only show that database.
  // Otherwise, default to the first database in the list if available.
  const activeDbId =
    targetDbId || (databases.length > 0 ? databases[0].uuid : null);
  const activeDatabases = databases.filter((db) => db.uuid === activeDbId);

  const [selection, setSelection] = useState<Selection>(null);

  useEffect(() => {
    setSelection(null);
  }, [projectId, targetDbId]);

  const showLoading = loading && !anatomy;

  return (
    <div style={pageWrap}>
      <div style={grid}>
        {/* ── Left rail ── */}
        <section style={leftCol}>
          {showLoading && (
            <Inline>
              <Loader2 size={13} className="animate-spin" /> Loading…
            </Inline>
          )}
          {error && !showLoading && (
            <Inline>
              <AlertCircle size={13} /> {error}
            </Inline>
          )}

          {anatomy && (
            <RailGroup title="Databases" count={activeDatabases.length}>
              {activeDatabases.length === 0 && (
                <RailEmpty>
                  No databases yet.
                  <span style={nudge}>
                    Try: &quot;Add a Postgres database to my project&quot;
                  </span>
                </RailEmpty>
              )}
              {activeDatabases.map((db) => {
                return (
                  <article key={db.uuid} style={codebaseTile}>
                    <div style={tileHeader}>
                      <span style={chevronCell}>
                        <ChevronDown size={13} style={{ color: INK.mid }} />
                      </span>
                      <Database
                        size={13}
                        style={{ color: INK.mid, flexShrink: 0 }}
                      />
                      <div style={{ minWidth: 0, textAlign: "left", flex: 1 }}>
                        <div style={tileLabel}>{db.name}</div>
                        <div style={tileHint}>{db.type}</div>
                      </div>
                      <CircleDot
                        size={9}
                        style={{ color: statusColor(db.status), flexShrink: 0 }}
                      />
                    </div>
                    <div style={tileBody}>
                      <DatabaseTableTree
                        projectId={projectId}
                        dbUuid={db.uuid}
                        selectedTable={
                          selection?.kind === "table" &&
                          selection.dbUuid === db.uuid
                            ? {
                                schema: selection.schema,
                                name: selection.name,
                              }
                            : undefined
                        }
                        onSelectTable={({ schema, name }) =>
                          setSelection({
                            kind: "table",
                            dbUuid: db.uuid,
                            schema,
                            name,
                          })
                        }
                      />
                    </div>
                  </article>
                );
              })}
            </RailGroup>
          )}
        </section>

        {/* ── Right pane ── */}
        <aside style={rightCol}>
          <h3 style={heading}>{paneHeading(selection)}</h3>
          <div style={panel}>
            {selection?.kind === "table" && (
              <TableViewer
                projectId={projectId}
                dbUuid={selection.dbUuid}
                schema={selection.schema}
                table={selection.name}
              />
            )}
            {!selection && (
              <Empty>Select a table on the left to preview data.</Empty>
            )}
          </div>
        </aside>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────
// Bits
// ──────────────────────────────────────────────────

function RailGroup({
  title,
  count,
  children,
}: {
  title: string;
  count: number;
  children: React.ReactNode;
}) {
  return (
    <div style={railGroup}>
      <header style={railGroupHeader}>
        <span style={railGroupTitle}>{title}</span>
        <span style={countPill}>{count}</span>
      </header>
      <div style={railItems}>{children}</div>
    </div>
  );
}

function RailEmpty({ children }: { children: React.ReactNode }) {
  return <div style={railEmpty}>{children}</div>;
}

function Inline({ children }: { children: React.ReactNode }) {
  return (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        gap: 8,
        padding: "12px 14px",
        fontSize: "0.82rem",
        color: INK.mid,
        background: INK.cardBg,
        border: `1px solid ${INK.borderSoft}`,
        borderRadius: 8,
      }}
    >
      {children}
    </div>
  );
}

function Empty({ children }: { children: React.ReactNode }) {
  return (
    <div
      style={{
        flex: 1,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color: INK.mid,
        fontSize: "0.85rem",
        padding: "32px 16px",
        textAlign: "center",
      }}
    >
      {children}
    </div>
  );
}

function paneHeading(s: Selection): string {
  if (!s) return "Preview";
  if (s.kind === "table")
    return `Preview · ${s.schema === "public" ? s.name : `${s.schema}.${s.name}`}`;
  return "Preview";
}

function statusColor(status: string) {
  const s = (status ?? "").toLowerCase();
  if (s.includes("running") || s.includes("healthy")) return "#2e7d32";
  if (s.includes("starting") || s.includes("deploying")) return "#d4a04a";
  if (s.includes("exit") || s.includes("fail") || s.includes("unhealthy"))
    return "#c5392b";
  return "#a09a90";
}

// ──────────────────────────────────────────────────
// Tokens
// ──────────────────────────────────────────────────

const INK = {
  ink: "#1a1a1a",
  mid: "#5f5e5a",
  muted: "#a09a90",
  border: "#e8e4dc",
  borderSoft: "#efebe1",
  cardBg: "#fff",
  fontSans: '"Outfit", "Inter", ui-sans-serif, sans-serif',
} as const;

const pageWrap: React.CSSProperties = {
  padding: "28px 48px 48px",
  fontFamily: INK.fontSans,
  color: INK.ink,
};
const grid: React.CSSProperties = {
  display: "grid",
  gridTemplateColumns: "minmax(280px, 360px) minmax(0, 1fr)",
  gap: 28,
  maxWidth: 1400,
  margin: "0 auto",
  alignItems: "stretch",
};
const leftCol: React.CSSProperties = {
  minWidth: 0,
  display: "flex",
  flexDirection: "column",
  gap: 18,
};
const rightCol: React.CSSProperties = {
  minWidth: 0,
  display: "flex",
  flexDirection: "column",
};
const heading: React.CSSProperties = {
  fontSize: "0.72rem",
  fontWeight: 600,
  letterSpacing: "0.12em",
  textTransform: "uppercase",
  color: INK.muted,
  margin: "0 0 14px",
};
const railGroup: React.CSSProperties = {
  display: "flex",
  flexDirection: "column",
};
const railGroupHeader: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  padding: "0 4px 8px",
};
const railGroupTitle: React.CSSProperties = {
  fontSize: "0.68rem",
  fontWeight: 600,
  letterSpacing: "0.12em",
  textTransform: "uppercase",
  color: INK.muted,
};
const countPill: React.CSSProperties = {
  fontSize: "0.7rem",
  fontWeight: 600,
  color: INK.mid,
  padding: "1px 7px",
  borderRadius: 999,
  background: "#f3eee4",
};
const railItems: React.CSSProperties = {
  display: "flex",
  flexDirection: "column",
  gap: 10,
};
const railEmpty: React.CSSProperties = {
  padding: "10px 12px",
  fontSize: "0.74rem",
  color: INK.muted,
  border: `1px dashed ${INK.borderSoft}`,
  borderRadius: 8,
  lineHeight: 1.6,
};
const nudge: React.CSSProperties = {
  display: "block",
  marginTop: 6,
  fontStyle: "normal",
  background: "#f3eee4",
  borderRadius: 4,
  padding: "3px 8px",
  fontSize: "0.72rem",
  color: "#7a6a50",
};
const codebaseTile: React.CSSProperties = {
  background: INK.cardBg,
  border: `1px solid ${INK.borderSoft}`,
  borderRadius: 10,
  overflow: "hidden",
};
const tileHeader: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  gap: 8,
  width: "100%",
  padding: "12px 14px",
  background: "transparent",
  border: "none",
  font: "inherit",
  color: "inherit",
};
const tileLabel: React.CSSProperties = {
  fontSize: "0.85rem",
  fontWeight: 600,
  color: INK.ink,
  marginBottom: 2,
};
const tileHint: React.CSSProperties = {
  fontSize: "0.74rem",
  color: INK.mid,
  lineHeight: 1.4,
  textTransform: "capitalize",
};
const tileBody: React.CSSProperties = {
  padding: "8px 10px 12px",
  borderTop: `1px solid ${INK.borderSoft}`,
};
const chevronCell: React.CSSProperties = {
  width: 14,
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "center",
  flexShrink: 0,
};
const panel: React.CSSProperties = {
  background: INK.cardBg,
  border: `1px solid ${INK.border}`,
  borderRadius: 10,
  padding: 16,
  flex: 1,
  minHeight: 0,
  display: "flex",
  flexDirection: "column",
};
