import { generatePageMetadata } from "@/lib/seo/metadata";
import { cn } from "@/lib/utils";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  BadgeIndianRupee,
  CalendarCheck,
  Car,
  CheckCircle2,
  Hotel,
  Package,
  Plane,
} from "lucide-react";
import type { Metadata } from "next";

export const metadata: Metadata = generatePageMetadata({
  title: "Admin Dashboard",
  description: "Ameera Holidays Platform administration dashboard",
  path: "/admin/dashboard",
  noIndex: true,
});

const topMetrics = [
  {
    label: "Active Bookings",
    value: "1,247",
    change: "+21.5%",
    icon: CalendarCheck,
  },
  {
    label: "Converted Leads",
    value: "318",
    change: "+8.8%",
    icon: CheckCircle2,
  },
  {
    label: "Completed Trips",
    value: "2,356",
    change: "+14.8%",
    icon: Plane,
  },
];

const salesTrend = [
  [10, 112],
  [24, 108],
  [38, 65],
  [52, 154],
  [66, 92],
  [80, 136],
  [94, 130],
];

const revenueTrend = [
  { month: "Feb", revenue: 112, expense: 58 },
  { month: "Mar", revenue: 141, expense: 72 },
  { month: "Apr", revenue: 126, expense: 64 },
  { month: "May", revenue: 167, expense: 88 },
  { month: "Jun", revenue: 162, expense: 91 },
  { month: "Jul", revenue: 191, expense: 67 },
];

const routeRows = [
  { route: "Haridwar - Kedarnath", value: "234 trips", percent: 92 },
  { route: "Delhi - Rishikesh", value: "188 trips", percent: 73 },
  { route: "Chandigarh - Kangra", value: "156 trips", percent: 61 },
  { route: "Una - Amb - Kangra", value: "129 trips", percent: 52 },
];

const scheduleBars = [
  { month: "Jan", bookings: 112, cancellations: 46 },
  { month: "Feb", bookings: 145, cancellations: 71 },
  { month: "Mar", bookings: 168, cancellations: 93 },
  { month: "Apr", bookings: 151, cancellations: 82 },
  { month: "May", bookings: 188, cancellations: 116 },
  { month: "Jun", bookings: 164, cancellations: 77 },
  { month: "Jul", bookings: 132, cancellations: 95 },
  { month: "Aug", bookings: 196, cancellations: 121 },
];

const bookingRows = [
  {
    vendor: "Teertham Routes",
    count: 180,
    from: "DEL",
    to: "KED",
    time: "09:30 AM",
    amount: "INR 14.8K",
    code: "KEDARNATH25",
    description: "Route booking confirmed for the next spiritual departure.",
    action: "VIEW",
    active: true,
  },
  {
    vendor: "Ameera Cabs",
    count: 230,
    from: "IXC",
    to: "DHM",
    time: "11:10 AM",
    amount: "INR 23.2K",
    code: "VEHICLEPRO",
    description: "Vehicle bookings increased on premium route packages.",
    action: "OPEN",
    active: false,
  },
  {
    vendor: "Himalayan Stays",
    count: 160,
    from: "HRD",
    to: "RDP",
    time: "02:00 PM",
    amount: "INR 18.0K",
    code: "HOTELSTAY",
    description: "Hotel partners received fresh confirmed reservations.",
    action: "OPEN",
    active: false,
  },
  {
    vendor: "Nimbus Holidays",
    count: 200,
    from: "KGR",
    to: "AMB",
    time: "04:45 PM",
    amount: "INR 31.6K",
    code: "PACKAGEPLUS",
    description: "Package sales are trending up for family itineraries.",
    action: "OPEN",
    active: false,
  },
  {
    vendor: "Spiritual Express",
    count: 145,
    from: "HRD",
    to: "BAD",
    time: "06:20 AM",
    amount: "INR 22.4K",
    code: "SPIRITUAL15",
    description: "Morning yatra bookings are active for Badrinath departures.",
    action: "OPEN",
    active: false,
  },
  {
    vendor: "Temple Connect",
    count: 118,
    from: "RDP",
    to: "UNA",
    time: "01:35 PM",
    amount: "INR 16.7K",
    code: "TEMPLEPASS",
    description: "Temple route reservations are filling across hill circuits.",
    action: "OPEN",
    active: false,
  },
  {
    vendor: "Divine Hotels",
    count: 94,
    from: "AMB",
    to: "KGR",
    time: "07:15 PM",
    amount: "INR 12.9K",
    code: "STAYMORE",
    description: "Partner stays received steady bookings for family rooms.",
    action: "OPEN",
    active: false,
  },
  {
    vendor: "Pilgrim Wheels",
    count: 82,
    from: "IXC",
    to: "UNA",
    time: "10:50 AM",
    amount: "INR 10.8K",
    code: "CABREADY",
    description: "Cab inventory remains available for same-day transfers.",
    action: "OPEN",
    active: false,
  },
];

