import { Fragment } from "react";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { DiscountSimulationBucket } from "@/types/discount-simulator";
import { formatCurrency, formatNumber } from "@/utils/productUtils";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";

// Utility function to interpolate between two colors
const interpolateColor = (color1: [number, number, number], color2: [number, number, number], ratio: number): [number, number, number] => {
  return [
    Math.round(color1[0] + (color2[0] - color1[0]) * ratio),
    Math.round(color1[1] + (color2[1] - color1[1]) * ratio),
    Math.round(color1[2] + (color2[2] - color1[2]) * ratio)
  ];
};

// Utility function to calculate color based on profit percentage
const getProfitPercentageColor = (percentage: number): string => {
  const percent = percentage * 100; // Convert to percentage
  
  // Define color points (RGB values for red-400, yellow-400, green-400)
  const red: [number, number, number] = [248, 113, 113]; // red-400
  const yellow: [number, number, number] = [251, 191, 36]; // yellow-400
  const green: [number, number, number] = [74, 222, 128]; // green-400
  
  const min = 25;
  const mid = 29;
  const max = 35;
  
  let rgb: [number, number, number];
  
  if (percent <= min) {
    rgb = red;
  } else if (percent >= max) {
    rgb = green;
  } else if (percent <= mid) {
    // Interpolate between red and yellow
    const ratio = (percent - min) / (mid - min);
    rgb = interpolateColor(red, yellow, ratio);
  } else {
    // Interpolate between yellow and green
    const ratio = (percent - mid) / (max - mid);
    rgb = interpolateColor(yellow, green, ratio);
  }
  
  return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
};

interface ResultsTableProps {
  buckets: DiscountSimulationBucket[];
  isLoading: boolean;
}

type MetricGroup =
  | "orderVolume"
  | "customerSpend"
  | "discounts"
  | "shipping"
  | "costs"
  | "outcomes";

const metricGroupStyles: Record<MetricGroup, { label: string; indicatorClass: string; badgeClass: string; rowClass: string }> = {
  orderVolume: {
    label: "Order Volume",
    indicatorClass: "bg-sky-500",
    badgeClass: "bg-sky-100 text-sky-900 border-sky-200 uppercase",
    rowClass: "bg-sky-50",
  },
  customerSpend: {
    label: "Customer Spend",
    indicatorClass: "bg-indigo-500",
    badgeClass: "bg-indigo-100 text-indigo-900 border-indigo-200 uppercase",
    rowClass: "bg-indigo-50",
  },
  discounts: {
    label: "Discounts",
    indicatorClass: "bg-amber-500",
    badgeClass: "bg-amber-100 text-amber-900 border-amber-200 uppercase",
    rowClass: "bg-amber-50",
  },
  shipping: {
    label: "Shipping Impact",
    indicatorClass: "bg-cyan-500",
    badgeClass: "bg-cyan-100 text-cyan-900 border-cyan-200 uppercase",
    rowClass: "bg-cyan-50",
  },
  costs: {
    label: "Cost Inputs",
    indicatorClass: "bg-rose-500",
    badgeClass: "bg-rose-100 text-rose-900 border-rose-200 uppercase",
    rowClass: "bg-rose-50",
  },
  outcomes: {
    label: "Results",
    indicatorClass: "bg-emerald-600",
    badgeClass: "bg-emerald-100 text-emerald-900 border-emerald-200 uppercase",
    rowClass: "bg-emerald-50",
  },
};

interface RowConfig {
  key: keyof DiscountSimulationBucket;
  label: string;
  format: (value: number) => string;
  important?: boolean;
  isCalculated: boolean;
  group: MetricGroup;
}

const rowLabels: RowConfig[] = [
  { key: "orderCount", label: "Orders", format: (value: number) => formatNumber(value), isCalculated: false, group: "orderVolume" },
  { key: "weight", label: "Weight", format: (value: number) => `${(value * 100).toFixed(2)}%`, isCalculated: false, group: "orderVolume" },
  { key: "orderValue", label: "Order Value", format: (value: number) => formatCurrency(value), isCalculated: false, group: "customerSpend" },
  { key: "customerItemCost", label: "Cust Item Cost", format: (value: number) => formatCurrency(value), isCalculated: true, group: "customerSpend" },
  { key: "customerShipCost", label: "Cust Ship Cost", format: (value: number) => formatCurrency(value), isCalculated: true, group: "customerSpend" },
  { key: "productDiscountAmount", label: "Prod Discount", format: (value: number) => formatCurrency(value), isCalculated: true, group: "discounts" },
  { key: "promoProductDiscount", label: "Promo Prod Disc", format: (value: number) => formatCurrency(value), isCalculated: true, group: "discounts" },
  { key: "shipPromoDiscount", label: "Ship Promo Disc", format: (value: number) => formatCurrency(value), isCalculated: true, group: "discounts" },
  { key: "shippingAfterAuto", label: "Ship Charge", format: (value: number) => formatCurrency(value), isCalculated: true, group: "shipping" },
  { key: "actualShippingCost", label: "Actual Ship Cost", format: (value: number) => formatCurrency(value), isCalculated: false, group: "shipping" },
  { key: "productCogs", label: "Product COGS", format: (value: number) => formatCurrency(value), isCalculated: false, group: "costs" },
  { key: "merchantFees", label: "Merchant Fees", format: (value: number) => formatCurrency(value), isCalculated: true, group: "costs" },
  { key: "pointsCost", label: "Points Cost", format: (value: number) => formatCurrency(value), isCalculated: true, group: "costs" },
  { key: "fixedCosts", label: "Fixed Cost", format: (value: number) => formatCurrency(value), isCalculated: true, group: "costs" },
  { key: "totalRevenue", label: "Total Revenue", format: (value: number) => formatCurrency(value), important: true, isCalculated: true, group: "outcomes" },
  { key: "totalCosts", label: "Total Cost", format: (value: number) => formatCurrency(value), important: true, isCalculated: true, group: "outcomes" },
  { key: "profit", label: "Profit $", format: (value: number) => formatCurrency(value), important: true, isCalculated: true, group: "outcomes" },
  { key: "profitPercent", label: "Profit %", format: (value: number) => `${(value * 100).toFixed(2)}%`, important: true, isCalculated: true, group: "outcomes" },
];

