"use client";

import { TableMetadata } from "@/app/lib/api";

type Props = {
  tables: TableMetadata[];
  selectedTable?: TableMetadata | null;
  loading: boolean;
  error?: string | null;
  onSelect: (table: TableMetadata) => void;
};

export default function TableExplorerSidebar({
  tables,
  selectedTable,
  loading,
  error,
  onSelect,
}: Props) {
  return (
    <section className="flex flex-col gap-4 rounded-2xl border border-white/10 bg-white/5 p-4 shadow-md shadow-black/30 backdrop-blur">
      <div>
        <h2 className="text-base font-semibold uppercase tracking-wide text-zinc-300">
          Tables
        </h2>
        <p className="text-xs text-zinc-500">
          Browse available schemas and pick a table to explore.
        </p>
      </div>
      {loading && (
        <div className="text-sm text-zinc-400">Loading tables …</div>
      )}
      {error && (
        <div className="rounded-md bg-red-500/20 p-2 text-xs text-red-200">
          {error}
        </div>
      )}
      <div className="flex-1 space-y-2 overflow-y-auto">
        {tables.map((table) => {
          const isSelected = table.table_name === selectedTable?.table_name;
          return (
            <button
              key={`${table.table_schema ?? "public"}.${table.table_name}`}
              onClick={() => onSelect(table)}
              className={`w-full rounded-xl border px-3 py-2 text-left transition ${
                isSelected
                  ? "border-cyan-500 bg-cyan-500/10 text-cyan-100"
                  : "border-white/10 hover:border-white/30"
              }`}
            >
              <div className="text-sm font-medium">
                {table.table_name}
              </div>
              {table.table_schema && (
                <div className="text-xs text-zinc-500">
                  {table.table_schema}
                </div>
              )}
            </button>
          );
        })}
        {!loading && tables.length === 0 && (
          <div className="text-sm text-zinc-500">
            No tables detected yet. Run a query to refresh the schema.
          </div>
        )}
      </div>
    </section>
  );
}
