import { createFileRoute, Link } from "@tanstack/react-router";
import {
  AlertTriangle,
  ArrowRight,
  BedDouble,
  CreditCard,
  FileWarning,
  Plane,
  UserRound,
} from "lucide-react";

import { Page } from "@/components/app/Page";
import {
  Avatar,
  MetricCard,
  ProgressBar,
  SectionHeading,
  formatDate,
  formatINR,
} from "@/components/app/Primitives";
import { StatusPill } from "@/components/app/StatusPill";
import { Button } from "@/components/ui/button";
import { useAdminProfile } from "@/features/auth/api";
import { destinationImage } from "@/lib/images";
import {
  activeTrips,
  attentionItems,
  daysUntil,
  departuresToday,
  docsNeedingAttention,
  operationalAlerts,
  outstandingTotal,
  recentOperationalActivity,
  todayLabel,
  todaysOperations,
  travellersOnUpcoming,
  tripReadiness,
  upcomingTrips,
} from "@/lib/ops";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Operations command centre | KareVoyage Operations" },
      {
        name: "description",
        content:
          "Today's departures, trip readiness, overdue payments, supplier confirmations and document alerts in one travel operations command centre.",
      },
      { property: "og:title", content: "Operations command centre | KareVoyage Operations" },
      {
        property: "og:description",
        content: "What is happening today, what needs attention, and which journeys are not ready.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: Dashboard,
});

const alertIcon = {
  Flight: Plane,
  Hotel: BedDouble,
  Document: FileWarning,
  Payment: CreditCard,
  Guest: UserRound,
} as const;

