import React, { useState, useEffect, useCallback, useMemo } from "react";
import { apiClient } from "@/utils/apiClient";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  Package,
  Truck,
  UserPlus,
  XCircle,
  DollarSign,
  ChevronRight,
  Tag,
  Box,
  Activity,
  RefreshCcw,
  FileText,
  AlertCircle,
} from "lucide-react";
import { format } from "date-fns";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import {
  CARD_STYLES,
  TYPOGRAPHY,
} from "@/lib/dashboard/designTokens";
import { DashboardErrorState } from "@/components/dashboard/shared";

const METRIC_IDS = {
  PLACED_ORDER: "Y8cqcF",
  SHIPPED_ORDER: "VExpdL",
  ACCOUNT_CREATED: "TeeypV",
  CANCELED_ORDER: "YjVMNg",
  NEW_BLOG_POST: "YcxeDr",
  PAYMENT_REFUNDED: "R7XUYh",
};

const EVENT_ICONS = {
  [METRIC_IDS.PLACED_ORDER]: Package,
  [METRIC_IDS.SHIPPED_ORDER]: Truck,
  [METRIC_IDS.ACCOUNT_CREATED]: UserPlus,
  [METRIC_IDS.CANCELED_ORDER]: XCircle,
  [METRIC_IDS.PAYMENT_REFUNDED]: DollarSign,
  [METRIC_IDS.NEW_BLOG_POST]: FileText,
};

const EVENT_TYPES = {
  [METRIC_IDS.PLACED_ORDER]: { label: "Order Placed" },
  [METRIC_IDS.SHIPPED_ORDER]: { label: "Order Shipped" },
  [METRIC_IDS.ACCOUNT_CREATED]: { label: "New Account" },
  [METRIC_IDS.CANCELED_ORDER]: { label: "Order Canceled" },
  [METRIC_IDS.PAYMENT_REFUNDED]: { label: "Payment Refunded" },
  [METRIC_IDS.NEW_BLOG_POST]: { label: "New Blog Post" },
};

// Helper Functions
const formatCurrency = (amount) => {
  // Convert to number if it's a string
  const num = typeof amount === "string" ? parseFloat(amount) : amount;
  // Handle negative numbers
  const absNum = Math.abs(num);
  // Format to 2 decimal places and add negative sign if needed
  return `${num < 0 ? "-" : ""}$${absNum.toFixed(2)}`;
};

const toTitleCase = (str) => {
  if (!str) return "";
  return str
    .toLowerCase()
    .split(" ")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
};

const formatShipMethod = (method) => {
  if (!method) return "Standard Shipping";
  return method
    .replace("usps_", "USPS ")
    .replace("ups_", "UPS ")
    .replace("fedex_", "FedEx ")
    .replace(/_/g, " ")
    .split(" ")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
};

const formatShipMethodSimple = (method) => {
  if (!method) return "Digital";
  if (method.includes("usps")) return "USPS";
  if (method.includes("fedex")) return "FedEx";
  if (method.includes("ups")) return "UPS";
  return "Standard";
};

// Loading State Component
const LoadingState = () => (
  <div className="divide-y divide-[#f5f3f0]">
    {[...Array(8)].map((_, i) => (
      <div key={i} className="flex items-center gap-3 px-3 py-3">
        <div className="shrink-0">
          <Skeleton className="h-8 w-8 rounded-md bg-[#f0eeea]" />
        </div>
        <div className="flex-1 min-w-0 space-y-2">
          <div className="flex items-center gap-2">
            <Skeleton className="h-4 w-24 bg-[#f0eeea] rounded-sm" />
          </div>
          <div className="flex items-center gap-2">
            <Skeleton className="h-4 w-48 bg-[#f0eeea] rounded-sm" />
          </div>
          <div className="flex gap-1.5 items-center flex-wrap">
            <Skeleton className="h-5 w-16 bg-[#f0eeea] rounded-md" />
            <Skeleton className="h-5 w-20 bg-[#f0eeea] rounded-md" />
            <Skeleton className="h-5 w-14 bg-[#f0eeea] rounded-md" />
          </div>
        </div>
        <div className="flex items-center gap-2 shrink-0">
          <Skeleton className="h-4 w-16 bg-[#f0eeea] rounded-sm" />
          <Skeleton className="h-4 w-4 bg-[#f0eeea] rounded-full" />
        </div>
      </div>
    ))}
  </div>
);

// Empty State Component
const EmptyState = () => (
  <div className="h-full flex flex-col items-center justify-center py-16 px-4 text-center">
    <div className="bg-[#f0eeea] rounded-full p-3 mb-4">
      <Activity className="h-8 w-8 text-muted-foreground" />
    </div>
    <h3 className="text-sm font-medium text-foreground mb-1">
      No activity yet today
    </h3>
    <p className={`${TYPOGRAPHY.cardDescription} max-w-sm`}>
      Recent activity will appear here as it happens
    </p>
  </div>
);

