"use client";

import { useState, useEffect, useCallback } from "react";
import {
  ShoppingCart, TrendingUp, DollarSign, Receipt, ArrowRight,
} from "lucide-react";
import { SummaryCard, CardShell, TableSkeleton } from "./_shared";
import type { LucideIcon } from "lucide-react";

// ─── Types ──────────────────────────────────────────────────────────────────

interface EcommerceFunnel {
  productViews: number;
  addToCarts: number;
  checkoutsStarted: number;
  purchases: number;
  cartRate: number;
  checkoutRate: number;
  purchaseRate: number;
}

interface EcommerceRevenue {
  total: number;
  orderCount: number;
  avgOrderValue: number;
  currency: string | null;
}

interface OrderRow {
  id: string;
  orderId: string | null;
  value: number | null;
  currency: string | null;
  timestamp: string;
  pageUrl: string;
  channel: string | null;
  source: string | null;
}

interface EcommerceData {
  funnel: EcommerceFunnel;
  revenue: EcommerceRevenue;
  orders: OrderRow[];
}

export interface EcommerceTabProps {
  brandId: string;
  range: string;
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function fmtMoney(val: number | null, currency: string | null): string {
  if (val == null) return "--";
  const sym = currency === "GBP" ? "PS" : currency === "EUR" ? "EUR" : "$";
  return `${sym}${val.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

function pageSlug(url: string): string {
  try {
    return new URL(url).pathname || "/";
  } catch {
    return url.slice(-60) || "/";
  }
}

// ─── Funnel step ─────────────────────────────────────────────────────────────

function FunnelStep({
  icon: Icon,
  label,
  count,
  rate,
  rateLabel,
  first,
}: {
  icon: LucideIcon;
  label: string;
  count: number;
  rate?: number;
  rateLabel?: string;
  first?: boolean;
}) {
  return (
    <div className="flex items-center gap-3">
      {!first && (
        <div className="flex flex-col items-center">
          <ArrowRight className="w-4 h-4 text-slate-400" />
          {rate != null && (
            <span className="text-[10px] font-medium text-slate-500 mt-0.5 whitespace-nowrap">
              {rate}%
            </span>
          )}
        </div>
      )}
      <div className="bg-white rounded-xl border border-slate-200 px-5 py-4 flex flex-col gap-1 min-w-[130px] flex-1">
        <div className="flex items-center gap-1.5">
          <Icon className="w-3.5 h-3.5 text-slate-400" />
          <span className="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">
            {label}
          </span>
        </div>
        <p className="text-2xl font-bold text-slate-900 tabular-nums">{count.toLocaleString()}</p>
        {rateLabel && <p className="text-[10px] text-slate-400">{rateLabel}</p>}
      </div>
    </div>
  );
}

// ─── Component ───────────────────────────────────────────────────────────────

export function EcommerceTab({ brandId, range }: EcommerceTabProps) {
  const [data, setData] = useState<EcommerceData | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch(
      `/api/site-tag/analytics/ecommerce?brandId=${brandId}&range=${range}`,
    );
    if (res.ok) setData(await res.json());
    setLoading(false);
  }, [brandId, range]);

  useEffect(() => {
    load();
  }, [load]);

  if (loading && !data) {
    return (
      <div className="space-y-6">
        <TableSkeleton rows={4} cols={4} />
      </div>
    );
  }

  const funnel = data?.funnel;
  const revenue = data?.revenue;
  const orders = data?.orders ?? [];

  const hasActivity =
    !!funnel &&
    (funnel.purchases > 0 || funnel.checkoutsStarted > 0 || funnel.addToCarts > 0 || funnel.productViews > 0);

  if (!hasActivity) {
    return (
      <div className="rounded-xl bg-slate-50 border border-slate-200 p-10 text-center">
        <ShoppingCart className="mx-auto w-10 h-10 text-slate-300 mb-3" />
        <h3 className="font-semibold text-slate-700">No e-commerce activity recorded yet</h3>
        <p className="text-slate-500 text-sm mt-2 max-w-md mx-auto">
          Add to Cart and Checkout Started events will appear here as they are captured.
          Purchase revenue requires the order confirmation page to load the Site Tag.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">

      {/* Funnel */}
      <CardShell title="Conversion Funnel" icon={TrendingUp}>
        <div className="px-5 py-5 overflow-x-auto">
          <div className="flex items-center gap-1 min-w-max">
            <FunnelStep
              first
              icon={ShoppingCart}
              label="Product Views"
              count={funnel?.productViews ?? 0}
            />
            <FunnelStep
              icon={ShoppingCart}
              label="Add to Cart"
              count={funnel?.addToCarts ?? 0}
              rate={funnel?.cartRate}
            />
            <FunnelStep
              icon={Receipt}
              label="Checkout"
              count={funnel?.checkoutsStarted ?? 0}
              rate={funnel?.checkoutRate}
            />
            <FunnelStep
              icon={DollarSign}
              label="Purchases"
              count={funnel?.purchases ?? 0}
              rate={funnel?.purchaseRate}
            />
          </div>
        </div>
      </CardShell>

      {/* Revenue summary */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <SummaryCard
          label="Total Revenue"
          value={fmtMoney(revenue?.total ?? null, revenue?.currency ?? null)}
          subtitle={`${revenue?.orderCount ?? 0} orders with value`}
          icon={DollarSign}
          iconColor="text-emerald-300"
        />
        <SummaryCard
          label="Avg Order Value"
          value={fmtMoney(revenue?.avgOrderValue ?? null, revenue?.currency ?? null)}
          subtitle={revenue?.currency ?? ""}
          icon={TrendingUp}
          iconColor="text-blue-300"
        />
        <SummaryCard
          label="Total Purchases"
          value={String(funnel?.purchases ?? 0)}
          subtitle={`${funnel?.purchaseRate ?? 0}% checkout-to-purchase`}
          icon={Receipt}
          iconColor="text-violet-300"
        />
      </div>

      {/* Order history */}
      {orders.length > 0 && (
        <CardShell title="Order History" icon={Receipt}>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-slate-100">
                  <th className="text-left px-5 py-3 text-[11px] font-semibold text-slate-500 uppercase tracking-wide">
                    Order ID
                  </th>
                  <th className="text-right px-5 py-3 text-[11px] font-semibold text-slate-500 uppercase tracking-wide">
                    Value
                  </th>
                  <th className="text-left px-5 py-3 text-[11px] font-semibold text-slate-500 uppercase tracking-wide hidden sm:table-cell">
                    Channel / Source
                  </th>
                  <th className="text-left px-5 py-3 text-[11px] font-semibold text-slate-500 uppercase tracking-wide hidden md:table-cell">
                    Page
                  </th>
                  <th className="text-left px-5 py-3 text-[11px] font-semibold text-slate-500 uppercase tracking-wide">
                    Time
                  </th>
                </tr>
              </thead>
              <tbody>
                {orders.map((order) => (
                  <tr
                    key={order.id}
                    className="border-b border-slate-50 hover:bg-slate-50 transition-colors"
                  >
                    <td className="px-5 py-3 font-mono text-xs text-slate-600">
                      {order.orderId ? (
                        <span title={order.orderId}>
                          {order.orderId.length > 24
                            ? `${order.orderId.slice(0, 24)}...`
                            : order.orderId}
                        </span>
                      ) : (
                        <span className="text-slate-400">--</span>
                      )}
                    </td>
                    <td className="px-5 py-3 text-right font-semibold text-slate-900 tabular-nums">
                      {fmtMoney(order.value, order.currency)}
                    </td>
                    <td className="px-5 py-3 text-slate-600 hidden sm:table-cell">
                      {order.channel ?? "--"}
                      {order.source && order.source !== order.channel && (
                        <span className="text-slate-400"> / {order.source}</span>
                      )}
                    </td>
                    <td className="px-5 py-3 text-slate-500 font-mono text-xs hidden md:table-cell">
                      {pageSlug(order.pageUrl)}
                    </td>
                    <td className="px-5 py-3 text-slate-500 text-xs whitespace-nowrap">
                      {new Date(order.timestamp).toLocaleString(undefined, {
                        month: "short",
                        day: "numeric",
                        hour: "2-digit",
                        minute: "2-digit",
                      })}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardShell>
      )}

      {orders.length === 0 && funnel && funnel.purchases === 0 && funnel.checkoutsStarted > 0 && (
        <div className="rounded-xl bg-amber-50 border border-amber-200 px-5 py-4 text-sm text-amber-800">
          <strong>Checkout Started</strong> events are being captured but no Purchase completions
          yet. If the store checkout is hosted on a Shopify or third-party domain, the Site Tag
          may not load there -- only the storefront events are visible.
        </div>
      )}
    </div>
  );
}
