import Link from "next/link";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule, canOrgMutate } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { Badge, btn, Card, EmptyState, Field, PageHeader, StatCard, input } from "@/components/ui";
import { parseJSON } from "@/lib/utils";
import { INDIAN_STATES } from "@/lib/constants";
import { createOrgVenue, deleteOrgVenue, reuseVenueAction, updateOrgVenue, type HallSpec } from "./actions";

export const metadata = { title: "Venues" };

type PoolDefaults = {
  name: string; address: string | null; city: string | null; state: string | null;
  capacity: number | null; contactName: string | null; contactPhone: string | null;
  contactEmail: string | null; website: string | null; facilities: string | null;
  mapUrl: string | null; description: string | null; hallsSpec: string | null;
};

function VenueFormFields({ defaults }: { defaults?: PoolDefaults }) {
  const halls = parseJSON<HallSpec[]>(defaults?.hallsSpec ?? null, []);
  const hallsText = halls.map((h) => [h.name, h.capacity ?? "", h.floor ?? ""].join(" | ").replace(/( \| )+$/, "")).join("\n");
  return (
    <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
      <Field name="name" title="Venue name *"><input name="name" required defaultValue={defaults?.name ?? ""} placeholder="Convention centre, hotel, campus…" className={input} /></Field>
      <div className="sm:col-span-2"><Field name="address" title="Address"><input name="address" defaultValue={defaults?.address ?? ""} className={input} /></Field></div>
      <Field name="city" title="City"><input name="city" defaultValue={defaults?.city ?? ""} className={input} /></Field>
      <Field name="state" title="State">
        <select name="state" defaultValue={defaults?.state ?? ""} className={input}>
          <option value="">— Select —</option>
          {INDIAN_STATES.map((s) => <option key={s} value={s}>{s}</option>)}
        </select>
      </Field>
      <Field name="capacity" title="Total capacity"><input name="capacity" type="number" min="1" defaultValue={defaults?.capacity ?? ""} className={input} /></Field>
      <Field name="contactName" title="Contact person"><input name="contactName" defaultValue={defaults?.contactName ?? ""} className={input} /></Field>
      <Field name="contactPhone" title="Phone"><input name="contactPhone" defaultValue={defaults?.contactPhone ?? ""} className={input} /></Field>
      <Field name="contactEmail" title="Email"><input name="contactEmail" type="email" defaultValue={defaults?.contactEmail ?? ""} className={input} /></Field>
      <Field name="website" title="Website"><input name="website" type="url" defaultValue={defaults?.website ?? ""} placeholder="https://…" className={input} /></Field>
      <Field name="mapUrl" title="Google Maps link"><input name="mapUrl" type="url" defaultValue={defaults?.mapUrl ?? ""} placeholder="https://maps.google.com/…" className={input} /></Field>
      <Field name="facilities" title="Facilities (comma-separated)"><input name="facilities" defaultValue={defaults?.facilities ?? ""} placeholder="Parking, Wi-Fi, AV, Catering…" className={input} /></Field>
      <div className="sm:col-span-2 lg:col-span-3">
        <Field name="description" title="Notes"><textarea name="description" rows={2} defaultValue={defaults?.description ?? ""} className={input} /></Field>
      </div>
      <div className="sm:col-span-2 lg:col-span-3">
        <Field name="halls" title="Halls / meeting rooms — one per line: Name | capacity | floor">
          <textarea name="halls" rows={3} defaultValue={hallsText} placeholder={"Main Auditorium | 800 | Ground\nSeminar Hall A | 120 | 1st"} className={`${input} font-mono text-xs`} />
        </Field>
      </div>
    </div>
  );
}

