import { differenceInDays } from "date-fns";
import { Card, CardContent } from "@/components/ui/card";
import { formatCurrency } from "@/utils/productUtils";
import { DiscountSimulationResponse } from "@/types/discount-simulator";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { Bookmark, X } from "lucide-react";

// 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 SummaryCardProps {
  result?: DiscountSimulationResponse;
  isLoading: boolean;
  baselineResult?: DiscountSimulationResponse;
  onSaveAsBaseline?: () => void;
  onClearBaseline?: () => void;
}

function rangesMatch(a: DiscountSimulationResponse, b: DiscountSimulationResponse): boolean {
  return a.dateRange.start === b.dateRange.start && a.dateRange.end === b.dateRange.end;
}

function calculateAnnualizedProfitDiff(
  current: DiscountSimulationResponse,
  baseline: DiscountSimulationResponse
): number | null {
  const currentTotals = current.totals;
  const baselineTotals = baseline.totals;

  if (!currentTotals || !baselineTotals) return null;
  if (!Number.isFinite(currentTotals.weightedProfitAmount) || !Number.isFinite(baselineTotals.weightedProfitAmount)) {
    return null;
  }

  // Calculate days in the current simulation period
  const startDate = new Date(current.dateRange.start);
  const endDate = new Date(current.dateRange.end);
  const daysInPeriod = differenceInDays(endDate, startDate) + 1; // +1 to include both start and end days

  if (daysInPeriod <= 0) return null;

  // Profit difference per order
  const profitDiffPerOrder = currentTotals.weightedProfitAmount - baselineTotals.weightedProfitAmount;

  // Total profit difference for the period
  const totalProfitDiff = profitDiffPerOrder * currentTotals.orders;

  // Annualize: scale to 365 days
  const annualizedDiff = (totalProfitDiff / daysInPeriod) * 365;

  return annualizedDiff;
}

const formatPercent = (value: number) => {
  if (!Number.isFinite(value)) return 'N/A';
  return `${(value * 100).toFixed(2)}%`;
};

export function SummaryCard({
  result,
  isLoading,
  baselineResult,
  onSaveAsBaseline,
  onClearBaseline
}: SummaryCardProps) {
  if (isLoading && !result) {
    return (
      <Card>
        <CardContent className="py-4">
          <div className="flex items-center justify-center gap-8">
            <div className="text-center space-y-2">
              <Skeleton className="h-4 w-24 mx-auto" />
              <Skeleton className="h-8 w-20 mx-auto" />
            </div>
            <Separator orientation="vertical" className="h-12" />
            <div className="text-center space-y-2">
              <Skeleton className="h-4 w-32 mx-auto" />
              <Skeleton className="h-8 w-24 mx-auto" />
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  const totals = result?.totals;
  const weightedProfitAmount = totals && Number.isFinite(totals.weightedProfitAmount)
    ? formatCurrency(totals.weightedProfitAmount)
    : '—';
  const weightedProfitPercent = totals ? formatPercent(totals.weightedProfitPercent) : '—';

  // Get color for profit percentage
  const profitPercentageColor = totals ? getProfitPercentageColor(totals.weightedProfitPercent) : '';

  const weightedBadgeVariant = totals
    ? totals.weightedProfitAmount >= 0
      ? "default"
      : "destructive"
    : "secondary";

  const baselineScopeMatches = !!(result && baselineResult && rangesMatch(result, baselineResult));
  // Calculate annualized profit difference if baseline exists and scope matches
  const annualizedDiff = result && baselineResult && baselineScopeMatches
    ? calculateAnnualizedProfitDiff(result, baselineResult)
    : null;
  const hasBaseline = !!baselineResult;
  const isPositiveDiff = annualizedDiff !== null && annualizedDiff >= 0;

  return (
    <Card>
      <CardContent className="py-4">
        <div className="flex items-center justify-center gap-6">
          {/* Weighted Average Profit */}
          <div className="text-center">
            <p className="text-sm text-muted-foreground mb-2">Weighted Average Profit</p>
            {totals ? (
              <span
                className="inline-block px-3 py-1.5 rounded text-white font-semibold text-lg"
                style={{ backgroundColor: profitPercentageColor }}
              >
                {weightedProfitPercent}
              </span>
            ) : (
              <Badge variant={weightedBadgeVariant} className="text-lg py-1.5 px-3 font-semibold">
                {weightedProfitPercent}
              </Badge>
            )}
          </div>

          <Separator orientation="vertical" className="h-12" />

          {/* Weighted Profit Per Order */}
          <div className="text-center">
            <p className="text-sm text-muted-foreground mb-2">Weighted Profit Per Order</p>
            <Badge variant="secondary" className="text-lg py-1.5 px-3 font-semibold">
              {weightedProfitAmount}
            </Badge>
          </div>

          {/* Baseline comparison section */}
          {hasBaseline && annualizedDiff !== null && (
            <>
              <Separator orientation="vertical" className="h-12" />
              <div className="text-center">
                <p className="text-sm text-muted-foreground mb-2">Annual Change vs Baseline</p>
                <span
                  className={`inline-block px-3 py-1.5 rounded bg-secondary font-semibold text-lg ${
                    isPositiveDiff ? 'text-green-600' : 'text-red-600'
                  }`}
                >
                  {isPositiveDiff ? '+' : ''}{formatCurrency(annualizedDiff)}
                </span>
              </div>
              <Button
                variant="ghost"
                size="sm"
                className="text-xs text-muted-foreground hover:text-foreground"
                onClick={onClearBaseline}
              >
                <X className="h-3 w-3 mr-1" />
                Clear
              </Button>
            </>
          )}

          {hasBaseline && !baselineScopeMatches && (
            <>
              <Separator orientation="vertical" className="h-12" />
              <div className="text-center">
                <p className="text-sm text-muted-foreground mb-2">Baseline</p>
                <span className="inline-block px-3 py-1.5 rounded bg-secondary text-amber-700 text-sm">
                  Date range changed — clear or restore to compare
                </span>
              </div>
              <Button
                variant="ghost"
                size="sm"
                className="text-xs text-muted-foreground hover:text-foreground"
                onClick={onClearBaseline}
              >
                <X className="h-3 w-3 mr-1" />
                Clear
              </Button>
            </>
          )}

          {/* Save as baseline button */}
          {result && !hasBaseline && (
            <>
              <Separator orientation="vertical" className="h-12" />
              <Button
                variant="outline"
                size="sm"
                onClick={onSaveAsBaseline}
              >
                <Bookmark className="h-3 w-3 mr-1" />
                Set as baseline
              </Button>
            </>
          )}
        </div>
      </CardContent>
    </Card>
  );
}