// Shared Components
const OrderStatusTags = ({ details }) => (
  <div className="flex flex-wrap gap-2">
    {details.HasPreorder && (
      <span className="px-2 py-1 bg-[#f5f3f0] text-[#7c7870] rounded-full text-xs font-medium cursor-help">
        Includes Pre-order
      </span>
    )}
    {details.LocalPickup && (
      <span className="px-2 py-1 bg-[#f5f3f0] text-[#7c7870] rounded-full text-xs font-medium cursor-help">
        Local Pickup
      </span>
    )}
    {details.IsOnHold && (
      <span className="px-2 py-1 bg-[#f5f3f0] text-[#7c7870] rounded-full text-xs font-medium cursor-help">
        On Hold
      </span>
    )}
    {details.HasDigiItem && (
      <span className="px-2 py-1 bg-[#f5f3f0] text-[#7c7870] rounded-full text-xs font-medium cursor-help">
        Digital Items
      </span>
    )}
    {details.HasNotions && (
      <span className="px-2 py-1 bg-[#f5f3f0] text-[#7c7870] rounded-full text-xs font-medium cursor-help">
        Includes Notions
      </span>
    )}
    {details.HasDigitalGC && (
      <span className="px-2 py-1 bg-[#f5f3f0] text-[#7c7870] rounded-full text-xs font-medium cursor-help">
        Gift Card
      </span>
    )}
    {details.StillOwes && (
      <span className="px-2 py-1 bg-[#f5f3f0] text-[#7c7870] rounded-full text-xs font-medium cursor-help">
        Payment Due
      </span>
    )}
  </div>
);

const ProductCard = ({ product }) => (
  <div className="p-3 bg-[#faf9f7] rounded-xl mb-3 hover:bg-[#f0eeea] transition-colors">
    <div className="flex items-start space-x-3">
      <div className="flex-1 min-w-0">
        <div className="flex items-center space-x-2">
          <p className="font-medium text-sm text-foreground truncate">
            {product.ProductName || "Unnamed Product"}
          </p>
          {product.ItemStatus === "Pre-Order" && (
            <span className="px-2 py-0.5 bg-[#eae6f6] text-[#4a3f9e] rounded-full text-xs cursor-help">
              Pre-order
            </span>
          )}
        </div>
        <div className="mt-1 flex flex-wrap gap-2">
          {product.Brand && (
            <div className="flex items-center text-xs text-muted-foreground cursor-help">
              <Tag className="w-3 h-3 mr-1" />
              <span>{product.Brand}</span>
            </div>
          )}
          {product.SKU && (
            <div className="flex items-center text-xs text-muted-foreground cursor-help">
              <Box className="w-3 h-3 mr-1" />
              <span>SKU: {product.SKU}</span>
            </div>
          )}
        </div>
      </div>
      <div className="text-right flex-shrink-0">
        <div className="text-sm font-medium text-foreground cursor-help">
          {formatCurrency(product.ItemPrice)}
        </div>
        <div className="text-xs text-muted-foreground cursor-help">
          Qty: {product.Quantity || product.QuantityOrdered || 1}
        </div>
        {product.RowTotal && (
          <div className="text-xs font-medium text-foreground/80 cursor-help">
            Total: {formatCurrency(product.RowTotal)}
          </div>
        )}
      </div>
    </div>
  </div>
);

const PromotionalInfo = ({ details }) => {
  if (!details?.PromosUsedReg?.length && !details?.PointsDiscount) return null;

  return (
    <div className="mt-4 p-3 bg-[#e6f3ee] rounded-xl">
      <h4 className="text-sm font-semibold text-[#237a4d] mb-2">
        <span className="cursor-help">Savings Applied</span>
      </h4>
      <div className="space-y-2">
        {Array.isArray(details.PromosUsedReg) &&
          details.PromosUsedReg.map(([code, amount], index) => (
            <div key={index} className="flex justify-between text-sm">
              <span className="font-mono text-[#237a4d] cursor-help">
                {code}
              </span>
              <span className="font-medium text-[#237a4d] cursor-help">
                -{formatCurrency(amount)}
              </span>
            </div>
          ))}
        {details.PointsDiscount > 0 && (
          <div className="flex justify-between text-sm">
            <span className="text-[#237a4d] cursor-help">
              Points Discount
            </span>
            <span className="font-medium text-[#237a4d] cursor-help">
              -{formatCurrency(details.PointsDiscount)}
            </span>
          </div>
        )}
      </div>
    </div>
  );
};

