import { createFileRoute } from "@tanstack/react-router";
import { Bar, BarChart, CartesianGrid, Cell, Pie, PieChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import { toast } from "sonner";

import { Page } from "@/components/app/Page";
import { PageHeading, SectionHeading, formatINR } from "@/components/app/Primitives";
import { Button } from "@/components/ui/button";
import { bookings, guests, payments, trips } from "@/data/mock";
import { destinationImage } from "@/lib/images";
import { outstandingTotal, upcomingTrips } from "@/lib/ops";

export const Route = createFileRoute("/reports")({
  head: () => ({
    meta: [
      { title: "Reports | KareVoyage Operations" },
      { name: "description", content: "Revenue, bookings, destination demand and membership mix across the business." },
      { property: "og:title", content: "Reports | KareVoyage Operations" },
      { property: "og:description", content: "Operational and commercial insight for KareVoyage." },
    ],
  }),
  component: ReportsPage,
});

const CHART_COLORS = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"];

function ReportsPage() {
  const byMonth = (() => {
    const map = new Map<string, number>();
    bookings.forEach((b) => {
      const key = b.bookingDate.slice(0, 7);
      map.set(key, (map.get(key) ?? 0) + b.amount);
    });
    return [...map.entries()]
      .sort((a, b) => a[0].localeCompare(b[0]))
      .slice(-8)
      .map(([month, value]) => ({
        month: new Date(`${month}-01`).toLocaleDateString("en-GB", { month: "short" }),
        value: Math.round(value / 100000),
      }));
  })();

  const byDestination = (() => {
    const map = new Map<string, number>();
    trips.forEach((t) => map.set(t.destination, (map.get(t.destination) ?? 0) + t.guests));
    return [...map.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6).map(([destination, travellers]) => ({ destination, travellers }));
  })();

  const membership = (["Infinity", "Platinum", "Gold", "None"] as const).map((tier) => ({
    name: tier,
    value: guests.filter((g) => g.membership === tier).length,
  }));

  const revenue = bookings.reduce((s, b) => s + b.amount, 0);
  const collected = payments.reduce((s, p) => s + p.paid, 0);

  return (
    <Page className="space-y-8">
      <PageHeading
        title="Reports"
        description="How the business is travelling: revenue, demand and membership mix."
        actions={<Button variant="outline" onClick={() => toast.success("Report exported as CSV.")}>Export</Button>}
      />

      <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {[
          { label: "Booked value", value: formatINR(revenue) },
          { label: "Collected", value: formatINR(collected) },
          { label: "Outstanding", value: formatINR(outstandingTotal) },
          { label: "Upcoming departures", value: String(upcomingTrips.length) },
        ].map((s) => (
          <div key={s.label} className="rounded-xl border border-border bg-surface px-5 py-4">
            <p className="kv-eyebrow">{s.label}</p>
            <p className="mt-2 font-display text-[26px] leading-none">{s.value}</p>
          </div>
        ))}
      </section>

      <section className="grid gap-6 lg:grid-cols-3">
        <div className="rounded-xl border border-border bg-surface p-5 lg:col-span-2">
          <SectionHeading title="Booked value by month" description="In lakhs (₹L)." />
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={byMonth}>
                <CartesianGrid vertical={false} stroke="var(--border)" />
                <XAxis dataKey="month" stroke="var(--muted-foreground)" fontSize={12} tickLine={false} axisLine={false} />
                <YAxis stroke="var(--muted-foreground)" fontSize={12} tickLine={false} axisLine={false} />
                <Tooltip
                  cursor={{ fill: "var(--muted)" }}
                  contentStyle={{ background: "var(--popover)", border: "1px solid var(--border)", borderRadius: 12, fontSize: 12 }}
                />
                <Bar dataKey="value" fill="var(--chart-1)" radius={[6, 6, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

        <div className="rounded-xl border border-border bg-surface p-5">
          <SectionHeading title="Membership mix" />
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie data={membership} dataKey="value" nameKey="name" innerRadius={52} outerRadius={80} paddingAngle={3}>
                  {membership.map((m, i) => (
                    <Cell key={m.name} fill={CHART_COLORS[i % CHART_COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip contentStyle={{ background: "var(--popover)", border: "1px solid var(--border)", borderRadius: 12, fontSize: 12 }} />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <ul className="mt-2 space-y-1.5">
            {membership.map((m, i) => (
              <li key={m.name} className="flex items-center justify-between text-xs">
                <span className="flex items-center gap-2">
                  <span className="h-2 w-2 rounded-full" style={{ background: CHART_COLORS[i % CHART_COLORS.length] }} aria-hidden />
                  {m.name}
                </span>
                <span className="tabular-nums text-muted-foreground">{m.value}</span>
              </li>
            ))}
          </ul>
        </div>
      </section>

      <section>
        <SectionHeading title="Destination demand" description="Travellers booked by destination." />
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {byDestination.map((d) => (
            <div key={d.destination} className="overflow-hidden rounded-xl border border-border bg-surface">
              <img src={destinationImage(d.destination)} alt="" loading="lazy" width={640} height={400} className="h-24 w-full object-cover" />
              <div className="flex items-baseline justify-between px-4 py-3">
                <p className="text-sm font-medium">{d.destination}</p>
                <p className="text-sm tabular-nums text-muted-foreground">{d.travellers} travellers</p>
              </div>
            </div>
          ))}
        </div>
      </section>
    </Page>
  );
}
