import { AlertCircle, DollarSign } from 'lucide-react';

import { cn } from '@/lib/utils';

interface CostEstimateDisplayProps {
  estimate: {
    selected_count: number;
    estimated_input_tokens: number;
    estimated_output_tokens: number;
    estimated_total_tokens: number;
    estimated_cost: number;
    cost_per_recommendation: number;
    model?: string;
  };
  limits?: {
    max_drafts_per_month: number | null;
    drafts_used_this_month: number;
  } | null;
}

function formatTokens(tokens: number): string {
  if (tokens >= 1_000_000) {
    return `${(tokens / 1_000_000).toFixed(1)}M`;
  }
  if (tokens >= 1_000) {
    return `${(tokens / 1_000).toFixed(1)}K`;
  }
  return tokens.toString();
}

function formatCost(cost: number): string {
  if (cost < 0.01) {
    return '<$0.01';
  }
  return `$${cost.toFixed(2)}`;
}

export default function CostEstimateDisplay({ estimate, limits }: CostEstimateDisplayProps) {
  const approachingLimit =
    limits?.max_drafts_per_month !== null && limits?.max_drafts_per_month !== undefined
      ? limits.drafts_used_this_month + estimate.selected_count > limits.max_drafts_per_month * 0.8
      : false;

  const exceedsLimit =
    limits?.max_drafts_per_month !== null && limits?.max_drafts_per_month !== undefined
      ? limits.drafts_used_this_month + estimate.selected_count > limits.max_drafts_per_month
      : false;

  return (
    <div className="space-y-3">
      <div className="rounded-lg border bg-muted/50 p-4">
        <div className="flex items-center gap-2 mb-3">
          <DollarSign className="h-4 w-4 text-muted-foreground" />
          <span className="text-sm font-medium">Cost Estimate</span>
        </div>

        <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
          <span className="text-muted-foreground">Selected:</span>
          <span className="font-medium text-foreground">
            {estimate.selected_count} recommendations
          </span>

          {estimate.model && (
            <>
              <span className="text-muted-foreground">Model:</span>
              <span className="font-medium text-foreground">{estimate.model}</span>
            </>
          )}

          <span className="text-muted-foreground">Cost per draft:</span>
          <span className="font-medium text-foreground">
            {formatCost(estimate.cost_per_recommendation)}
          </span>

          <span className="text-muted-foreground">Breakdown:</span>
          <span className="font-medium text-foreground">
            {formatCost(estimate.cost_per_recommendation)} × {estimate.selected_count} ={' '}
            {formatCost(estimate.estimated_cost)}
          </span>

          <span className="text-muted-foreground">Est. tokens:</span>
          <span className="font-medium text-foreground">
            {formatTokens(estimate.estimated_total_tokens)}
            <span className="text-xs text-muted-foreground ml-1">
              ({formatTokens(estimate.estimated_input_tokens)} in +{' '}
              {formatTokens(estimate.estimated_output_tokens)} out)
            </span>
          </span>
        </div>

        <p className="text-xs text-muted-foreground mt-3">
          Estimates based on average content length. Actual cost may vary. Charged by OpenAI to your
          API key.
        </p>
      </div>

      {estimate.estimated_cost > 1 && (
        <div className="rounded-lg border border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-800 p-3 flex items-start gap-2">
          <AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
          <div className="text-sm">
            <p className="font-medium text-amber-800 dark:text-amber-200">High estimated cost</p>
            <p className="text-xs text-amber-700 dark:text-amber-300">
              This batch is estimated to cost {formatCost(estimate.estimated_cost)}. Please review
              before proceeding.
            </p>
          </div>
        </div>
      )}

      {approachingLimit && (
        <div
          className={cn(
            'rounded-lg border p-3 flex items-start gap-2',
            exceedsLimit
              ? 'border-red-200 bg-red-50 dark:bg-red-950/20 dark:border-red-800'
              : 'border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-800',
          )}
        >
          <AlertCircle
            className={cn(
              'h-4 w-4 mt-0.5 flex-shrink-0',
              exceedsLimit
                ? 'text-red-600 dark:text-red-400'
                : 'text-amber-600 dark:text-amber-400',
            )}
          />
          <div className="text-sm space-y-1">
            <p
              className={cn(
                'font-medium',
                exceedsLimit
                  ? 'text-red-800 dark:text-red-200'
                  : 'text-amber-800 dark:text-amber-200',
              )}
            >
              {exceedsLimit ? 'Monthly limit exceeded' : 'Approaching monthly limit'}
            </p>
            <p
              className={cn(
                'text-xs',
                exceedsLimit
                  ? 'text-red-700 dark:text-red-300'
                  : 'text-amber-700 dark:text-amber-300',
              )}
            >
              You&apos;ve used {limits?.drafts_used_this_month ?? 0} of{' '}
              {limits?.max_drafts_per_month ?? 0} drafts this month.
              {exceedsLimit
                ? ' This batch would exceed your monthly limit.'
                : ' This batch will use a significant portion of your remaining quota.'}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}
