import { useEffect, useMemo, useState } from "react";
import { AdminGrid } from "../components/data-explorer/AdminGrid";
import { RowEditForm } from "../components/data-explorer/RowEditForm";
import { useAdminTables } from "../hooks/useAdminTables";

export function DataExplorerPage() {
  const { error, isLoading, meta, rows, selectedTableId, setSelectedTableId, tables, updateRow } =
    useAdminTables();
  const [selectedRowId, setSelectedRowId] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [saveMessage, setSaveMessage] = useState<string | null>(null);

  useEffect(() => {
    setSelectedRowId(null);
    setSaveMessage(null);
  }, [selectedTableId]);

  const selectedRow = useMemo(() => {
    if (!meta || !selectedRowId) {
      return null;
    }

    return rows.find((row) => String(row[meta.primaryKey] ?? "") === selectedRowId) ?? null;
  }, [meta, rows, selectedRowId]);

  const handleSave = async (changes: Record<string, string | boolean | null>) => {
    if (!selectedRowId) {
      return;
    }

    setIsSaving(true);
    setSaveMessage(null);

    try {
      await updateRow(selectedRowId, changes);
      setSaveMessage("Row updated and logged.");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <main className="min-h-screen p-6">
      <div className="grid gap-6 lg:grid-cols-[220px_minmax(0,1fr)_360px]">
        <aside className="rounded-3xl border border-border bg-card p-4">
          <p className="text-xs uppercase tracking-[0.25em] text-foreground/60">Data Explorer</p>
          <div className="mt-4 flex flex-col gap-2">
            {tables.map((table) => (
              <button
                className={`rounded-2xl border px-3 py-2 text-left text-sm ${
                  selectedTableId === table.id
                    ? "border-foreground bg-foreground text-background"
                    : "border-border"
                }`}
                key={table.id}
                onClick={() => setSelectedTableId(table.id)}
                type="button"
              >
                {table.label}
              </button>
            ))}
          </div>
        </aside>

        <section className="space-y-4">
          <header>
            <h1 className="text-3xl font-semibold">{meta?.label ?? "Explorer"}</h1>
            <p className="mt-2 text-sm text-foreground/70">
              Approved production tables exposed through the internal admin registry.
            </p>
          </header>

          {isLoading ? <p>Loading explorer...</p> : null}
          {error ? <p className="text-red-600">{error}</p> : null}
          {!isLoading && !error ? (
            <AdminGrid
              meta={meta}
              onSelectRow={(row) => {
                if (!meta) {
                  return;
                }

                setSelectedRowId(String(row[meta.primaryKey] ?? ""));
                setSaveMessage(null);
              }}
              rows={rows}
              selectedRowId={selectedRowId}
            />
          ) : null}
        </section>

        <aside className="rounded-3xl border border-border bg-card p-5">
          <p className="text-xs uppercase tracking-[0.25em] text-foreground/60">Row Detail</p>

          {!selectedRow || !meta ? (
            <div className="mt-6 space-y-2 text-sm text-foreground/70">
              <p>Select a row to inspect record details.</p>
              <p>Approved edits are reviewed before they hit production.</p>
            </div>
          ) : (
            <div className="mt-6 space-y-6">
              <div className="space-y-3">
                {meta.columns.map((column) => (
                  <div className="rounded-2xl border border-border/80 px-3 py-2" key={column.id}>
                    <p className="text-xs uppercase tracking-[0.2em] text-foreground/50">
                      {column.label}
                    </p>
                    <p className="mt-1 text-sm">{String(selectedRow[column.id] ?? "")}</p>
                  </div>
                ))}
              </div>

              {meta.editableFields.length > 0 ? (
                <div className="space-y-3">
                  <div>
                    <h2 className="text-lg font-semibold">Guarded Edit</h2>
                    <p className="text-sm text-foreground/70">
                      Editable fields require a reviewed diff and create an audit log entry.
                    </p>
                  </div>

                  <RowEditForm
                    columns={meta.columns}
                    editableFields={meta.editableFields}
                    isSaving={isSaving}
                    onSave={handleSave}
                    record={selectedRow}
                  />

                  {saveMessage ? <p className="text-sm text-emerald-700">{saveMessage}</p> : null}
                </div>
              ) : (
                <p className="text-sm text-foreground/70">
                  This table is currently read-only in the admin panel.
                </p>
              )}
            </div>
          )}
        </aside>
      </div>
    </main>
  );
}
