import { pool } from "@/lib/db";
import NewStopForm from "@/components/admin/NewStopForm";
import StopProductAssignment from "@/components/admin/StopProductAssignment";
import { getAdminUser } from "@/lib/admin-permissions";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import { PageHeader } from "@/components/admin/design-system";
import { redirect } from "next/navigation";
import Link from "next/link";

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>
);

type Stop = {
  city: string;
  state: string;
  location: string;
  date: string;
  time: string;
  brand_id: string;
  active: boolean;
  address?: string | null;
  zip?: string | null;
  cutoff_time?: string | null;
};

export default async function NewStopPage({
  searchParams,
}: {
  searchParams: Promise<{ duplicate?: string }>;
}) {
  const adminUser = await getAdminUser();
  const { duplicate } = await searchParams;

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

  let duplicateFrom: Stop | null = null;
  if (duplicate) {
    const { rows } = await pool.query<Stop>(
      `SELECT city, state, location, date, time, brand_id, active, address, zip, cutoff_date
       FROM stops WHERE id = $1 LIMIT 1`,
      [duplicate]
    );
    const row = rows[0];
    if (row) {
      duplicateFrom = {
        city: row.city ?? "",
        state: row.state ?? "",
        location: row.location ?? "",
        date: row.date ? String(row.date) : "",
        time: row.time ?? "",
        brand_id: row.brand_id,
        active: row.active ?? true,
        address: row.address ?? null,
        zip: row.zip ?? null,
        cutoff_time: row.cutoff_time ?? null,
      };
    }
  }

  const brandId =
    adminUser.brand_id ?? "64294306-5f42-463d-a5e8-2ad6c81a96de";

  const { rows: productRows } = await pool.query<{ id: string; name: string; type: string; price: number }>(
    `SELECT id, name, type, price FROM products WHERE brand_id = $1 AND active = true ORDER BY name`,
    [brandId]
  );

  const pageTitle = duplicateFrom ? "Duplicate Stop" : "Create Stop";
  const pageSubtitle = duplicateFrom
    ? `Pre-filled from ${duplicateFrom.city}, ${duplicateFrom.state}. Edit and save to create.`
    : "Add a new tour stop for Tuxedo Corn or Indian River Direct.";

  return (
    <main 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={pageTitle}
          subtitle={pageSubtitle}
          icon={<StopIcon />}
        />
      </div>

      <div className="px-4 sm:px-6 md:px-8 pb-8 sm:pb-10">
        <div className="mx-auto max-w-4xl">
          <Link
            href="/admin/stops"
            className="ha-btn-ghost mb-4 inline-flex"
          >
            <svg className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2.2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
            </svg>
            Back to Stops
          </Link>

          <div className="rounded-2xl bg-white p-8 border border-[var(--admin-border)] shadow-sm">
            <NewStopForm duplicateFrom={duplicateFrom} />
          </div>
        </div>
      </div>
    </main>
  );
}
