"use client";

import { useState, useMemo } from "react";
import { type TableMetadata } from "@/app/lib/api";
import { Input } from "./ui/input";
import { ScrollArea } from "./ui/scroll-area";
import { Search, LayoutList, Table2, Loader2 } from "lucide-react";
import { cn } from "@/app/lib/utils";

type Props = {
  clients: string[];
  selectedClient: string | null;
  onClientChange: (client: string) => void;
  clientsLoading: boolean;
  clientsError: string | null;
  tables: TableMetadata[];
  tablesLoading: boolean;
  onSelectTable: (table: TableMetadata) => void;
};

const TABLE_COLORS = [
  "bg-neutral-800 text-white",
  "bg-neutral-700 text-white",
  "bg-zinc-700 text-white",
  "bg-stone-700 text-white",
  "bg-slate-700 text-white",
  "bg-gray-600 text-white",
  "bg-neutral-600 text-white",
  "bg-zinc-800 text-white",
];

function hashColor(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = (hash << 5) - hash + name.charCodeAt(i);
    hash |= 0;
  }
  return TABLE_COLORS[Math.abs(hash) % TABLE_COLORS.length];
}

export default function TableSelectPage({
  clients,
  selectedClient,
  onClientChange,
  clientsLoading,
  clientsError,
  tables,
  tablesLoading,
  onSelectTable,
}: Props) {
  const [filter, setFilter] = useState("");

  const filtered = useMemo(() => {
    if (!filter.trim()) return tables;
    const q = filter.toLowerCase();
    return tables.filter(
      (t) =>
        t.table_name.toLowerCase().includes(q) ||
        (t.table_schema ?? "").toLowerCase().includes(q),
    );
  }, [tables, filter]);

  return (
    <div className="flex flex-1 flex-col items-center justify-center animate-fade-in">
      <div className="flex flex-col items-center w-full max-w-md px-4">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-muted/60 mb-4">
          <LayoutList className="h-5 w-5 text-muted-foreground/60" />
        </div>

        <h2 className="text-base font-semibold text-foreground mb-0.5">
          Continue to Table Editor
        </h2>
        <p className="text-sm text-muted-foreground mb-6">
          {selectedClient
            ? "Choose a table to continue"
            : "Choose a connection to continue"}
        </p>

        <div className="w-full rounded-lg border border-border bg-card shadow-sm">
          {selectedClient && (
            <div className="px-3 py-2.5 border-b border-border">
              <div className="relative">
                <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground/50" />
                <Input
                  placeholder="Find Table..."
                  value={filter}
                  onChange={(e) => setFilter(e.target.value)}
                  className="h-8 pl-8 text-sm bg-background border-border/60"
                />
              </div>
            </div>
          )}

          <ScrollArea className="max-h-90">
            {!selectedClient && clientsLoading && (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
              </div>
            )}

            {!selectedClient && clientsError && !clientsLoading && (
              <div className="flex flex-col items-center justify-center py-10 text-center">
                <p className="text-sm text-destructive px-4">{clientsError}</p>
              </div>
            )}

            {!selectedClient &&
              !clientsLoading &&
              !clientsError &&
              clients.length === 0 && (
                <div className="flex flex-col items-center justify-center py-10 text-center">
                  <Table2 className="h-8 w-8 text-muted-foreground/20 mb-2" />
                  <p className="text-sm text-muted-foreground">
                    No connections found
                  </p>
                </div>
              )}

            {!selectedClient &&
              !clientsLoading &&
              !clientsError &&
              clients.map((client) => (
                <button
                  key={client}
                  type="button"
                  onClick={() => onClientChange(client)}
                  className={cn(
                    "flex items-center gap-3 w-full px-3 py-2.5 text-left",
                    "hover:bg-accent/50 transition-colors",
                    "border-b border-border/40 last:border-b-0",
                  )}
                >
                  <div className="flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium shrink-0 bg-neutral-800 text-white">
                    {client.charAt(0).toUpperCase()}
                  </div>
                  <div className="flex flex-col min-w-0">
                    <span className="text-sm font-medium text-foreground truncate">
                      {client}
                    </span>
                    <span className="text-xs text-muted-foreground/60 truncate">
                      Connection
                    </span>
                  </div>
                </button>
              ))}

            {selectedClient && tablesLoading && (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
              </div>
            )}

            {selectedClient && !tablesLoading && filtered.length === 0 && (
              <div className="flex flex-col items-center justify-center py-10 text-center">
                <Table2 className="h-8 w-8 text-muted-foreground/20 mb-2" />
                <p className="text-sm text-muted-foreground">
                  {tables.length === 0
                    ? "No tables found"
                    : "No tables match your search"}
                </p>
              </div>
            )}

            {selectedClient &&
              !tablesLoading &&
              filtered.map((table) => (
                <button
                  key={`${table.table_schema ?? "public"}.${table.table_name}`}
                  type="button"
                  onClick={() => onSelectTable(table)}
                  className={cn(
                    "flex items-center gap-3 w-full px-3 py-2.5 text-left",
                    "hover:bg-accent/50 transition-colors",
                    "border-b border-border/40 last:border-b-0",
                  )}
                >
                  <div
                    className={cn(
                      "flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium shrink-0",
                      hashColor(table.table_name),
                    )}
                  >
                    {table.table_name.charAt(0).toUpperCase()}
                  </div>
                  <div className="flex flex-col min-w-0">
                    <span className="text-sm font-medium text-foreground truncate">
                      {table.table_name}
                    </span>
                    {table.table_schema && table.table_schema !== "public" && (
                      <span className="text-xs text-muted-foreground/60 truncate">
                        {table.table_schema}
                      </span>
                    )}
                  </div>
                </button>
              ))}
          </ScrollArea>
        </div>
      </div>
    </div>
  );
}