function Dashboard() {
  const journeys = upcomingTrips.slice(0, 3);
  const readinessTrips = upcomingTrips.slice(0, 5);
  const { data: admin } = useAdminProfile();
  const firstName = admin?.fullName.split(" ")[0] ?? "there";

  return (
    <Page className="space-y-12">
      {/* Greeting */}
      <header>
        <p className="kv-eyebrow">{todayLabel}</p>
        <h1 className="mt-2 text-[32px] leading-tight">Good morning, {firstName}</h1>
        <p className="mt-2 text-sm text-muted-foreground">
          {departuresToday.length} departures today · {activeTrips.length} journeys on the road ·{" "}
          {attentionItems.reduce((s, a) => s + a.count, 0)} items need attention.
        </p>
      </header>

      {/* A — Today's overview */}
      <section>
        <SectionHeading title="Today's overview" description="The shape of operations right now." />
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-6">
          <MetricCard
            label="Active trips"
            value={activeTrips.length}
            hint="On the road"
            to="/trips"
          />
          <MetricCard
            label="Upcoming trips"
            value={upcomingTrips.length}
            hint="Confirmed departures"
            to="/trips"
          />
          <MetricCard
            label="Departures today"
            value={departuresToday.length}
            hint="Leaving in the next 24h"
            to="/trips"
          />
          <MetricCard
            label="Travellers"
            value={travellersOnUpcoming}
            hint="Booked on upcoming journeys"
            to="/guests"
          />
          <MetricCard
            label="Outstanding"
            value={formatINR(outstandingTotal)}
            hint="Across open bookings"
            tone="warning"
            to="/payments"
          />
          <MetricCard
            label="Documents"
            value={docsNeedingAttention.length}
            hint="Need verification or renewal"
            tone="danger"
            to="/documents"
          />
        </div>
      </section>

      {/* B — Needs your attention */}
      <section>
        <SectionHeading
          title="Needs your attention"
          description="Everything blocking a journey right now — each with one next step."
        />
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {attentionItems.map((item) => (
            <div
              key={item.label}
              className="flex flex-col rounded-xl border border-border bg-surface p-5"
            >
              <div className="flex items-start gap-3">
                <span
                  className={cn(
                    "font-display text-[28px] leading-none",
                    item.tone === "danger"
                      ? "text-destructive"
                      : item.tone === "warning"
                        ? "text-warning-foreground"
                        : "text-foreground",
                  )}
                >
                  {item.count}
                </span>
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-medium text-foreground">{item.label}</p>
                  <p className="mt-1 text-xs text-muted-foreground">{item.description}</p>
                </div>
              </div>
              <Button
                variant="ghost"
                size="sm"
                className="mt-4 w-fit gap-1.5 px-0 text-xs text-primary hover:bg-transparent"
                asChild
              >
                <Link to={item.to as "/"}>
                  {item.cta} <ArrowRight className="h-3.5 w-3.5" />
                </Link>
              </Button>
            </div>
          ))}
        </div>
      </section>

      <div className="grid gap-10 xl:grid-cols-[minmax(0,1fr)_360px]">
        <div className="space-y-12">
          {/* C — Upcoming journeys */}
          <section>
            <SectionHeading
              title="Upcoming journeys"
              description="The next departures and how ready they are."
              action={
                <Button variant="ghost" size="sm" asChild>
                  <Link to="/trips">View all trips</Link>
                </Button>
              }
            />
            <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {journeys.map((trip) => {
                const r = tripReadiness(trip);
                return (
                  <div
                    key={trip.id}
                    className="group overflow-hidden rounded-xl border border-border bg-surface transition-shadow hover:shadow-[var(--shadow-soft)]"
                  >
                    <div className="relative h-32 overflow-hidden">
                      <img
                        src={destinationImage(trip.destination)}
                        alt={`${trip.destination} landscape`}
                        loading="lazy"
                        width={1024}
                        height={640}
                        className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-[1.03]"
                      />
                      <span className="absolute right-3 top-3">
                        <StatusPill value={trip.status} className="bg-background/90" />
                      </span>
                    </div>
                    <div className="space-y-3 p-4">
                      <div>
                        <p className="kv-eyebrow">{trip.destination}</p>
                        <h3 className="mt-1 truncate text-base">{trip.tour}</h3>
                        <p className="mt-1 text-xs text-muted-foreground">
                          {formatDate(trip.departure)} – {formatDate(trip.returnDate)} ·{" "}
                          {trip.guests} travellers
                        </p>
                      </div>
                      <span className="flex items-center gap-2 text-xs text-muted-foreground">
                        <Avatar name={trip.tourManager} className="h-6 w-6 text-[10px]" />
                        {trip.tourManager}
                      </span>
                      <div>
                        <div className="mb-1.5 flex items-center justify-between text-xs text-muted-foreground">
                          <span>Readiness</span>
                          <span className="tabular-nums">{r.score}%</span>
                        </div>
                        <ProgressBar
                          value={r.score}
                          tone={r.score > 85 ? "success" : r.score > 60 ? "brand" : "warning"}
                        />
                      </div>
                      <Button variant="outline" size="sm" className="w-full" asChild>
                        <Link to="/trips/$id" params={{ id: trip.id }}>
                          Open trip
                        </Link>
                      </Button>
                    </div>
                  </div>
                );
              })}
            </div>
          </section>

          {/* D — Trip readiness */}
          <section>
            <SectionHeading
              title="Trip readiness"
              description="Where each upcoming journey stands across the four things that block a departure."
            />
            <div className="overflow-hidden rounded-xl border border-border bg-surface">
              {readinessTrips.map((trip, i) => {
                const r = tripReadiness(trip);
                const cells = [
                  {
                    label: "Guests",
                    value: `${r.guestsConfirmed}/${r.guestsTotal}`,
                    pct: (r.guestsConfirmed / r.guestsTotal) * 100,
                  },
                  {
                    label: "Documents",
                    value: r.docsTotal ? `${r.docsVerified}/${r.docsTotal}` : "—",
                    pct: r.docsTotal ? (r.docsVerified / r.docsTotal) * 100 : 0,
                  },
                  {
                    label: "Payments",
                    value: r.totalAmount
                      ? `${Math.round((r.paidAmount / r.totalAmount) * 100)}%`
                      : "—",
                    pct: r.totalAmount ? (r.paidAmount / r.totalAmount) * 100 : 0,
                  },
                  {
                    label: "Itinerary",
                    value: r.itineraryComplete
                      ? "Complete"
                      : `${r.itineraryPlanned}/${r.itineraryDays}`,
                    pct: r.itineraryDays ? (r.itineraryPlanned / r.itineraryDays) * 100 : 0,
                  },
                ];
                return (
                  <Link
                    key={trip.id}
                    to="/trips/$id"
                    params={{ id: trip.id }}
                    className={cn(
                      "flex flex-wrap items-center gap-x-6 gap-y-4 px-5 py-4 transition-colors hover:bg-muted/50",
                      i > 0 && "border-t border-border",
                    )}
                  >
                    <div className="min-w-[190px] flex-1">
                      <p className="truncate text-sm font-medium">{trip.tour}</p>
                      <p className="text-xs text-muted-foreground">
                        {formatDate(trip.departure)} · in {daysUntil(trip.departure)} days
                      </p>
                    </div>
                    {cells.map((c) => (
                      <div key={c.label} className="w-[104px]">
                        <p className="text-[11px] text-muted-foreground">{c.label}</p>
                        <p className="text-xs font-medium tabular-nums">{c.value}</p>
                        <ProgressBar
                          className="mt-1.5"
                          value={c.pct}
                          tone={c.pct >= 99 ? "success" : c.pct > 55 ? "brand" : "warning"}
                        />
                      </div>
                    ))}
                    <div className="w-[86px] text-right">
                      <p className="text-[11px] text-muted-foreground">Overall</p>
                      <p
                        className={cn(
                          "font-display text-lg leading-none",
                          r.score > 85
                            ? "text-success"
                            : r.score > 60
                              ? "text-foreground"
                              : "text-warning-foreground",
                        )}
                      >
                        {r.score}%
                      </p>
                    </div>
                  </Link>
                );
              })}
            </div>
          </section>

          {/* E — Today's operations */}
          <section>
            <SectionHeading
              title="Today's operations"
              description="Movements, activities and who is responsible."
            />
            <ol className="relative space-y-4 border-l border-border pl-6">
              {todaysOperations.map((e, i) => (
                <li key={`${e.time}-${e.title}-${i}`} className="relative">
                  <span
                    className="absolute -left-[27px] top-3 h-2 w-2 rounded-full bg-primary"
                    aria-hidden
                  />
                  <div className="flex flex-wrap items-center gap-x-5 gap-y-2 rounded-xl border border-border bg-surface px-4 py-3">
                    <p className="w-14 font-mono text-xs text-muted-foreground">{e.time}</p>
                    <div className="min-w-[180px] flex-1">
                      <p className="text-sm font-medium text-foreground">{e.title}</p>
                      <p className="text-xs text-muted-foreground">{e.detail}</p>
                    </div>
                    <div className="min-w-[150px]">
                      <p className="truncate text-xs text-foreground">{e.tripName}</p>
                      <p className="text-xs text-muted-foreground">{e.travellers} travellers</p>
                    </div>
                    <span className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Avatar name={e.owner} className="h-6 w-6 text-[10px]" />
                      {e.owner}
                    </span>
                    <StatusPill value={e.status} />
                    <Button variant="ghost" size="sm" className="ml-auto gap-1 text-xs" asChild>
                      <Link to="/trips/$id" params={{ id: e.tripId }}>
                        Open <ArrowRight className="h-3.5 w-3.5" />
                      </Link>
                    </Button>
                  </div>
                </li>
              ))}
            </ol>
          </section>
        </div>

        {/* Right rail */}
        <aside className="space-y-10">
          {/* F — Operational alerts */}
          <section>
            <SectionHeading
              title="Operational alerts"
              description="Live exceptions from suppliers and travellers."
            />
            <ul className="space-y-2.5">
              {operationalAlerts.map((a, i) => {
                const Icon = alertIcon[a.kind];
                return (
                  <li key={`${a.title}-${i}`}>
                    <Link
                      to={a.to as "/"}
                      className="flex items-start gap-3 rounded-xl border border-border bg-surface px-4 py-3 transition-colors hover:border-border-strong"
                    >
                      <Icon
                        className={cn(
                          "mt-0.5 h-4 w-4 shrink-0",
                          a.tone === "danger" ? "text-destructive" : "text-warning",
                        )}
                      />
                      <span className="min-w-0 flex-1">
                        <span className="block text-sm font-medium text-foreground">{a.title}</span>
                        <span className="block truncate text-xs text-muted-foreground">
                          {a.detail}
                        </span>
                      </span>
                    </Link>
                  </li>
                );
              })}
              {operationalAlerts.length === 0 ? (
                <li className="rounded-xl border border-dashed border-border px-4 py-6 text-center text-xs text-muted-foreground">
                  No active exceptions. Everything is running to plan.
                </li>
              ) : null}
            </ul>
          </section>

          {/* G — Recent activity */}
          <section>
            <SectionHeading title="Recent activity" />
            <ul className="space-y-3">
              {recentOperationalActivity.map((a) => (
                <li key={a.id} className="flex gap-3">
                  <Avatar name={a.user} className="h-7 w-7 text-[10px]" />
                  <div className="min-w-0">
                    <p className="truncate text-sm text-foreground">
                      {a.user}{" "}
                      <span className="text-muted-foreground">{a.action.toLowerCase()}</span>
                    </p>
                    <p className="truncate text-xs text-muted-foreground">
                      {a.record} · {formatDate(a.date)}
                    </p>
                  </div>
                </li>
              ))}
            </ul>
          </section>

          <section>
            <SectionHeading
              title="Trips not ready"
              description="Departing soon, below 75% readiness."
            />
            <ul className="space-y-2">
              {upcomingTrips
                .filter((t) => tripReadiness(t).score < 75)
                .slice(0, 5)
                .map((t) => (
                  <li key={t.id}>
                    <Link
                      to="/trips/$id"
                      params={{ id: t.id }}
                      className="flex items-center gap-3 rounded-lg border border-border bg-surface px-3.5 py-2.5 transition-colors hover:border-border-strong"
                    >
                      <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-warning" />
                      <span className="min-w-0 flex-1">
                        <span className="block truncate text-sm">{t.tour}</span>
                        <span className="block text-xs text-muted-foreground">
                          in {daysUntil(t.departure)} days
                        </span>
                      </span>
                      <span className="text-xs tabular-nums text-muted-foreground">
                        {tripReadiness(t).score}%
                      </span>
                    </Link>
                  </li>
                ))}
            </ul>
          </section>
        </aside>
      </div>
    </Page>
  );
}