const OrderSummary = ({ details }) => (
  <div className="bg-[#faf9f7] p-4 rounded-xl space-y-3">
    <div className="grid grid-cols-2 gap-4">
      <div>
        <h4 className="text-sm font-medium text-muted-foreground mb-2 cursor-help">
          Subtotal
        </h4>
        <div className="space-y-1">
          <div className="flex justify-between">
            <span className="cursor-help">
              Items ({details.Items?.length || 0})
            </span>
            <span>{formatCurrency(details.Subtotal)}</span>
          </div>
          {details.PointsDiscount > 0 && (
            <div className="flex justify-between text-[#237a4d]">
              <span className="cursor-help">Points Discount</span>
              <span>-{formatCurrency(details.PointsDiscount)}</span>
            </div>
          )}
          {details.TotalDiscounts > 0 && (
            <div className="flex justify-between text-[#237a4d]">
              <span className="cursor-help">Discounts</span>
              <span>-{formatCurrency(details.TotalDiscounts)}</span>
            </div>
          )}
        </div>
      </div>
      <div>
        <h4 className="text-sm font-medium text-muted-foreground mb-2 cursor-help">
          Shipping
        </h4>
        <div className="space-y-1">
          <div className="flex justify-between">
            <span className="cursor-help">Shipping Cost</span>
            <span>{formatCurrency(details.ShippingTotal)}</span>
          </div>
          {details.SalesTax > 0 && (
            <div className="flex justify-between">
              <span className="cursor-help">Sales Tax</span>
              <span>{formatCurrency(details.SalesTax)}</span>
            </div>
          )}
        </div>
      </div>
    </div>

    <div className="pt-3 border-t border-[#f0eeea]">
      <div className="flex justify-between items-center">
        <div>
          <span className="text-sm font-medium">Total</span>
          {details.TotalSavings > 0 && (
            <div className="text-xs text-[#237a4d] cursor-help">
              You saved {formatCurrency(details.TotalSavings)}
            </div>
          )}
        </div>
        <span className="text-lg font-bold">
          {formatCurrency(details.TotalAmount)}
        </span>
      </div>
    </div>

    <PromotionalInfo details={details} />
  </div>
);

const ShippingInfo = ({ details }) => (
  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
    <div className="space-y-2">
      <h4 className="text-sm font-medium text-muted-foreground cursor-help">
        Shipping Address
      </h4>
      <div className="text-sm space-y-1">
        <div className="font-medium cursor-help">
          {details.ShippingName || "Customer"}
        </div>
        <div>{details.ShippingStreet1}</div>
        {details.ShippingStreet2 && <div>{details.ShippingStreet2}</div>}
        <div className="cursor-help">
          {details.ShippingCity}, {details.ShippingState} {details.ShippingZip}
        </div>
        {details.ShippingCountry !== "US" && (
          <div className="cursor-help">{details.ShippingCountry}</div>
        )}
      </div>
    </div>
    {details.TrackingNumber && (
      <div className="space-y-2">
        <h4 className="text-sm font-medium text-muted-foreground cursor-help">
          Tracking Information
        </h4>
        <div className="text-sm space-y-1">
          <div className="font-medium cursor-help">
            {formatShipMethod(details.ShipMethod)}
          </div>
          <div className="font-mono text-[#3f7fae] cursor-pointer hover:underline">
            {details.TrackingNumber}
          </div>
        </div>
      </div>
    )}
  </div>
);

