"use client";

import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import {
  FolderOpen,
  Package,
  ShoppingBag,
  ShoppingCart,
  UsersRound,
} from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useMemo, useState } from "react";

const PAGE_BG = "#F4F5F7";
const NAVY = "#003366";
const SKY = "#93C5FD";
const SKY_SOFT = "#DBEAFE";
const ORANGE = "#FB923C";

const PERIODS = ["This Week", "Last Week", "This Month"] as const;
const SUMMARY_RANGES = ["Last 7 Days", "Last 30 Days", "Last 90 Days"] as const;

type OrderStatus = "pending" | "completed";

type RecentOrder = {
  id: string;
  name: string;
  line: string;
  date: string;
  status: OrderStatus;
  thumbClass: string;
};

const RECENT_ORDERS: RecentOrder[] = [
  {
    id: "1",
    name: "iPhone 13",
    line: "$30,000.00 × 1",
    date: "12 Feb 2024",
    status: "pending",
    thumbClass: "bg-gradient-to-br from-slate-200 to-slate-400",
  },
  {
    id: "2",
    name: "MacBook Pro",
    line: "$2,499.00 × 1",
    date: "11 Feb 2024",
    status: "completed",
    thumbClass: "bg-gradient-to-br from-zinc-300 to-zinc-500",
  },
  {
    id: "3",
    name: "Wireless Controller",
    line: "$79.00 × 2",
    date: "10 Feb 2024",
    status: "completed",
    thumbClass: "bg-gradient-to-br from-violet-200 to-violet-500",
  },
  {
    id: "4",
    name: "Noise-Canceling Headphones",
    line: "$349.00 × 1",
    date: "9 Feb 2024",
    status: "pending",
    thumbClass: "bg-gradient-to-br from-sky-200 to-sky-500",
  },
];

const SUMMARY_BARS = [
  { label: "Sept 10", value: 58_000 },
  { label: "Sept 11", value: 72_000 },
  { label: "Sept 12", value: 45_000 },
  { label: "Sept 13", value: 88_000 },
  { label: "Sept 14", value: 62_000 },
  { label: "Sept 15", value: 95_000 },
  { label: "Sept 16", value: 70_000 },
];

const Y_MAX = 100_000;