const formatRangeUpperBound = (bucket: DiscountSimulationBucket) => {
  if (bucket.max == null) {
    return `${formatCurrency(bucket.min, 0)}+`;
  }

  return `${formatCurrency(bucket.min, 0)}–${formatCurrency(bucket.max, 0)}`;
};

export function ResultsTable({ buckets, isLoading }: ResultsTableProps) {
  if (isLoading && buckets.length === 0) {
    return (
      <Card>
        <CardHeader className="px-4 py-3">
          <CardTitle className="text-base font-semibold">Profitability by Order Value</CardTitle>
        </CardHeader>
        <CardContent className="px-4 pb-4 pt-0">
          <Skeleton className="h-36 w-full" />
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="pt-6">
      <CardContent className="px-4 pb-4 pt-0">
        <div className="overflow-x-auto max-w-full">
          <Table className="text-sm table-fixed">
            <colgroup>
              <col style={{ width: '156px' }} />
              {buckets.map((bucket) => (
                <col key={bucket.key} style={{ minWidth: '95px', width: '110px' }} />
              ))}
            </colgroup>
            <TableHeader>
              <TableRow>
                <TableHead className="font-medium sticky left-0 bg-background z-10 px-3 py-2 border-r">Metric</TableHead>
                {buckets.map((bucket) => (
                  <TableHead key={bucket.key} className="text-center whitespace-nowrap px-1 py-2 font-medium">
                    {formatRangeUpperBound(bucket)}
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {buckets.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={buckets.length + 1} className="text-center text-muted-foreground">
                    No data available for the selected configuration.
                  </TableCell>
                </TableRow>
              ) : (
                rowLabels.map((row, index) => {
                  const groupStyle = metricGroupStyles[row.group];
                  const isImportant = Boolean(row.important);
                  const prevGroup = index > 0 ? rowLabels[index - 1].group : null;
                  const isFirstOfGroup = prevGroup !== row.group;

                  return (
                    <Fragment key={`${row.group}-${row.key}`}>
                      {isFirstOfGroup && (
                        <TableRow className={cn(groupStyle.badgeClass)}>
                          <TableCell
                            colSpan={buckets.length + 1}
                            className={cn(
                              "border-0 px-3 py-0",
                              groupStyle.badgeClass,
                              index !== 0 && "pt-0"
                            )}
                          >
                            <div className="flex items-center gap-2">
                              
                              <div
                                
                                className={cn(
                                  "px-2 py-1 font-semibold tracking-wide text-xs",
                                  groupStyle.badgeClass
                                )}
                              >
                                {groupStyle.label}
                              </div>
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                      <TableRow className={cn("align-top", groupStyle.rowClass)}>
                        <TableCell
                          className={cn(
                            "sticky left-0 z-10 border-r px-3 py-2",
                            groupStyle.rowClass,
                            isImportant ? "font-semibold text-emerald-800" : "font-medium text-slate-700"
                          )}
                        >
                          <div className="flex items-center gap-2">
                            <span
                              aria-hidden
                              className={cn("h-4 w-1 rounded-full", groupStyle.indicatorClass)}
                            />
                            <span
                              className={cn(
                                "text-sm leading-tight pr-2",
                                isImportant ? "font-semibold text-emerald-900" : "font-medium text-slate-800"
                              )}
                            >
                              {row.label}
                            </span>
                            <TooltipProvider>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <span
                                    className={cn(
                                      "inline-block h-2.5 w-2.5 rounded-full shadow-sm absolute right-1 top-1/2 -translate-y-1/2",
                                      row.isCalculated ? "bg-blue-400" : "bg-emerald-400"
                                    )}
                                  />
                                </TooltipTrigger>
                                <TooltipContent>
                                  <p>{row.isCalculated ? "Calculated value" : "Database value"}</p>
                                </TooltipContent>
                              </Tooltip>
                            </TooltipProvider>
                          </div>
                        </TableCell>
                        {buckets.map((bucket) => {
                          const value = bucket[row.key as keyof DiscountSimulationBucket] as number;
                          const formattedValue = row.format(value);

                          if (row.key === "profitPercent") {
                            const backgroundColor = getProfitPercentageColor(value);
                            return (
                              <TableCell
                                key={`${row.key}-${bucket.key}`}
                                className={cn(
                                  "text-center whitespace-nowrap px-1 py-1 text-slate-700",
                                  groupStyle.rowClass,
                                  isImportant && "font-semibold text-emerald-700"
                                )}
                              >
                                <span
                                  className="inline-block rounded px-1.5 py-0.5 text-white font-medium"
                                  style={{ backgroundColor }}
                                >
                                  {formattedValue}
                                </span>
                              </TableCell>
                            );
                          }

                          return (
                            <TableCell
                              key={`${row.key}-${bucket.key}`}
                              className={cn(
                                "text-center whitespace-nowrap px-1 py-1 text-slate-700",
                                groupStyle.rowClass,
                                isImportant && "font-semibold text-emerald-700"
                              )}
                            >
                              {formattedValue}
                            </TableCell>
                          );
                        })}
                      </TableRow>
                    </Fragment>
                  );
                })
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
