/**
 * DashboardChartTooltip
 *
 * Standardized tooltip components for Recharts across the dashboard.
 * Provides consistent styling and formatting for all chart tooltips.
 *
 * @example
 * // Basic usage with Recharts
 * <RechartsTooltip content={<DashboardChartTooltip />} />
 *
 * @example
 * // Currency tooltip
 * <RechartsTooltip content={<CurrencyTooltip />} />
 *
 * @example
 * // Custom formatter
 * <RechartsTooltip
 *   content={
 *     <DashboardChartTooltip
 *       valueFormatter={(value) => `${value} units`}
 *       labelFormatter={(label) => `Week of ${label}`}
 *     />
 *   }
 * />
 */

import React from "react";
import { cn } from "@/lib/utils";
import { TOOLTIP_STYLES } from "@/lib/dashboard/chartConfig";

// =============================================================================
// TYPES
// =============================================================================

export interface TooltipPayloadItem {
  name: string;
  value: number | string;
  color?: string;
  dataKey?: string;
  payload?: Record<string, unknown>;
  fill?: string;
  stroke?: string;
}

export interface DashboardChartTooltipProps {
  /** Whether the tooltip is currently active (provided by Recharts) */
  active?: boolean;
  /** The payload data (provided by Recharts) */
  payload?: TooltipPayloadItem[];
  /** The label for the tooltip header (provided by Recharts) */
  label?: string;
  /** Custom formatter for the value */
  valueFormatter?: (value: number | string, name: string) => string;
  /** Custom formatter for the label/header */
  labelFormatter?: (label: string) => string;
  /** Custom formatter for item names */
  nameFormatter?: (name: string) => string;
  /** Hide the header/label */
  hideLabel?: boolean;
  /** Additional className for the container */
  className?: string;
  /** Show a divider between items */
  showDivider?: boolean;
  /** Custom render function for each item */
  itemRenderer?: (item: TooltipPayloadItem, index: number) => React.ReactNode;
}

// =============================================================================
// FORMATTERS
// =============================================================================

/**
 * Format a number as currency
 */
export const formatCurrency = (value: number | string): string => {
  const num = typeof value === "string" ? parseFloat(value) : value;
  if (isNaN(num)) return "$0";

  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
    maximumFractionDigits: 2,
  }).format(num);
};

/**
 * Format a number as percentage
 */
export const formatPercentage = (value: number | string): string => {
  const num = typeof value === "string" ? parseFloat(value) : value;
  if (isNaN(num)) return "0%";
  return `${num.toFixed(1)}%`;
};

/**
 * Format a number with commas
 */
export const formatNumber = (value: number | string): string => {
  const num = typeof value === "string" ? parseFloat(value) : value;
  if (isNaN(num)) return "0";
  return num.toLocaleString();
};

/**
 * Format a duration in seconds to human-readable format
 */
export const formatDuration = (seconds: number | string): string => {
  const num = typeof seconds === "string" ? parseFloat(seconds) : seconds;
  if (isNaN(num)) return "0s";

  const hours = Math.floor(num / 3600);
  const minutes = Math.floor((num % 3600) / 60);
  const secs = Math.floor(num % 60);

  if (hours > 0) {
    return `${hours}h ${minutes}m`;
  }
  if (minutes > 0) {
    return `${minutes}m ${secs}s`;
  }
  return `${secs}s`;
};

// =============================================================================
// MAIN COMPONENT
// =============================================================================

export const DashboardChartTooltip: React.FC<DashboardChartTooltipProps> = ({
  active,
  payload,
  label,
  valueFormatter,
  labelFormatter,
  nameFormatter,
  hideLabel = false,
  className,
  showDivider = false,
  itemRenderer,
}) => {
  if (!active || !payload?.length) {
    return null;
  }

  const formattedLabel = labelFormatter ? labelFormatter(String(label)) : label;

  return (
    <div className={cn(TOOLTIP_STYLES.container, className)}>
      {!hideLabel && formattedLabel && (
        <p className={TOOLTIP_STYLES.header}>{formattedLabel}</p>
      )}
      <div className={TOOLTIP_STYLES.content}>
        {payload.map((item, index) => {
          // Allow custom item rendering
          if (itemRenderer) {
            return (
              <React.Fragment key={index}>
                {itemRenderer(item, index)}
              </React.Fragment>
            );
          }

          const itemColor = item.color || item.fill || item.stroke || "#888";
          const itemName = nameFormatter ? nameFormatter(item.name) : item.name;
          const itemValue = valueFormatter
            ? valueFormatter(item.value, item.name)
            : String(item.value);

          return (
            <React.Fragment key={index}>
              {showDivider && index > 0 && (
                <div className={TOOLTIP_STYLES.divider} />
              )}
              <div className={TOOLTIP_STYLES.row}>
                <div className={TOOLTIP_STYLES.rowLabel}>
                  <span
                    className={TOOLTIP_STYLES.dot}
                    style={{ backgroundColor: itemColor }}
                  />
                  <span className={TOOLTIP_STYLES.name}>{itemName}</span>
                </div>
                <span className={TOOLTIP_STYLES.value}>{itemValue}</span>
              </div>
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
};

// =============================================================================
// SPECIALIZED TOOLTIPS
// =============================================================================

/**
 * Currency-formatted tooltip
 */
export const CurrencyTooltip: React.FC<Omit<DashboardChartTooltipProps, "valueFormatter">> = (
  props
) => {
  return <DashboardChartTooltip {...props} valueFormatter={formatCurrency} />;
};

/**
 * Percentage-formatted tooltip
 */
export const PercentageTooltip: React.FC<Omit<DashboardChartTooltipProps, "valueFormatter">> = (
  props
) => {
  return <DashboardChartTooltip {...props} valueFormatter={formatPercentage} />;
};

/**
 * Number-formatted tooltip (with commas)
 */
export const NumberTooltip: React.FC<Omit<DashboardChartTooltipProps, "valueFormatter">> = (
  props
) => {
  return <DashboardChartTooltip {...props} valueFormatter={formatNumber} />;
};

/**
 * Duration-formatted tooltip (for call times, etc.)
 */
export const DurationTooltip: React.FC<Omit<DashboardChartTooltipProps, "valueFormatter">> = (
  props
) => {
  return <DashboardChartTooltip {...props} valueFormatter={formatDuration} />;
};

// =============================================================================
// SIMPLE TOOLTIP (for single-value charts)
// =============================================================================

export interface SimpleTooltipProps {
  active?: boolean;
  payload?: TooltipPayloadItem[];
  label?: string;
  valueFormatter?: (value: number | string) => string;
  labelFormatter?: (label: string) => string;
  className?: string;
}

/**
 * Simplified tooltip for single-series charts
 */
export const SimpleTooltip: React.FC<SimpleTooltipProps> = ({
  active,
  payload,
  label,
  valueFormatter = formatNumber,
  labelFormatter,
  className,
}) => {
  if (!active || !payload?.length) {
    return null;
  }

  const item = payload[0];
  const formattedLabel = labelFormatter ? labelFormatter(String(label)) : label;
  const formattedValue = valueFormatter(item.value);

  return (
    <div className={cn(TOOLTIP_STYLES.container, className)}>
      {formattedLabel && (
        <p className={TOOLTIP_STYLES.header}>{formattedLabel}</p>
      )}
      <p className={TOOLTIP_STYLES.value}>{formattedValue}</p>
    </div>
  );
};

export default DashboardChartTooltip;