function PeriodSelect({
  value,
  onChange,
  className,
}: {
  value: string;
  onChange: (v: string) => void;
  className?: string;
}) {
  return (
    <Select value={value} onValueChange={onChange}>
      <SelectTrigger
        className={cn(
          "h-8 w-[118px] border-0 bg-transparent px-2 text-xs font-medium text-gray-600 shadow-none ring-0 focus:ring-0",
          className
        )}
      >
        <SelectValue />
      </SelectTrigger>
      <SelectContent>
        {PERIODS.map((p) => (
          <SelectItem key={p} value={p} className="text-xs">
            {p}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

function OrderStatusBadge({ status }: { status: OrderStatus }) {
  const isPending = status === "pending";
  return (
    <span
      className={cn(
        "inline-flex min-w-[76px] justify-center rounded-md px-2.5 py-1 text-xs font-medium capitalize",
        isPending
          ? "bg-rose-50 text-rose-600"
          : "bg-emerald-50 text-emerald-700"
      )}
    >
      {isPending ? "Pending" : "Completed"}
    </span>
  );
}

function MarketingDonut({
  acquisitionPct,
  purchasePct,
  retentionPct,
}: {
  acquisitionPct: number;
  purchasePct: number;
  retentionPct: number;
}) {
  const gradient = useMemo(() => {
    const a = acquisitionPct;
    const b = a + purchasePct;
    const c = b + retentionPct;
    return `conic-gradient(${NAVY} 0% ${a}%, ${SKY} ${a}% ${b}%, ${ORANGE} ${b}% ${c}%)`;
  }, [acquisitionPct, purchasePct, retentionPct]);

  return (
    <div className="relative mx-auto flex size-[200px] max-w-full items-center justify-center">
      <div
        className="absolute size-[200px] max-w-[min(100%,200px)] rounded-full"
        style={{ background: gradient }}
      />
      <div
        className="relative z-[1] flex size-[120px] items-center justify-center rounded-full bg-white shadow-inner"
        style={{ boxShadow: "inset 0 0 0 1px rgba(0,0,0,0.04)" }}
      />
    </div>
  );
}

function SummaryBarChart() {
  return (
    <div className="mt-4">
      <div className="mb-2 flex justify-between px-1 text-[11px] font-medium text-gray-400">
        <span>20k</span>
        <span>40k</span>
        <span>60k</span>
        <span>80k</span>
        <span>100k</span>
      </div>
      <div className="flex h-52 items-end justify-between gap-2 border-b border-l border-gray-200 pl-1 pr-1 pt-2">
        {SUMMARY_BARS.map((bar) => {
          const h = Math.round((bar.value / Y_MAX) * 100);
          return (
            <div
              key={bar.label}
              className="flex min-w-0 flex-1 flex-col items-center justify-end gap-2"
            >
              <div className="relative flex h-full w-full max-w-[44px] flex-col justify-end">
                <div
                  className="absolute bottom-0 left-0 right-0 rounded-t-md bg-[#E8EEF7]"
                  style={{ height: "100%" }}
                />
                <div
                  className="relative z-[1] w-full rounded-t-md transition-all"
                  style={{
                    height: `${h}%`,
                    backgroundColor: NAVY,
                    minHeight: "4px",
                  }}
                />
              </div>
              <span className="truncate text-center text-[11px] text-gray-500">
                {bar.label}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default function EcommerceAnalyticsDashboard() {
  const { app } = useParams() as { app: string };
  const productsHref = `/${app}/products/new`;

  const [periodCustomers, setPeriodCustomers] = useState<string>(PERIODS[0]);
  const [periodOrders, setPeriodOrders] = useState<string>(PERIODS[0]);
  const [periodMarketing, setPeriodMarketing] = useState<string>(PERIODS[0]);
  const [periodCart, setPeriodCart] = useState<string>(PERIODS[0]);
  const [summaryMetric, setSummaryMetric] = useState("Sales");
  const [summaryRange, setSummaryRange] = useState<string>(SUMMARY_RANGES[0]);

  const statCardClass =
    "rounded-xl border-0 bg-white shadow-[0_1px_3px_rgba(15,23,42,0.06)]";

  return (
    <div className="min-h-0 pb-8" style={{ backgroundColor: PAGE_BG }}>
      <div className="mx-auto max-w-[1400px] space-y-4 px-4 pt-2 md:px-6">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-stretch">
          <div className="flex min-w-0 flex-1 flex-col gap-4">
            <div className="grid gap-4 md:grid-cols-2">
              <Card className={cn(statCardClass, "p-5")}>
                <div className="mb-5 flex items-start justify-between">
                  <div className="flex size-10 items-center justify-center rounded-lg bg-gray-100 text-gray-500">
                    <UsersRound className="size-5" />
                  </div>
                  <PeriodSelect
                    value={periodCustomers}
                    onChange={setPeriodCustomers}
                  />
                </div>
                <div className="grid grid-cols-3 gap-3 divide-x divide-gray-100">
                  <div className="pr-3 text-center first:pl-0 md:text-left">
                    <p className="text-xs text-gray-500">All Customers</p>
                    <p className="mt-1 text-lg font-semibold text-gray-900">
                      {Number(1250).toLocaleString()}
                    </p>
                    <p className="mt-0.5 text-xs font-medium text-emerald-600">
                      +15.80%
                    </p>
                  </div>
                  <div className="px-3 text-center md:text-left">
                    <p className="text-xs text-gray-500">Active</p>
                    <p className="mt-1 text-lg font-semibold text-gray-900">
                      {Number(1180).toLocaleString()}
                    </p>
                    <p className="mt-0.5 text-xs font-medium text-emerald-600">
                      85%
                    </p>
                  </div>
                  <div className="pl-3 text-center md:text-left">
                    <p className="text-xs text-gray-500">In Active</p>
                    <p className="mt-1 text-lg font-semibold text-gray-900">
                      {Number(70).toLocaleString()}
                    </p>
                    <p className="mt-0.5 text-xs font-medium text-gray-400">
                      —
                    </p>
                  </div>
                </div>
              </Card>

              <Card className={cn(statCardClass, "p-5")}>
                <div className="mb-5 flex items-start justify-between">
                  <div className="flex size-10 items-center justify-center rounded-lg bg-gray-100 text-gray-500">
                    <ShoppingBag className="size-5" />
                  </div>
                  <PeriodSelect
                    value={periodOrders}
                    onChange={setPeriodOrders}
                  />
                </div>
                <div className="grid grid-cols-3 gap-3 divide-x divide-gray-100">
                  <div className="pr-3 text-center md:text-left">
                    <p className="text-xs text-gray-500">All Orders</p>
                    <p className="mt-1 text-lg font-semibold text-gray-900">450</p>
                  </div>
                  <div className="px-3 text-center md:text-left">
                    <p className="text-xs text-gray-500">Pending</p>
                    <p className="mt-1 text-lg font-semibold text-rose-600">5</p>
                  </div>
                  <div className="pl-3 text-center md:text-left">
                    <p className="text-xs text-gray-500">Completed</p>
                    <p className="mt-1 text-lg font-semibold text-emerald-700">
                      445
                    </p>
                  </div>
                </div>
              </Card>
            </div>

            <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
              <Card className={cn(statCardClass, "flex flex-col p-5")}>
                <div className="mb-4 flex items-center justify-between">
                  <h2 className="text-sm font-semibold text-gray-900">
                    Marketing
                  </h2>
                  <PeriodSelect
                    value={periodMarketing}
                    onChange={setPeriodMarketing}
                  />
                </div>
                <div className="mb-4 flex flex-wrap gap-4 text-xs text-gray-600">
                  <span className="inline-flex items-center gap-2">
                    <span
                      className="size-2.5 rounded-full"
                      style={{ backgroundColor: NAVY }}
                    />
                    Acquisition
                  </span>
                  <span className="inline-flex items-center gap-2">
                    <span
                      className="size-2.5 rounded-full"
                      style={{ backgroundColor: SKY }}
                    />
                    Purchase
                  </span>
                  <span className="inline-flex items-center gap-2">
                    <span
                      className="size-2.5 rounded-full"
                      style={{ backgroundColor: ORANGE }}
                    />
                    Retention
                  </span>
                </div>
                <div className="flex flex-1 flex-col items-center justify-center py-2">
                  <MarketingDonut
                    acquisitionPct={40}
                    purchasePct={35}
                    retentionPct={25}
                  />
                </div>
              </Card>

              <div className="flex flex-col gap-4">
                <Card
                  className={cn(
                    "flex flex-1 flex-col justify-between rounded-xl border-0 p-5 text-white shadow-[0_1px_3px_rgba(15,23,42,0.12)]"
                  )}
                  style={{ backgroundColor: NAVY }}
                >
                  <div className="mb-6 flex items-start justify-between">
                    <div className="flex size-10 items-center justify-center rounded-lg bg-white/10">
                      <FolderOpen className="size-5 text-white" />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <p className="text-xs text-white/80">All Products</p>
                      <p className="mt-1 text-2xl font-semibold">45</p>
                      <p className="mt-1 text-xs font-medium text-emerald-300">
                        +24%
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-white/80">Active</p>
                      <p className="mt-1 text-2xl font-semibold">32</p>
                    </div>
                  </div>
                </Card>

                <Card className={cn(statCardClass, "p-5")}>
                  <div className="mb-4 flex items-start justify-between">
                    <div className="flex size-10 items-center justify-center rounded-lg bg-gray-100 text-gray-500">
                      <ShoppingCart className="size-5" />
                    </div>
                    <PeriodSelect value={periodCart} onChange={setPeriodCart} />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <p className="text-xs text-gray-500">Abandoned Cart</p>
                      <p className="mt-1 text-lg font-semibold text-gray-900">
                        20%
                      </p>
                      <p className="mt-0.5 text-xs font-medium text-emerald-600">
                        +0.00%
                      </p>
                    </div>
                    <div>
                      <p className="text-xs text-gray-500">Customers</p>
                      <p className="mt-1 text-lg font-semibold text-gray-900">
                        30
                      </p>
                    </div>
                  </div>
                </Card>
              </div>
            </div>

            <Card className={cn(statCardClass, "p-5")}>
              <div className="mb-2 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <h2 className="text-sm font-semibold text-gray-900">Summary</h2>
                <div className="flex flex-wrap items-center gap-2">
                  <Select value={summaryMetric} onValueChange={setSummaryMetric}>
                    <SelectTrigger
                      className="h-9 w-[108px] rounded-lg border-0 text-xs font-medium shadow-none"
                      style={{ backgroundColor: SKY_SOFT, color: NAVY }}
                    >
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Sales">Sales</SelectItem>
                      <SelectItem value="Orders">Orders</SelectItem>
                      <SelectItem value="Revenue">Revenue</SelectItem>
                    </SelectContent>
                  </Select>
                  <Select
                    value={summaryRange}
                    onValueChange={setSummaryRange}
                  >
                    <SelectTrigger className="h-9 w-[132px] rounded-lg border border-gray-200 bg-white text-xs font-medium shadow-sm">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {SUMMARY_RANGES.map((r) => (
                        <SelectItem key={r} value={r} className="text-xs">
                          {r}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <SummaryBarChart />
            </Card>
          </div>

          <Card
            className={cn(
              statCardClass,
              "flex w-full shrink-0 flex-col lg:w-[min(100%,380px)]"
            )}
          >
            <div className="border-b border-gray-100 p-5">
              <h2 className="text-sm font-semibold text-gray-900">
                Recent Orders
              </h2>
            </div>
            <div className="flex min-h-[320px] flex-1 flex-col">
              {RECENT_ORDERS.length === 0 ? (
                <div className="flex flex-1 flex-col items-center justify-center gap-4 px-6 py-10 text-center">
                  <div className="flex size-24 items-center justify-center rounded-full bg-gray-100 text-gray-400">
                    <ShoppingBag className="size-10" />
                  </div>
                  <div>
                    <p className="text-base font-semibold text-gray-900">
                      No Orders Yet?
                    </p>
                    <p className="mt-2 max-w-[260px] text-sm text-gray-500">
                      Add products to your store and start selling to see orders
                      here.
                    </p>
                  </div>
                  <Button
                    className="mt-2 rounded-lg px-8 font-medium text-white shadow-none"
                    style={{ backgroundColor: NAVY }}
                    asChild
                  >
                    <Link href={productsHref}>New Product</Link>
                  </Button>
                </div>
              ) : (
                <ul className="max-h-[min(70vh,640px)] flex-1 divide-y divide-gray-100 overflow-y-auto">
                  {RECENT_ORDERS.map((o) => (
                    <li
                      key={o.id}
                      className="flex items-center gap-3 p-4 transition-colors hover:bg-gray-50/80"
                    >
                      <div
                        className={cn(
                          "flex size-14 shrink-0 items-center justify-center rounded-xl text-white",
                          o.thumbClass
                        )}
                        aria-hidden
                      >
                        <Package className="size-6 opacity-90" strokeWidth={1.75} />
                      </div>
                      <div className="min-w-0 flex-1">
                        <p className="truncate text-sm font-medium text-gray-900">
                          {o.name}
                        </p>
                        <p className="truncate text-xs text-gray-500">{o.line}</p>
                        <p className="mt-1 text-xs text-gray-400">{o.date}</p>
                      </div>
                      <OrderStatusBadge status={o.status} />
                    </li>
                  ))}
                </ul>
              )}
            </div>
            {RECENT_ORDERS.length > 0 && (
              <div className="border-t border-gray-100 p-4">
                <Button
                  variant="outline"
                  className="w-full rounded-lg border-gray-200 text-sm font-medium"
                  asChild
                >
                  <Link href={productsHref}>New Product</Link>
                </Button>
              </div>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}