const EventDialog = ({ event, children, scale }) => {
  const eventType = EVENT_TYPES[event.metric_id];
  if (!eventType) return children;

  const details = event.event_properties || {};
  const Icon = EVENT_ICONS[event.metric_id] || Package;

  const dialogInner = (
    <>
        <DialogHeader className="border-b border-[#f0eeea] px-6 py-4">
          <div className="flex items-center gap-2 mb-2">
            {Icon && <Icon className="h-5 w-5 text-[#7c7870]" />}
            <DialogTitle className="text-lg font-semibold">{eventType.label}</DialogTitle>
          </div>
          <div className="flex items-center justify-between">
            <DialogDescription className="text-base">
              {details.OrderId
                ? `Order #${details.OrderId}`
                : details.title
                ? details.title
                : details.EmailAddress
                ? details.EmailAddress
                : "Event Details"}
            </DialogDescription>
            {event.datetime && (
              <time
                className="text-sm text-muted-foreground"
                dateTime={event.datetime}
              >
                {format(new Date(event.datetime), "h:mm a")}
              </time>
            )}
          </div>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto px-6 py-4">
          <div className="space-y-6">
            {event.metric_id === METRIC_IDS.PLACED_ORDER && (
              <>
                <div className="grid gap-6 sm:grid-cols-2">
                  <div className="space-y-4">
                    <Card>
                      <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium">Shipping Information</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-1">
                        <p className="text-sm font-medium">{details.ShippingName}</p>
                        {details.ShippingStreet1 && (
                          <p className="text-sm text-muted-foreground">{details.ShippingStreet1}</p>
                        )}
                        {details.ShippingStreet2 && (
                          <p className="text-sm text-muted-foreground">{details.ShippingStreet2}</p>
                        )}
                        <p className="text-sm text-muted-foreground">
                          {details.ShippingCity}, {details.ShippingState} {details.ShippingZip}
                        </p>
                        {details.ShippingCountry !== "US" && (
                          <p className="text-sm text-muted-foreground">{details.ShippingCountry}</p>
                        )}
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium">Order Properties</CardTitle>
                      </CardHeader>
                      <CardContent className="flex flex-wrap gap-2">
                        {details.IsOnHold && (
                          <Badge variant="secondary" className="bg-[#eae6f6] text-[#4a3f9e]">
                            On Hold
                          </Badge>
                        )}
                        {details.OnHoldReleased && (
                          <Badge variant="secondary" className="bg-green-100 dark:bg-green-900/20 text-green-700 dark:text-green-300">
                            Hold Released
                          </Badge>
                        )}
                        {details.StillOwes && (
                          <Badge variant="secondary" className="bg-red-100 dark:bg-red-900/20 text-red-700 dark:text-red-300">
                            Owes
                          </Badge>
                        )}
                        {details.LocalPickup && (
                          <Badge variant="secondary" className="bg-green-100 dark:bg-green-900/20 text-green-700 dark:text-green-300">
                            Local
                          </Badge>
                        )}
                        {details.HasPreorder && (
                          <Badge variant="secondary" className="bg-purple-100 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300">
                            Pre-order
                          </Badge>
                        )}
                        {details.HasNotions && (
                          <Badge variant="secondary" className="bg-yellow-100 dark:bg-yellow-900/20 text-yellow-700 dark:text-yellow-300">
                            Notions
                          </Badge>
                        )}
                        {(details.OnlyDigitalGC || details.HasDigitalGC) && (
                          <Badge variant="secondary" className="bg-pink-100 dark:bg-pink-900/20 text-pink-700 dark:text-pink-300">
                            eGift Card
                          </Badge>
                        )}
                        {(details.HasDigiItem || details.OnlyDigiItem) && (
                          <Badge variant="secondary" className="bg-indigo-100 dark:bg-indigo-900/20 text-indigo-700 dark:text-indigo-300">
                            Digital
                          </Badge>
                        )}
                      </CardContent>
                    </Card>
                  </div>

                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium">Order Summary</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                          <span className="text-muted-foreground">Subtotal</span>
                          <span className="font-medium">{formatCurrency(details.Subtotal)}</span>
                        </div>
                        <div className="flex justify-between text-sm">
                          <span className="text-muted-foreground">Shipping</span>
                          <span className="font-medium">{formatCurrency(details.ShippingTotal)}</span>
                        </div>
                        <div className="flex justify-between text-sm">
                          <span className="text-muted-foreground">Tax</span>
                          <span className="font-medium">{formatCurrency(details.SalesTax)}</span>
                        </div>
                        {details.PointsDiscount > 0 && (
                          <div className="flex justify-between text-sm text-[#237a4d]">
                            <span>Points Discount</span>
                            <span className="font-medium">-{formatCurrency(details.PointsDiscount)}</span>
                          </div>
                        )}
                        {Array.isArray(details.PromosUsedReg) &&
                          details.PromosUsedReg.map(([code, amount], i) => (
                            <div key={i} className="flex justify-between text-sm text-[#237a4d]">
                              <span>{code}</span>
                              <span className="font-medium">-{formatCurrency(amount)}</span>
                            </div>
                          ))}
                      </div>
                      <div className="pt-2 border-t">
                        <div className="flex justify-between font-medium">
                          <span>Total</span>
                          <span>{formatCurrency(details.TotalAmount)}</span>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                </div>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm font-medium">Order Items</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="divide-y">
                      {details.Items?.map((item, i) => (
                        <div key={i} className="flex gap-4 py-4 first:pt-0 last:pb-0">
                          {item.ImgThumb && (
                            <img
                              src={item.ImgThumb}
                              alt={item.ProductName}
                              className="w-16 h-16 object-cover rounded-lg bg-[#faf9f7]"
                            />
                          )}
                          <div className="flex-1 min-w-0">
                            <div className="flex items-start justify-between gap-2">
                              <div>
                                <p className="font-medium text-sm">{item.ProductName}</p>
                                <p className="text-sm text-muted-foreground">
                                  {item.Quantity}x @ {formatCurrency(item.ItemPrice)}
                                </p>
                              </div>
                              <p className="text-sm font-medium text-[#237a4d] shrink-0">
                                {formatCurrency(item.RowTotal)}
                              </p>
                            </div>
                            {item.ItemStatus && item.ItemStatus !== "Ready" && (
                              <Badge variant="secondary" className="mt-2">
                                {item.ItemStatus}
                              </Badge>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </>
            )}

            {event.metric_id === METRIC_IDS.SHIPPED_ORDER && (
              <>
                <div className="mt-1">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium text-foreground">
                      {toTitleCase(details.ShippingName)}
                    </span>
                    <span className="text-sm text-muted-foreground">•</span>
                    <span className="text-sm text-muted-foreground">
                      #{details.OrderId}
                    </span>
                  </div>
                  <div className="text-sm text-muted-foreground">
                    {formatShipMethodSimple(details.ShipMethod)}
                    {event.event_properties?.ShippedBy && (
                      <>
                        <span className="text-sm text-muted-foreground"> • </span>
                        <span className="text-sm font-medium text-[#3f7fae]">Shipped by {event.event_properties.ShippedBy}</span>
                      </>
                    )}
                  </div>
                </div>
              </>
            )}

            {event.metric_id === METRIC_IDS.ACCOUNT_CREATED && (
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium">Customer Information</CardTitle>
                </CardHeader>
                <CardContent className="space-y-1">
                  <p className="text-sm font-medium">{details.EmailAddress}</p>
                  <p className="text-sm text-muted-foreground">
                    {details.FirstName} {details.LastName}
                  </p>
                </CardContent>
              </Card>
            )}

            {event.metric_id === METRIC_IDS.CANCELED_ORDER && (
              <>
                <div className="grid gap-6 sm:grid-cols-2">
                  <div className="space-y-4">
                    <Card>
                      <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium">Cancellation Details</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-1">
                        <p className="text-sm font-medium">Reason: {details.CancelReason}</p>
                        {details.CancelMessage && (
                          <p className="text-sm text-muted-foreground">{details.CancelMessage}</p>
                        )}
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader className="pb-2">
                        <CardTitle className="text-sm font-medium">Order Summary</CardTitle>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="space-y-2">
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Subtotal</span>
                            <span className="font-medium">{formatCurrency(details.Subtotal)}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Shipping</span>
                            <span className="font-medium">{formatCurrency(details.ShippingTotal)}</span>
                          </div>
                          <div className="flex justify-between text-sm">
                            <span className="text-muted-foreground">Tax</span>
                            <span className="font-medium">{formatCurrency(details.SalesTax)}</span>
                          </div>
                        </div>
                        <div className="pt-2 border-t">
                          <div className="flex justify-between font-medium text-red-600 dark:text-red-400">
                            <span>Total Refunded</span>
                            <span>{formatCurrency(details.TotalAmount)}</span>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  </div>

                  <Card>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm font-medium">Canceled Items</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <div className="divide-y">
                        {details.Items?.map((item, i) => (
                          <div key={i} className="flex gap-4 py-4 first:pt-0 last:pb-0">
                            {item.ImgThumb && (
                              <img
                                src={item.ImgThumb}
                                alt={item.ProductName}
                                className="w-16 h-16 object-cover rounded-lg bg-[#faf9f7]"
                              />
                            )}
                            <div className="flex-1 min-w-0">
                              <div className="flex items-start justify-between gap-2">
                                <div>
                                  <p className="font-medium text-sm">{item.ProductName}</p>
                                  <p className="text-sm text-muted-foreground">
                                    {item.Quantity}x @ {formatCurrency(item.ItemPrice)}
                                  </p>
                                </div>
                                <p className="text-sm font-medium text-red-600 dark:text-red-400 shrink-0">
                                  {formatCurrency(item.RowTotal)}
                                </p>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </CardContent>
                  </Card>
                </div>
              </>
            )}

            {event.metric_id === METRIC_IDS.PAYMENT_REFUNDED && (
              <div className="grid gap-6 sm:grid-cols-2">
                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm font-medium">Refund Details</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-muted-foreground">Amount Refunded</span>
                      <span className="text-sm font-medium text-red-600 dark:text-red-400">
                        {formatCurrency(details.PaymentAmount)}
                      </span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-sm text-muted-foreground">Payment Method</span>
                      <span className="text-sm">{details.PaymentName}</span>
                    </div>
                    {details.OrderMessage && (
                      <div className="pt-2 border-t mt-4">
                        <p className="text-sm text-muted-foreground">{details.OrderMessage}</p>
                      </div>
                    )}
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-sm font-medium">Customer Information</CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-1">
                    <p className="text-sm font-medium">{details.EmailAddress}</p>
                    <p className="text-sm text-muted-foreground">
                      {details.FirstName} {details.LastName}
                    </p>
                  </CardContent>
                </Card>
              </div>
            )}

            {event.metric_id === METRIC_IDS.NEW_BLOG_POST && (
              <Card>
                <CardHeader className="pb-2">
                  <CardTitle className="text-sm font-medium">{details.title}</CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <p className="text-sm text-muted-foreground whitespace-pre-wrap">
                    {details.description}
                  </p>
                  {details.url && (
                    <a
                      href={details.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-sm text-[#3f7fae] hover:underline inline-flex items-center gap-1"
                    >
                      Read More
                      <ChevronRight className="h-4 w-4" />
                    </a>
                  )}
                </CardContent>
              </Card>
            )}
          </div>
        </div>
    </>
  );

  return (
    <Dialog>
      <DialogTrigger asChild>{children}</DialogTrigger>
      <DialogContent className={scale
        ? "w-[80vw] h-[80vh] max-w-none p-0 overflow-hidden rounded-[14px] border-[#e7e5e1]"
        : "max-w-2xl max-h-[85vh] overflow-hidden flex flex-col rounded-[14px] border-[#e7e5e1]"
      }>
        {scale ? (
          <div
            className="origin-top-left flex flex-col overflow-auto"
            style={{ transform: `scale(${scale})`, width: `${100 / scale}%`, height: `${100 / scale}%` }}
          >
            {dialogInner}
          </div>
        ) : dialogInner}
      </DialogContent>
    </Dialog>
  );
};

export { EventDialog };

// Studio feed row: type is a colored dot, details collapse to one muted line,
// order flags get a single amber emphasis instead of a rainbow of badges.
const EVENT_DOTS = {
  [METRIC_IDS.PLACED_ORDER]: "#2e8f5b",
  [METRIC_IDS.SHIPPED_ORDER]: "#3f7fae",
  [METRIC_IDS.ACCOUNT_CREATED]: "#6b5fc7",
  [METRIC_IDS.CANCELED_ORDER]: "#b3503f",
  [METRIC_IDS.PAYMENT_REFUNDED]: "#c9973d",
  [METRIC_IDS.NEW_BLOG_POST]: "#a09b92",
};

const EventCard = ({ event }) => {
  const eventType = EVENT_TYPES[event.metric_id] || { label: "Event" };
  const details = event.event_properties || {};

  const datetime = event.attributes?.datetime || event.datetime || event.event_properties?.datetime;
  const timestamp = datetime ? new Date(datetime) : null;
  const isValidDate = timestamp && !isNaN(timestamp.getTime());
  const dot = EVENT_DOTS[event.metric_id] || "#a09b92";

  let name = "";
  let parts = [];
  let flags = [];

  switch (event.metric_id) {
    case METRIC_IDS.PLACED_ORDER:
      name = toTitleCase(details.ShippingName);
      parts = [`#${details.OrderId}`, formatCurrency(details.TotalAmount)];
      flags = [
        details.IsOnHold && "On Hold",
        details.OnHoldReleased && "Hold Released",
        details.StillOwes && "Owes",
        details.LocalPickup && "Local",
        details.HasPreorder && "Pre-order",
        details.HasNotions && "Notions",
        (details.OnlyDigitalGC || details.HasDigitalGC) && "eGift Card",
        (details.HasDigiItem || details.OnlyDigiItem) && "Digital",
      ].filter(Boolean);
      break;
    case METRIC_IDS.SHIPPED_ORDER:
      name = toTitleCase(details.ShippingName);
      parts = [
        `#${details.OrderId}`,
        formatShipMethodSimple(details.ShipMethod),
        details.ShippedBy && `by ${details.ShippedBy}`,
      ].filter(Boolean);
      break;
    case METRIC_IDS.ACCOUNT_CREATED:
      name =
        details.FirstName && details.LastName
          ? `${toTitleCase(details.FirstName)} ${toTitleCase(details.LastName)}`
          : "New customer";
      parts = [details.EmailAddress].filter(Boolean);
      break;
    case METRIC_IDS.CANCELED_ORDER:
      name = toTitleCase(details.ShippingName);
      parts = [
        `#${details.OrderId}`,
        formatCurrency(details.TotalAmount),
        details.CancelReason,
      ].filter(Boolean);
      break;
    case METRIC_IDS.PAYMENT_REFUNDED:
      name = toTitleCase(details.ShippingName);
      parts = [
        `#${details.FromOrder}`,
        formatCurrency(details.PaymentAmount),
        details.PaymentName && `via ${details.PaymentName}`,
      ].filter(Boolean);
      break;
    case METRIC_IDS.NEW_BLOG_POST:
      name = details.title;
      parts = [details.description].filter(Boolean);
      break;
    default:
      break;
  }

  return (
    <EventDialog event={event}>
      <button className="w-full text-left focus:outline-none focus-visible:bg-[#faf9f7]">
        <div className="flex items-start gap-2.5 border-b border-[#f5f3f0] px-4 py-2.5 transition-colors last:border-b-0 hover:bg-[#faf9f7]">
          <span
            className="mt-[7px] inline-block h-2 w-2 shrink-0 rounded-full"
            style={{ background: dot }}
          />
          <div className="min-w-0 flex-1">
            <div className="flex items-baseline justify-between gap-2">
              <span className="truncate text-[13px] font-semibold text-[#2b2925]">
                {name || eventType.label}
              </span>
              {isValidDate && (
                <time
                  className="shrink-0 text-[11px] text-[#a09b92]"
                  dateTime={timestamp.toISOString()}
                >
                  {format(timestamp, "h:mm a")}
                </time>
              )}
            </div>
            <div className="truncate text-[11.5px] text-[#7c7870]">
              {eventType.label}
              {parts.map((part, i) => (
                <span key={i}> · {part}</span>
              ))}
              {flags.length > 0 && (
                <span className="font-semibold text-[#a87a24]"> · {flags.join(" · ")}</span>
              )}
            </div>
          </div>
        </div>
      </button>
    </EventDialog>
  );
};

const DEFAULT_METRICS = Object.values(METRIC_IDS);

const EventFeed = ({
  title = "Event Feed",
  selectedMetrics = DEFAULT_METRICS,
}) => {
  const metrics = useMemo(() => selectedMetrics, [selectedMetrics]);
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [lastUpdate, setLastUpdate] = useState(null);
  const [activeEventTypes, setActiveEventTypes] = useState({
    [METRIC_IDS.PLACED_ORDER]: true,
    [METRIC_IDS.SHIPPED_ORDER]: true,
    [METRIC_IDS.ACCOUNT_CREATED]: true,
    [METRIC_IDS.CANCELED_ORDER]: true,
    [METRIC_IDS.PAYMENT_REFUNDED]: true,
    [METRIC_IDS.NEW_BLOG_POST]: true,
  });
  const [orderFilters, setOrderFilters] = useState({
    hasPreorder: false,
    localPickup: false,
    isOnHold: false,
    onHoldReleased: false,
    hasDigiItem: false,
    hasNotions: false,
    hasGiftCard: false,
    stillOwes: false,
  });

  const fetchEvents = useCallback(async () => {
    try {
      setError(null);

      // Only set loading true if we don't have any events yet
      if (events.length === 0) {
        setLoading(true);
      }

      const response = await apiClient.get("/api/klaviyo/events/feed", {
        params: {
          timeRange: "today",
          metricIds: JSON.stringify(metrics),
        },
      });

      // Keep the original event structure intact
      const processedEvents = (response.data.data || []).map((event) => ({
        ...event,
        datetime: event.attributes?.datetime || event.datetime,
        // Don't spread event_properties to preserve the nested structure
        event_properties: event.attributes?.event_properties || {}
      }));

      setEvents(processedEvents);
      setLastUpdate(new Date());
    } catch (error) {
      console.error("Error fetching events:", error);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  }, [metrics]);

  // Fetch events on mount and every minute
  useEffect(() => {
    fetchEvents();
    const interval = setInterval(fetchEvents, 60000); // Refresh every minute

    return () => {
      clearInterval(interval);
    };
  }, [fetchEvents]);

  const filteredEvents = useMemo(() => {
    // Check if any order property filters are active
    const hasActiveOrderFilters = Object.values(orderFilters).some(filter => filter);

    return events.filter(event => {
      // First check event type filter
      if (!activeEventTypes[event.metric_id]) {
        return false;
      }

      // Then check order property filters if any are active
      if (hasActiveOrderFilters) {
        if (event.metric_id !== METRIC_IDS.PLACED_ORDER) return false;
        
        const details = event.event_properties || {};
        if (orderFilters.hasPreorder && !details.HasPreorder) return false;
        if (orderFilters.localPickup && !details.LocalPickup) return false;
        if (orderFilters.isOnHold && !details.IsOnHold) return false;
        if (orderFilters.onHoldReleased && !details.OnHoldReleased) return false;
        if (orderFilters.hasDigiItem && !details.HasDigiItem) return false;
        if (orderFilters.hasNotions && !details.HasNotions) return false;
        if (orderFilters.hasGiftCard && !details.HasDigitalGC) return false;
        if (orderFilters.stillOwes && !details.StillOwes) return false;
      }

      return true;
    });
  }, [events, activeEventTypes, orderFilters]);

  // Calculate counts for event types and order properties
  const counts = useMemo(() => {
    const eventTypeCounts = {
      [METRIC_IDS.PLACED_ORDER]: 0,
      [METRIC_IDS.SHIPPED_ORDER]: 0,
      [METRIC_IDS.ACCOUNT_CREATED]: 0,
      [METRIC_IDS.CANCELED_ORDER]: 0,
      [METRIC_IDS.PAYMENT_REFUNDED]: 0,
      [METRIC_IDS.NEW_BLOG_POST]: 0,
    };

    const orderPropertyCounts = {
      hasPreorder: 0,
      localPickup: 0,
      isOnHold: 0,
      onHoldReleased: 0,
      hasDigiItem: 0,
      hasNotions: 0,
      hasGiftCard: 0,
      stillOwes: 0,
    };

    events.forEach(event => {
      // Count event types
      if (event.metric_id) {
        eventTypeCounts[event.metric_id]++;
      }

      // Count order properties
      if (event.metric_id === METRIC_IDS.PLACED_ORDER) {
        const details = event.event_properties || {};
        if (details.HasPreorder) orderPropertyCounts.hasPreorder++;
        if (details.LocalPickup) orderPropertyCounts.localPickup++;
        if (details.IsOnHold) orderPropertyCounts.isOnHold++;
        if (details.OnHoldReleased) orderPropertyCounts.onHoldReleased++;
        if (details.HasDigiItem) orderPropertyCounts.hasDigiItem++;
        if (details.HasNotions) orderPropertyCounts.hasNotions++;
        if (details.HasDigitalGC) orderPropertyCounts.hasGiftCard++;
        if (details.StillOwes) orderPropertyCounts.stillOwes++;
      }
    });

    return {
      eventTypes: eventTypeCounts,
      orderProperties: orderPropertyCounts,
    };
  }, [events]);

  const handleOrderPropertyClick = (property) => {
    setOrderFilters(prev => {
      // If clicking the active filter, clear all filters
      if (prev[property]) {
        return {
          hasPreorder: false,
          localPickup: false,
          isOnHold: false,
          onHoldReleased: false,
          hasDigiItem: false,
          hasNotions: false,
          hasGiftCard: false,
          stillOwes: false,
        };
      }
      // Otherwise, set only this filter to true
      return {
        hasPreorder: property === 'hasPreorder',
        localPickup: property === 'localPickup',
        isOnHold: property === 'isOnHold',
        onHoldReleased: property === 'onHoldReleased',
        hasDigiItem: property === 'hasDigiItem',
        hasNotions: property === 'hasNotions',
        hasGiftCard: property === 'hasGiftCard',
        stillOwes: property === 'stillOwes',
      };
    });
  };

  const handleEventTypeClick = (metricId) => {
    setActiveEventTypes(prev => {
      // If clicking the only active filter, reset to all active
      const activeCount = Object.values(prev).filter(Boolean).length;
      if (activeCount === 1 && prev[metricId]) {
        return {
          [METRIC_IDS.PLACED_ORDER]: true,
          [METRIC_IDS.SHIPPED_ORDER]: true,
          [METRIC_IDS.ACCOUNT_CREATED]: true,
          [METRIC_IDS.CANCELED_ORDER]: true,
          [METRIC_IDS.PAYMENT_REFUNDED]: true,
          [METRIC_IDS.NEW_BLOG_POST]: true,
        };
      }
      // Otherwise, set only this filter to true
      return {
        [METRIC_IDS.PLACED_ORDER]: metricId === METRIC_IDS.PLACED_ORDER,
        [METRIC_IDS.SHIPPED_ORDER]: metricId === METRIC_IDS.SHIPPED_ORDER,
        [METRIC_IDS.ACCOUNT_CREATED]: metricId === METRIC_IDS.ACCOUNT_CREATED,
        [METRIC_IDS.CANCELED_ORDER]: metricId === METRIC_IDS.CANCELED_ORDER,
        [METRIC_IDS.PAYMENT_REFUNDED]: metricId === METRIC_IDS.PAYMENT_REFUNDED,
        [METRIC_IDS.NEW_BLOG_POST]: metricId === METRIC_IDS.NEW_BLOG_POST,
      };
    });
  };

  const TYPE_FILTERS = [
    { id: METRIC_IDS.PLACED_ORDER, label: "Orders" },
    { id: METRIC_IDS.SHIPPED_ORDER, label: "Shipped" },
    { id: METRIC_IDS.ACCOUNT_CREATED, label: "Accounts" },
    { id: METRIC_IDS.CANCELED_ORDER, label: "Canceled" },
    { id: METRIC_IDS.PAYMENT_REFUNDED, label: "Refunds" },
    { id: METRIC_IDS.NEW_BLOG_POST, label: "Blog" },
  ];

  return (
    <Card className={`flex flex-col h-full ${CARD_STYLES.base} w-full`}>
      <CardHeader className="space-y-2 border-b border-[#f0eeea] px-4 pb-3.5 pt-4">
        <CardTitle className="text-[12.5px] font-semibold tracking-tight text-[#2b2925]">
          {title}
        </CardTitle>

        {/* Event-type filter pills — dot doubles as the type legend */}
        {!error && (
          <div className="flex flex-wrap items-center gap-1">
            {TYPE_FILTERS.map(({ id, label }) => (
              <button
                key={id}
                type="button"
                onClick={() => handleEventTypeClick(id)}
                className={`flex h-7 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[11px] font-medium transition-colors ${
                  activeEventTypes[id]
                    ? "bg-[#f0eeea] text-[#2b2925] hover:bg-[#eae7e2]"
                    : "text-[#a09b92] hover:bg-[#f5f3f0] hover:text-[#2b2925]"
                }`}
              >
                <span
                  className="inline-block h-1.5 w-1.5 rounded-full"
                  style={{ background: activeEventTypes[id] ? EVENT_DOTS[id] : "#d8d4cd" }}
                />
                {label}
                {counts.eventTypes[id] > 0 && (
                  <span className="tabular-nums text-[#a09b92]">{counts.eventTypes[id]}</span>
                )}
              </button>
            ))}
          </div>
        )}
      </CardHeader>

      <CardContent className="px-0 pb-4 pt-0 md:px-4 flex-1 overflow-hidden">
        <ScrollArea className="h-full">
          {loading && !events.length ? (
            <LoadingState />
          ) : error ? (
            <DashboardErrorState error={`Failed to load event feed: ${error}`} className="mt-1 mx-2" />
          ) : !filteredEvents || filteredEvents.length === 0 ? (
            <EmptyState />
          ) : (
            <div>
              {filteredEvents.map((event) => (
                <EventCard key={event.id} event={event} />
              ))}
            </div>
          )}
        </ScrollArea>
      </CardContent>
    </Card>
  );
};

export default EventFeed;
