import Link from "next/link";
import { redirect } from "next/navigation";
import { isOrganizer, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getOrgContext, rangeWindow, dateFilter } from "@/lib/org";
import { btn, Card, EmptyState, PageHeader, StatCard, StatusBadge, Badge } from "@/components/ui";
import { dateRange, formatMoney, parseJSON, fmtDateTime } from "@/lib/utils";
import { VOLUNTEER_AREAS } from "@/lib/constants";
import { AreaChart, Donut, HBars, CHART_COLORS } from "@/components/charts";

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

const AREA_PATHS: Record<string, string> = {
  checkin: "checkin",
  agenda: "agenda",
  registrations: "registrations",
  speakers: "speakers",
  announcements: "announcements",
  sponsors: "sponsors",
  certificates: "certificates",
};

const RANGES: { key: string; label: string }[] = [
  { key: "all", label: "All time" },
  { key: "today", label: "Today" },
  { key: "week", label: "This Week" },
  { key: "month", label: "This Month" },
  { key: "quarter", label: "This Quarter" },
  { key: "year", label: "This Year" },
];

export default async function DashboardHome({
  searchParams,
}: {
  searchParams: Promise<{ range?: string; from?: string; to?: string }>;
}) {
  const user = await requireUser();
  const canCreate = isOrganizer(user);

  // ── Volunteer duty roster & attendee redirect (unchanged behaviour) ──
  if (!canCreate) {
    const [memberships, orgMemberCount, volunteerRows] = await Promise.all([
      db.confMember.findMany({ where: { userId: user.id }, select: { role: true } }),
      db.orgMember.count({ where: { userId: user.id } }),
      db.volunteer.findMany({
        where: { userId: user.id },
        include: { conference: { include: { org: true } } },
        orderBy: { conference: { startAt: "desc" } },
      }),
    ]);
    if (memberships.length === 0 && orgMemberCount === 0) redirect("/me");

    // Volunteer-only accounts always get the duty roster, even if they hold a
    // basic org membership — the console is for staff roles.
    if (volunteerRows.length > 0 && memberships.length > 0 && memberships.every((m) => m.role === "VOLUNTEER")) {
      return (
        <main className="mx-auto max-w-4xl px-4 py-8">
          <PageHeader
            title={`Hi ${user.name.split(" ")[0]} 🙋`}
            sub="Your volunteer assignments — you can manage exactly the areas listed on each conference."
          />
          <div className="space-y-4">
            {volunteerRows.map((v) => {
              const areas = parseJSON<string[]>(v.areas, []);
              const c = v.conference;
              return (
                <Card key={v.id} className="p-5">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div className="flex min-w-0 items-center gap-4">
                      <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-lg font-bold text-white shadow-md" style={{ background: c.primaryColor }}>
                        {c.name[0]}
                      </span>
                      <div className="min-w-0">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="font-bold text-zinc-100">{c.name}</span>
                          <StatusBadge status={c.status} />
                        </div>
                        <div className="mt-0.5 text-sm text-zinc-500">
                          {dateRange(c.startAt, c.endAt)} · {c.org.name}
                          {v.department ? ` · ${v.department}` : ""}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="mt-4 border-t border-zinc-800/60 pt-3">
                    <div className="text-[11px] font-semibold uppercase tracking-wider text-zinc-500">Your assigned duties</div>
                    <div className="mt-2 flex flex-wrap gap-2">
                      {areas.length === 0 && (
                        <Badge className="bg-amber-500/10 text-amber-600">No duties assigned yet — contact the organizer</Badge>
                      )}
                      {areas.map((key) => {
                        const area = VOLUNTEER_AREAS.find((a) => a.key === key);
                        if (!area) return null;
                        return (
                          <Link key={key} href={`/dashboard/c/${c.id}/${AREA_PATHS[key] ?? ""}`} className={btn.sm}>
                            {area.label} →
                          </Link>
                        );
                      })}
                      <Link href={`/dashboard/c/${c.id}`} className={btn.smSecondary}>Overview</Link>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
          <p className="mt-6 text-center text-xs text-zinc-600">
            Signed in as a volunteer — organizer and attendee features are not part of this account's scope.
          </p>
        </main>
      );
    }
  }

  // ── Organizer Console: organization-level operational overview ──
  const ctx = await getOrgContext();
  const org = ctx?.org;

  if (!org) {
    return (
      <main className="py-10">
        <PageHeader title={`Welcome, ${user.name.split(" ")[0]}`} sub="Set up your organization to unlock the Organizer Console." />
        <EmptyState
          title="No organization yet"
          body="Create your first conference — your organization is set up along the way, and the console unlocks dashboards, finances, visitor management and more."
          action={canCreate ? <Link href="/dashboard/conferences/new" className={btn.primary}>Create your first conference</Link> : undefined}
        />
      </main>
    );
  }

  const sp = await searchParams;
  const { start, end, key: rangeKey } = rangeWindow(sp.range, sp.from, sp.to);
  const createdFilter = dateFilter(start, end);
  const now = new Date();

  const [conferences, regs, checkedIn, speakerCount, sponsors, assetCount, teamCount, expenses] = await Promise.all([
    db.conference.findMany({
      where: { orgId: org.id },
      orderBy: { startAt: "asc" },
      include: {
        _count: { select: { registrations: { where: { status: "CONFIRMED" } }, speakers: true, sponsors: true, sessions: true } },
        registrations: { where: { status: "CONFIRMED" }, select: { amount: true } },
      },
    }),
    db.registration.findMany({
      where: { conference: { orgId: org.id }, ...(createdFilter ? { createdAt: createdFilter } : {}) },
      select: {
        createdAt: true, amount: true, status: true, city: true,
        conference: { select: { name: true, state: true } },
        ticketType: { select: { audience: true, name: true } },
      },
    }),
    db.checkIn.count({ where: { registration: { conference: { orgId: org.id } }, type: "CONFERENCE" } }),
    db.speaker.count({ where: { conference: { orgId: org.id } } }),
    db.sponsor.findMany({ where: { conference: { orgId: org.id } }, select: { amount: true, tier: true } }),
    db.asset.count({ where: { orgId: org.id } }),
    db.orgMember.count({ where: { orgId: org.id } }),
    db.expense.aggregate({ where: { orgId: org.id, ...(createdFilter ? { incurredAt: createdFilter } : {}) }, _sum: { amount: true } }),
  ]);

  const upcoming = conferences.filter((c) => c.endAt >= now && c.status !== "ARCHIVED");
  const completed = conferences.filter((c) => c.status === "COMPLETED" || (c.endAt < now && c.status !== "DRAFT" && c.status !== "ARCHIVED"));
  const confirmed = regs.filter((r) => r.status === "CONFIRMED");
  const pendingAmount = regs.filter((r) => r.status === "PENDING").reduce((s, r) => s + r.amount, 0);
  const revenue = confirmed.reduce((s, r) => s + r.amount, 0);
  const sponsorRevenue = sponsors.reduce((s, x) => s + x.amount, 0);
  const expenseTotal = expenses._sum.amount ?? 0;

  // Registrations over time — day buckets for short ranges, month buckets otherwise.
  const spanDays = start ? Math.ceil((now.getTime() - start.getTime()) / 86400_000) : 365;
  const byDay = spanDays <= 45;
  const buckets = new Map<string, number>();
  const bucketKeys: string[] = [];
  const bucketCount = byDay ? Math.max(spanDays, 7) : 12;
  for (let i = bucketCount - 1; i >= 0; i--) {
    const d = new Date(now);
    if (byDay) d.setDate(d.getDate() - i);
    else d.setMonth(d.getMonth() - i);
    const k = byDay
      ? d.toLocaleDateString("en-IN", { day: "numeric", month: "short" })
      : d.toLocaleDateString("en-IN", { month: "short", year: "2-digit" });
    buckets.set(k, 0);
    bucketKeys.push(k);
  }
  for (const r of regs) {
    const k = byDay
      ? r.createdAt.toLocaleDateString("en-IN", { day: "numeric", month: "short" })
      : r.createdAt.toLocaleDateString("en-IN", { month: "short", year: "2-digit" });
    if (buckets.has(k)) buckets.set(k, (buckets.get(k) ?? 0) + 1);
  }
  const regSeries = bucketKeys.map((k) => ({ label: k, value: buckets.get(k) ?? 0 }));

  const revenueByConf = conferences
    .map((c) => ({ label: c.name, value: c.registrations.reduce((s, r) => s + r.amount, 0) }))
    .filter((d) => d.value > 0)
    .sort((a, b) => b.value - a.value)
    .slice(0, 6);

  const byAudience = new Map<string, number>();
  for (const r of confirmed) byAudience.set(r.ticketType.audience, (byAudience.get(r.ticketType.audience) ?? 0) + 1);
  const ticketDist = [...byAudience.entries()].map(([label, value], i) => ({
    label: label[0] + label.slice(1).toLowerCase(), value, color: CHART_COLORS[i % CHART_COLORS.length],
  })).sort((a, b) => b.value - a.value);

  const byState = new Map<string, number>();
  for (const r of regs) {
    const st = r.conference.state ?? "Unspecified";
    byState.set(st, (byState.get(st) ?? 0) + 1);
  }
  const geo = [...byState.entries()].map(([label, value]) => ({ label, value })).sort((a, b) => b.value - a.value).slice(0, 6);

  const rangeHref = (k: string) => (k === "all" ? "/dashboard" : `/dashboard?range=${k}`);

  return (
    <main>
      <PageHeader
        title={`${org.name} — Overview`}
        sub={`Welcome back, ${user.name.split(" ")[0]} · ${now.toLocaleDateString("en-IN", { weekday: "long", day: "numeric", month: "long", year: "numeric", timeZone: "Asia/Kolkata" })}`}
        action={
          <div className="flex gap-2">
            <Link href="/dashboard/reports" className={btn.secondary}>📊 Reports</Link>
            {canCreate && <Link href="/dashboard/conferences/new" className={btn.primary}>+ Create Conference</Link>}
          </div>
        }
      />

      {/* Date filter */}
      <div className="mb-5 flex flex-wrap items-center gap-2">
        {RANGES.map((r) => (
          <Link
            key={r.key}
            href={rangeHref(r.key)}
            className={`rounded-full px-3 py-1 text-xs font-semibold transition ${
              rangeKey === r.key ? "bg-indigo-500 text-white shadow-md shadow-indigo-500/30" : "border border-white/70 bg-white/50 text-zinc-400 hover:text-zinc-100"
            }`}
          >
            {r.label}
          </Link>
        ))}
        <form className="ml-1 flex items-center gap-1.5 text-xs" action="/dashboard">
          <input type="hidden" name="range" value="custom" />
          <input type="date" name="from" defaultValue={sp.from} className="rounded-lg border border-white/80 bg-white/70 px-2 py-1 text-xs text-zinc-200" aria-label="From date" />
          <span className="text-zinc-500">→</span>
          <input type="date" name="to" defaultValue={sp.to} className="rounded-lg border border-white/80 bg-white/70 px-2 py-1 text-xs text-zinc-200" aria-label="To date" />
          <button className={`${btn.smSecondary} !py-1`}>Apply</button>
        </form>
        {rangeKey === "custom" && <Badge className="bg-indigo-500/10 text-indigo-600">Custom range</Badge>}
      </div>

      {/* KPI cards */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
        <StatCard label="Total Conferences" value={conferences.length} />
        <StatCard label="Upcoming" value={upcoming.length} accent="text-sky-600" />
        <StatCard label="Completed" value={completed.length} accent="text-violet-600" />
        <StatCard label="Total Visitors" value={regs.length} sub={rangeKey !== "all" ? "in selected range" : "all registrations"} />
        <StatCard label="Confirmed" value={confirmed.length} accent="text-emerald-600" />
        <StatCard label="Checked-in" value={checkedIn} />
        <StatCard label="Speakers" value={speakerCount} />
        <StatCard label="Sponsors" value={sponsors.length} sub={sponsorRevenue > 0 ? `${formatMoney(sponsorRevenue)} committed` : undefined} />
        <StatCard label="Ticket Revenue" value={formatMoney(revenue)} accent="text-emerald-600" />
        <StatCard label="Pending Payments" value={formatMoney(pendingAmount)} accent={pendingAmount > 0 ? "text-amber-600" : "text-zinc-100"} />
        <StatCard label="Assets" value={assetCount} />
        <StatCard label="Team Members" value={teamCount} />
      </div>

      {/* Analytics */}
      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <Card className="p-5">
          <h3 className="text-sm font-semibold text-zinc-200">Registrations over time</h3>
          <p className="text-xs text-zinc-500">{byDay ? "Daily" : "Monthly"} visitor registrations</p>
          <div className="mt-3"><AreaChart data={regSeries} /></div>
        </Card>
        <Card className="p-5">
          <h3 className="text-sm font-semibold text-zinc-200">Revenue by conference</h3>
          <p className="text-xs text-zinc-500">Confirmed ticket revenue, top conferences</p>
          <div className="mt-4"><HBars data={revenueByConf} format={(v) => formatMoney(v)} /></div>
        </Card>
        <Card className="p-5">
          <h3 className="text-sm font-semibold text-zinc-200">Ticket category distribution</h3>
          <p className="text-xs text-zinc-500">Confirmed registrations by pass category</p>
          <div className="mt-4"><Donut data={ticketDist} centerLabel="confirmed" /></div>
        </Card>
        <Card className="p-5">
          <h3 className="text-sm font-semibold text-zinc-200">Geographic distribution</h3>
          <p className="text-xs text-zinc-500">Visitors by conference state</p>
          <div className="mt-4"><HBars data={geo} color="#8b5cf6" /></div>
        </Card>
      </div>

      {/* Finance strip */}
      <Card className="mt-6 flex flex-wrap items-center justify-between gap-4 p-5">
        <div className="flex flex-wrap gap-8">
          <div><div className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Revenue</div><div className="mt-1 text-lg font-bold text-emerald-600 tabular-nums">{formatMoney(revenue + sponsorRevenue)}</div></div>
          <div><div className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Expenses</div><div className="mt-1 text-lg font-bold text-red-500 tabular-nums">{formatMoney(expenseTotal)}</div></div>
          <div><div className="text-xs font-semibold uppercase tracking-wider text-zinc-500">Net</div><div className={`mt-1 text-lg font-bold tabular-nums ${revenue + sponsorRevenue - expenseTotal >= 0 ? "text-zinc-100" : "text-red-500"}`}>{formatMoney(revenue + sponsorRevenue - expenseTotal)}</div></div>
        </div>
        <Link href="/dashboard/finances" className={btn.secondary}>Open Finances →</Link>
      </Card>

      {/* Upcoming conferences */}
      <div className="mt-8">
        <div className="mb-3 flex items-baseline justify-between">
          <h2 className="text-base font-bold text-zinc-100">Upcoming conferences</h2>
          <Link href="/dashboard/conferences" className="text-sm font-medium text-indigo-600 hover:underline">All conferences →</Link>
        </div>
        {upcoming.length === 0 ? (
          <EmptyState
            title="Nothing on the calendar"
            body="Create a conference to see it here with registrations, revenue and capacity at a glance."
            action={canCreate ? <Link href="/dashboard/conferences/new" className={btn.primary}>Create a conference</Link> : undefined}
          />
        ) : (
          <Card className="overflow-x-auto">
            <table className="w-full min-w-[840px] text-sm">
              <thead>
                <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                  <th className="px-4 py-3">Conference</th>
                  <th className="px-3 py-3">Date</th>
                  <th className="px-3 py-3">Status</th>
                  <th className="px-3 py-3">Registrations</th>
                  <th className="px-3 py-3">Revenue</th>
                  <th className="px-3 py-3">Speakers</th>
                  <th className="px-3 py-3">Sponsors</th>
                  <th className="px-3 py-3">Venue</th>
                  <th className="px-3 py-3"></th>
                </tr>
              </thead>
              <tbody>
                {upcoming.slice(0, 8).map((c) => (
                  <tr key={c.id} className="border-b border-zinc-800/40 transition hover:bg-white/50">
                    <td className="px-4 py-3">
                      <Link href={`/dashboard/c/${c.id}`} className="flex items-center gap-2.5 font-semibold text-zinc-100 hover:text-indigo-700">
                        <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-xs font-bold text-white" style={{ background: c.primaryColor }}>{c.name[0]}</span>
                        <span className="max-w-[200px] truncate">{c.name}</span>
                      </Link>
                    </td>
                    <td className="whitespace-nowrap px-3 py-3 text-zinc-400">{dateRange(c.startAt, c.endAt)}</td>
                    <td className="px-3 py-3"><StatusBadge status={c.status} /></td>
                    <td className="px-3 py-3 tabular-nums text-zinc-300">
                      {c._count.registrations}{c.capacity ? <span className="text-zinc-500"> / {c.capacity}</span> : ""}
                    </td>
                    <td className="px-3 py-3 tabular-nums text-zinc-300">{formatMoney(c.registrations.reduce((s, r) => s + r.amount, 0))}</td>
                    <td className="px-3 py-3 tabular-nums text-zinc-300">{c._count.speakers}</td>
                    <td className="px-3 py-3 tabular-nums text-zinc-300">{c._count.sponsors}</td>
                    <td className="max-w-[140px] truncate px-3 py-3 text-zinc-400">{c.venueName ?? "—"}</td>
                    <td className="px-3 py-3"><Link href={`/dashboard/c/${c.id}`} className={btn.smSecondary}>Manage</Link></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        )}
      </div>
    </main>
  );
}