function pointsToPath(points: number[][]) {
  return points
    .map(([x, y], index) => `${index === 0 ? "M" : "L"}${x} ${y}`)
    .join(" ");
}

function MetricCard({
  label,
  value,
  change,
  icon: Icon,
}: (typeof topMetrics)[number]) {
  return (
    <Card className="admin-card rounded-xl border-0">
      <CardContent className="flex items-center gap-4 p-5">
        <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-sm">
          <Icon className="h-5 w-5" />
        </div>
        <div className="min-w-0 flex-1">
          <p className="truncate text-sm font-medium text-muted-foreground">
            {label}
          </p>
          <div className="mt-1 flex items-end gap-2">
            <p className="text-3xl font-bold leading-none text-foreground">
              {value}
            </p>
            <span className="rounded-md bg-primary/10 px-1.5 py-0.5 text-xs font-bold text-primary">
              {change}
            </span>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

function TicketSalesCard() {
  return (
    <Card className="admin-card rounded-xl border-0">
      <CardHeader className="flex flex-row items-start justify-between gap-4 pb-2">
        <div>
          <CardTitle className="text-base">Booking Sales</CardTitle>
          <CardDescription>Static six-month overview</CardDescription>
        </div>
        <span className="rounded-md bg-primary/10 px-3 py-1 text-xs font-bold text-primary">
          Last 6 Months
        </span>
      </CardHeader>
      <CardContent>
        <div className="flex items-end gap-2">
          <p className="text-3xl font-bold">12,500</p>
          <span className="mb-1 text-xs text-muted-foreground">
            tickets sold
          </span>
        </div>
        <div className="mt-5 h-32">
          <svg
            viewBox="0 0 104 170"
            preserveAspectRatio="none"
            className="h-full w-full overflow-visible"
            aria-hidden="true"
          >
            <defs>
              <linearGradient id="salesFill" x1="0" x2="0" y1="0" y2="1">
                <stop
                  offset="0%"
                  stopColor="hsl(var(--primary))"
                  stopOpacity="0.28"
                />
                <stop
                  offset="100%"
                  stopColor="hsl(var(--primary))"
                  stopOpacity="0"
                />
              </linearGradient>
            </defs>
            <path
              d={`${pointsToPath(salesTrend)} L94 168 L10 168 Z`}
              fill="url(#salesFill)"
            />
            <path
              d={pointsToPath(salesTrend)}
              fill="none"
              stroke="hsl(var(--foreground))"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="3"
            />
          </svg>
        </div>
        <div className="mt-2 grid grid-cols-6 text-center text-xs text-muted-foreground">
          {["Jan", "Feb", "Mar", "Apr", "May", "Jun"].map((month) => (
            <span key={month}>{month}</span>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

function RevenueGrowthCard() {
  return (
    <Card className="admin-card rounded-xl border-0 lg:col-span-2">
      <CardHeader className="flex flex-row items-start justify-between gap-4 pb-3">
        <div>
          <CardTitle className="text-base">Revenue Growth</CardTitle>
          <CardDescription>Income and expense by month</CardDescription>
        </div>
        <span className="rounded-md bg-primary/10 px-3 py-1 text-xs font-bold text-primary">
          Last 6 Months
        </span>
      </CardHeader>
      <CardContent>
        <div className="mb-4 flex items-center gap-4 text-xs">
          <span className="flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded-full bg-primary" />
            Income
          </span>
          <span className="flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded-full bg-foreground" />
            Expense
          </span>
        </div>
        <div className="relative h-56">
          <div className="absolute inset-x-0 top-0 border-t border-border/60" />
          <div className="absolute inset-x-0 top-1/3 border-t border-border/60" />
          <div className="absolute inset-x-0 top-2/3 border-t border-border/60" />
          <svg
            viewBox="0 0 520 210"
            preserveAspectRatio="none"
            className="absolute inset-0 h-full w-full"
            aria-hidden="true"
          >
            <path
              d="M20 105 L115 78 L210 90 L305 52 L400 57 L495 24"
              fill="none"
              stroke="hsl(var(--primary))"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="4"
            />
            <path
              d="M20 158 L115 143 L210 151 L305 128 L400 125 L495 150"
              fill="none"
              stroke="hsl(var(--foreground))"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="4"
            />
            <line
              x1="305"
              x2="305"
              y1="52"
              y2="202"
              stroke="hsl(var(--border))"
              strokeDasharray="4 4"
            />
            <circle cx="305" cy="52" r="6" fill="hsl(var(--primary))" />
          </svg>
          <div className="absolute left-[55%] top-4 rounded-md bg-foreground px-2.5 py-1 text-xs font-bold text-background">
            INR 18.4K
          </div>
        </div>
        <div className="grid grid-cols-6 text-center text-xs text-muted-foreground">
          {revenueTrend.map((item) => (
            <span key={item.month}>{item.month}</span>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

function CustomerGrowthCard() {
  return (
    <Card className="rounded-xl border-0 bg-foreground text-background shadow-lg">
      <CardHeader className="pb-2">
        <CardTitle className="text-base text-background">
          Customer Growth
        </CardTitle>
        <CardDescription className="text-background/60">
          From last month
        </CardDescription>
      </CardHeader>
      <CardContent className="flex flex-col items-center">
        <div className="relative mt-2 h-40 w-40">
          <div className="absolute inset-0 rounded-full border-[18px] border-background/15" />
          <div className="absolute inset-0 rounded-full border-[18px] border-transparent border-l-primary border-t-primary rotate-[-35deg]" />
          <div className="absolute inset-10 rounded-full border border-primary/70" />
          <div className="absolute left-1/2 top-1/2 h-2.5 w-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary" />
          <div className="absolute left-1/2 top-1/2 h-20 w-1 origin-bottom -translate-x-1/2 -translate-y-full rotate-[-38deg] rounded-full bg-primary" />
        </div>
        <p className="mt-2 text-4xl font-bold text-background">25%</p>
        <p className="text-xs font-medium uppercase tracking-wide text-background/60">
          from last month
        </p>
      </CardContent>
    </Card>
  );
}

function TopRoutesCard() {
  return (
    <Card className="admin-card rounded-xl border-0">
      <CardHeader className="pb-3">
        <CardTitle className="text-base">Top Travel Routes</CardTitle>
        <CardDescription>Most booked routes this season</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {routeRows.map((row, index) => (
          <div key={row.route} className="space-y-1.5">
            <div className="flex items-center justify-between text-sm">
              <span className="font-medium text-foreground">{row.route}</span>
              <span className="text-xs text-muted-foreground">{row.value}</span>
            </div>
            <div className="h-5 rounded-sm bg-muted">
              <div
                className={cn(
                  "h-full rounded-sm",
                  index % 2 === 0 ? "bg-foreground" : "bg-primary"
                )}
                style={{ width: `${row.percent}%` }}
              />
            </div>
          </div>
        ))}
      </CardContent>
    </Card>
  );
}

function ScheduleCard() {
  const maxValue = Math.max(
    ...scheduleBars.flatMap((item) => [item.bookings, item.cancellations])
  );

  return (
    <Card className="admin-card rounded-xl border-0 lg:col-span-2">
      <CardHeader className="flex flex-row items-start justify-between gap-4 pb-3">
        <div>
          <CardTitle className="text-base">Bookings Schedule</CardTitle>
          <CardDescription>Confirmed versus cancelled bookings</CardDescription>
        </div>
        <span className="rounded-md bg-primary/10 px-3 py-1 text-xs font-bold text-primary">
          Last 8 Months
        </span>
      </CardHeader>
      <CardContent>
        <div className="mb-4 flex items-center gap-4 text-xs">
          <span className="flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded-full bg-primary" />
            Confirmed
          </span>
          <span className="flex items-center gap-1.5">
            <span className="h-2.5 w-2.5 rounded-full bg-foreground" />
            Cancelled
          </span>
        </div>
        <div className="flex h-72 items-end gap-4 overflow-hidden border-b border-border/70 pb-2">
          {scheduleBars.map((item) => (
            <div
              key={item.month}
              className="flex min-w-0 flex-1 flex-col items-center gap-2"
            >
              <div className="flex h-56 w-full items-end justify-center gap-2">
                <div
                  className="w-4 rounded-t-md bg-primary sm:w-5"
                  style={{ height: `${(item.bookings / maxValue) * 100}%` }}
                />
                <div
                  className="w-4 rounded-t-md bg-foreground sm:w-5"
                  style={{
                    height: `${(item.cancellations / maxValue) * 100}%`,
                  }}
                />
              </div>
              <span className="text-xs text-muted-foreground">
                {item.month}
              </span>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

function AllBookingsPanel() {
  return (
    <aside>
      <Card className="admin-card rounded-xl border-0">
        <CardHeader className="flex flex-row items-center justify-between pb-3">
          <CardTitle className="text-lg">All Bookings</CardTitle>
          <span className="text-xs font-semibold text-[color:var(--chart-3)]">
            See All
          </span>
        </CardHeader>
        <CardContent className="space-y-3">
          {bookingRows.map((booking) => (
            <div
              key={booking.vendor}
              className={cn(
                "rounded-xl border p-4 transition-colors",
                booking.active
                  ? "border-[color:var(--chart-3)] bg-[color-mix(in_oklab,var(--chart-2)_14%,white)]"
                  : "border-border bg-background"
              )}
            >
              <div className="mb-2 flex items-start justify-between gap-3">
                <div className="flex min-w-0 items-center gap-2">
                  <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-[color-mix(in_oklab,var(--chart-3)_16%,white)] text-[color:var(--chart-3)]">
                    <Plane className="h-3.5 w-3.5" />
                  </span>
                  <div className="min-w-0">
                    <p className="truncate text-xs font-black uppercase tracking-wide text-foreground">
                      {booking.code}
                    </p>
                    <p className="truncate text-[11px] font-medium text-muted-foreground">
                      {booking.vendor} - {booking.from} to {booking.to}
                    </p>
                  </div>
                </div>
                <div className="shrink-0 text-right">
                  <p className="text-sm font-bold text-foreground">
                    - {booking.amount}
                  </p>
                  <p className="text-[11px] font-semibold text-muted-foreground">
                    {booking.count} bookings
                  </p>
                </div>
              </div>
              <div className="flex items-end justify-between gap-3">
                <p className="text-xs leading-snug text-muted-foreground">
                  {booking.description}
                </p>
                <span className="shrink-0 text-xs font-bold text-[color:var(--chart-3)]">
                  {booking.action}
                </span>
              </div>
            </div>
          ))}
        </CardContent>
      </Card>
    </aside>
  );
}

export default function AdminDashboardPage() {
  return (
    <div className="admin-section">
      <header className="admin-page-header">
        <h1 className="admin-page-title">Dashboard</h1>
        <p className="admin-page-description">
          Static travel operations snapshot for bookings, revenue, customers,
          and routes.
        </p>
      </header>

      <div className="grid gap-5 xl:grid-cols-[minmax(0,1fr)_300px]">
        <div className="space-y-5">
          <section className="grid gap-5 md:grid-cols-3">
            {topMetrics.map((metric) => (
              <MetricCard key={metric.label} {...metric} />
            ))}
          </section>

          <section className="grid gap-5 lg:grid-cols-4">
            <TicketSalesCard />
            <RevenueGrowthCard />
            <CustomerGrowthCard />
          </section>

          <section className="grid gap-5 lg:grid-cols-3">
            <TopRoutesCard />
            <ScheduleCard />
          </section>

          <section className="grid gap-5 md:grid-cols-4">
            {[
              { label: "Hotel Bookings", value: "1,234", icon: Hotel },
              { label: "Vehicle Bookings", value: "892", icon: Car },
              { label: "Package Bookings", value: "567", icon: Package },
              { label: "Revenue", value: "INR 42.8L", icon: BadgeIndianRupee },
            ].map((item) => {
              const Icon = item.icon;
              return (
                <Card
                  key={item.label}
                  className="admin-card rounded-xl border-0"
                >
                  <CardContent className="flex items-center gap-4 p-5">
                    <div className="flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary">
                      <Icon className="h-5 w-5" />
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">
                        {item.label}
                      </p>
                      <p className="text-2xl font-bold">{item.value}</p>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </section>
        </div>

        <AllBookingsPanel />
      </div>
    </div>
  );
}
