import { pool } from "@/lib/db";
import { getAdminUser } from "@/lib/admin-permissions";
import { getActiveBrandId } from "@/lib/brand-scope";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import StopTableClient from "@/components/admin/StopTableClient";
import { PageHeader } from "@/components/admin/design-system";
import { redirect } from "next/navigation";

const StopIcon = () => (
  <svg className="h-5 w-5 sm:h-6 sm:w-6 text-current" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z"/>
    <circle cx="12" cy="10" r="3"/>
  </svg>
);

interface PageProps {
  searchParams: Promise<{ page?: string }>;
}

export default async function AdminStopsPage({ searchParams }: PageProps) {
  const [params, adminUser] = await Promise.all([searchParams, getAdminUser()]);

  if (!adminUser) return <AdminAccessDenied />;
  if (!adminUser.can_manage_stops) redirect("/admin/pickup");

  interface DbStopRow {
    id: string;
    city: string;
    state: string;
    date: Date | string;
    time: string | null;
    location: string;
    status: string;
    brand_id: string;
    address: string | null;
    zip: string | null;
    cutoff_date: string | null;
    brand_name?: string;
  }
  let stops: DbStopRow[] = [];
  let error: string | null = null;

  // Resolve active brand from cookie/URL (respects platform_admin "All brands" = null)
  let activeBrandId: string | null = null;
  try {
    activeBrandId = await getActiveBrandId(adminUser);

    // Three fully-static SQL branches — no template-literal SQL anywhere.
    // The branch is selected by a hardcoded ternary; brand id values flow
    // through pg's positional bind variables (single id or uuid[] array).
    const STOP_LIST_QUERY = `SELECT s.id, s.city, s.state, s.date, s."time", s.location, s.status,
              s.brand_id, s.address, s.zip, s.cutoff_date,
              b.name as brand_name
       FROM stops s
       LEFT JOIN brands b ON b.id = s.brand_id`;

    let queryText: string;
    let queryParams: unknown[];
    if (activeBrandId) {
      queryText = `${STOP_LIST_QUERY} WHERE s.brand_id = $1 ORDER BY s.date ASC LIMIT 200`;
      queryParams = [activeBrandId];
    } else if (adminUser.role === "platform_admin") {
      queryText = `${STOP_LIST_QUERY} WHERE 1=1 ORDER BY s.date ASC LIMIT 200`;
      queryParams = [];
    } else {
      const allowedBrandIds = adminUser.brand_ids ?? [];
      if (allowedBrandIds.length === 0) {
        // No brands the user can see — short-circuit to an empty result
        // without running a query at all.
        stops = [];
        error = null;
      }
      queryText = `${STOP_LIST_QUERY} WHERE s.brand_id = ANY($1::uuid[]) ORDER BY s.date ASC LIMIT 200`;
      queryParams = [allowedBrandIds];
    }

    const { rows } = await pool.query(queryText, queryParams);
    stops = rows;
    console.log("[admin/stops] Fetched", rows.length, "stops");
  } catch (e) {
    error = e instanceof Error ? e.message : String(e);
    console.error("[admin/stops] Query error:", error);
  }

  if (error) {
    return (
      <main className="min-h-screen bg-[var(--admin-bg)]">
        <div className="px-4 sm:px-6 md:px-8 py-6 sm:py-8">
          <div className="max-w-6xl mx-auto">
            <p className="ha-eyebrow mb-2">Operations</p>
            <PageHeader
              title="Stops & Routes"
              subtitle="Schedule and manage pickup locations and dates."
              icon={<StopIcon />}
            />
            <div className="rounded-2xl border border-[var(--admin-danger)]/30 bg-[var(--admin-danger-soft)] p-5">
              <h2 className="text-lg font-semibold text-[var(--admin-danger)]">Error loading stops</h2>
              <pre className="mt-3 rounded-xl bg-white border border-[var(--admin-border)] p-4 text-sm text-[var(--admin-text-secondary)] overflow-auto">
                {error}
              </pre>
              <div className="mt-4 p-4 rounded-xl bg-[var(--admin-bg-subtle)] text-sm text-[var(--admin-text-secondary)]">
                <p className="font-semibold text-[var(--admin-text-primary)]">Debug info:</p>
                <p>adminUser.brand_id: {adminUser.brand_id ?? "null"}</p>
                <p>adminUser.role: {adminUser.role}</p>
                <p>adminUser.email: {adminUser.email}</p>
              </div>
            </div>
          </div>
        </div>
      </main>
    );
  }

  // Transform stops for the client component
  const stopsForClient = stops.map((s) => ({
    id: s.id,
    city: s.city,
    state: s.state,
    date: s.date instanceof Date ? s.date.toISOString().split("T")[0] : String(s.date).split("T")[0],
    time: s.time || "",
    location: s.location,
    active: s.status === "active",
    brand_id: s.brand_id,
    status: s.status,
    address: s.address,
    zip: s.zip,
    cutoff_time: s.cutoff_date,
    brands: s.brand_name ? { name: s.brand_name } : null,
  }));

  return (
    <div className="min-h-screen bg-[var(--admin-bg)]">
      <div className="px-4 sm:px-6 md:px-8 pt-4 sm:pt-6">
        <p className="ha-eyebrow mb-2">Operations</p>
        <PageHeader
          title="Stops & Routes"
          subtitle="Schedule and manage pickup locations and dates."
          icon={<StopIcon />}
        />
      </div>
      <div className="px-4 sm:px-6 md:px-8 pb-6 sm:pb-8">
        <StopTableClient stops={stopsForClient} />
      </div>
    </div>
  );
}