export default async function VenuesDirectoryPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; saved?: string; error?: string; add?: string; edit?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "venues")) {
    return <EmptyState title="No access" body="Venue management is not part of your role." />;
  }
  const org = ctx.org;
  const canMutate = canOrgMutate(ctx.role);
  const { q = "", saved, error, add, edit } = await searchParams;
  const showAddForm = add === "1" || Boolean(error);

  const [venues, conferences] = await Promise.all([
    db.venue.findMany({
      where: {
        OR: [{ conference: { orgId: org.id } }, { orgId: org.id, conferenceId: null }],
        ...(q ? { AND: [{ OR: [{ name: { contains: q } }, { city: { contains: q } }] }] } : {}),
      },
      include: {
        conference: { select: { id: true, name: true } },
        rooms: { select: { id: true, name: true, capacity: true, _count: { select: { sessions: true } } } },
      },
      orderBy: { name: "asc" },
    }),
    db.conference.findMany({ where: { orgId: org.id, status: { notIn: ["ARCHIVED"] } }, orderBy: { startAt: "desc" }, select: { id: true, name: true } }),
  ]);

  type Grouped = PoolDefaults & {
    latestId: string; poolId: string | null; halls: number; sessions: number;
    conferences: { id: string; name: string }[];
  };
  const byName = new Map<string, Grouped>();
  for (const v of venues) {
    const key = `${v.name.toLowerCase()}|${(v.city ?? "").toLowerCase()}`;
    const roomCapacity = v.rooms.reduce((s, r) => s + (r.capacity ?? 0), 0);
    const sessions = v.rooms.reduce((s, r) => s + r._count.sessions, 0);
    const poolHalls = parseJSON<HallSpec[]>(v.hallsSpec, []).length;
    let g = byName.get(key);
    if (!g) {
      g = {
        name: v.name, address: v.address, city: v.city, state: v.state, capacity: v.capacity,
        contactName: v.contactName, contactPhone: v.contactPhone, contactEmail: v.contactEmail,
        website: v.website, facilities: v.facilities, mapUrl: v.mapUrl, description: v.description,
        hallsSpec: v.hallsSpec, latestId: v.id, poolId: null, halls: 0, sessions: 0, conferences: [],
      };
      byName.set(key, g);
    }
    if (v.conference) {
      g.conferences.push({ id: v.conference.id, name: v.conference.name });
      g.halls = Math.max(g.halls, v.rooms.length);
      g.sessions += sessions;
      g.capacity = g.capacity ?? (roomCapacity || null);
    } else {
      g.poolId = v.id;
      g.latestId = v.id;
      g.name = v.name; g.address = v.address ?? g.address; g.city = v.city ?? g.city; g.state = v.state ?? g.state;
      g.capacity = v.capacity ?? g.capacity; g.contactName = v.contactName; g.contactPhone = v.contactPhone;
      g.contactEmail = v.contactEmail; g.website = v.website; g.facilities = v.facilities;
      g.mapUrl = v.mapUrl ?? g.mapUrl; g.description = v.description ?? g.description; g.hallsSpec = v.hallsSpec;
      g.halls = Math.max(g.halls, poolHalls);
    }
  }
  const directory = [...byName.values()];
  const poolCount = directory.filter((d) => d.poolId).length;

  return (
    <main>
      <PageHeader
        title="📍 Venues"
        sub={`Reusable venue database for ${org.name} — add a venue once (halls included), use it for any conference later.`}
        action={canMutate ? (
          <Link href={showAddForm ? "/dashboard/venues" : "/dashboard/venues?add=1"} className={btn.primary}>
            {showAddForm ? "Close" : "+ Add Venue"}
          </Link>
        ) : undefined}
      />
      {saved && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ {saved}</p>}
      {error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{error}</p>}

      {canMutate && showAddForm && (
        <Card className="mb-6 p-5">
          <h3 className="text-sm font-bold text-zinc-100">Add venue to your database</h3>
          <p className="mb-4 text-xs text-zinc-500">Full profile with halls, contacts and facilities — select it while setting up any conference.</p>
          <form action={createOrgVenue}>
            <VenueFormFields />
            <button className={`${btn.primary} mt-4`}>Save venue</button>
          </form>
        </Card>
      )}

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Venues" value={directory.length} />
        <StatCard label="In Venue Database" value={poolCount} sub="reusable profiles" accent="text-sky-600" />
        <StatCard label="Halls / Rooms" value={directory.reduce((s, d) => s + d.halls, 0)} />
        <StatCard label="Sessions Hosted" value={directory.reduce((s, d) => s + d.sessions, 0)} />
      </div>

      <form className="mt-5" action="/dashboard/venues">
        <input type="search" name="q" defaultValue={q} placeholder="Search venues by name or city… 🔍" className={`${input} max-w-md`} />
      </form>

      {directory.length === 0 ? (
        <div className="mt-5">
          <EmptyState
            title={q ? `No venues matching “${q}”` : "No venues yet"}
            body="Add venues here to build a reusable database, or set them up inside a conference — they appear here either way."
            action={canMutate && !q ? <Link href="/dashboard/venues?add=1" className={btn.primary}>+ Add your first venue</Link> : undefined}
          />
        </div>
      ) : (
        <div className="mt-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {directory.map((d) => {
            const editing = edit === d.poolId && canMutate;
            const facilities = (d.facilities ?? "").split(",").map((f) => f.trim()).filter(Boolean);
            return (
              <Card key={`${d.name}-${d.city}`} className={`fx-lift p-5 ${editing ? "sm:col-span-2 xl:col-span-3" : ""}`}>
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="font-bold text-zinc-100">🏛️ {d.name}</span>
                      {d.poolId && <Badge className="bg-sky-500/10 text-sky-600">📚 In database</Badge>}
                    </div>
                    <div className="mt-0.5 text-xs text-zinc-500">{[d.address, d.city, d.state].filter(Boolean).join(", ") || "Address not set"}</div>
                  </div>
                  <div className="flex shrink-0 gap-1.5">
                    {d.mapUrl && <a href={d.mapUrl} target="_blank" rel="noreferrer" className={btn.smSecondary}>🗺 Map</a>}
                    {d.poolId && canMutate && !editing && (
                      <Link href={`/dashboard/venues?edit=${d.poolId}`} className={btn.smSecondary}>✏️ Edit</Link>
                    )}
                  </div>
                </div>

                {editing ? (
                  <div className="mt-4 border-t border-zinc-800/50 pt-4">
                    <form action={updateOrgVenue.bind(null, d.poolId!)}>
                      <VenueFormFields defaults={d} />
                      <div className="mt-4 flex flex-wrap items-center gap-2">
                        <button className={btn.primary}>Save changes</button>
                        <Link href="/dashboard/venues" className={btn.secondary}>Cancel</Link>
                      </div>
                    </form>
                    <form action={deleteOrgVenue.bind(null, d.poolId!)} className="mt-2">
                      <button className="text-xs text-red-500 hover:underline">🗑 Remove from venue database (conference setups stay)</button>
                    </form>
                  </div>
                ) : (
                  <>
                    {d.description && <p className="mt-2 line-clamp-2 text-xs text-zinc-500">{d.description}</p>}
                    <div className="mt-3 flex flex-wrap gap-1.5">
                      {d.halls > 0 && <Badge className="bg-indigo-500/10 text-indigo-600">{d.halls} hall{d.halls === 1 ? "" : "s"}</Badge>}
                      {(d.capacity ?? 0) > 0 && <Badge className="bg-sky-500/10 text-sky-600">{d.capacity} capacity</Badge>}
                      {d.sessions > 0 && <Badge className="bg-violet-500/10 text-violet-600">{d.sessions} sessions hosted</Badge>}
                      {facilities.slice(0, 4).map((f) => <Badge key={f} className="bg-zinc-500/10 text-zinc-500">{f}</Badge>)}
                    </div>
                    {(d.contactName || d.contactPhone || d.contactEmail) && (
                      <p className="mt-2.5 text-xs text-zinc-500">👤 {[d.contactName, d.contactPhone, d.contactEmail].filter(Boolean).join(" · ")}</p>
                    )}
                    <div className="mt-3 border-t border-zinc-800/50 pt-3">
                      <div className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">Conferences</div>
                      <div className="mt-1.5 flex flex-wrap gap-1.5">
                        {d.conferences.length === 0 && (
                          <span className="text-[11px] text-zinc-500">Not used yet — pick it for a conference below.</span>
                        )}
                        {d.conferences.map((c) => (
                          <Link key={c.id} href={`/dashboard/c/${c.id}/venue`} className="max-w-full truncate rounded-full border border-white/70 bg-white/50 px-2 py-0.5 text-[11px] text-zinc-400 transition hover:text-indigo-600">
                            {c.name}
                          </Link>
                        ))}
                      </div>
                      {canMutate && conferences.filter((c) => !d.conferences.some((x) => x.id === c.id)).length > 0 && (
                        <form action={reuseVenueAction.bind(null, d.latestId)} className="mt-2.5 flex gap-1.5">
                          <select name="targetConferenceId" required className={`${input} !py-1.5 text-xs`} aria-label="Use for conference">
                            <option value="">Use for conference…</option>
                            {conferences.filter((c) => !d.conferences.some((x) => x.id === c.id)).map((c) => (
                              <option key={c.id} value={c.id}>{c.name}</option>
                            ))}
                          </select>
                          <button className={btn.sm}>Use venue</button>
                        </form>
                      )}
                    </div>
                  </>
                )}
              </Card>
            );
          })}
        </div>
      )}
    </main>
  );
}
