import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import {
  CHANNELS,
  type ChannelId,
  formatCount,
  formatNaira,
} from "@/lib/campaign-data";
import { calculateCampaignEstimate } from "@/lib/campaigns/engine";
import { Sparkles, Users, Send, Wallet } from "lucide-react";

interface Props {
  audienceSize: number;
  channels: ChannelId[];
  walletBalance?: number;
}

export function CostEstimator({ audienceSize, channels, walletBalance = 8_400_000 }: Props) {
  const estimate = calculateCampaignEstimate(channels, audienceSize);
  const { breakdown, total, reachPct } = estimate;
  const estReach = estimate.estimatedUniqueReach;
  const walletPct = walletBalance > 0 ? Math.min(100, (total / walletBalance) * 100) : 0;

  return (
    <Card className="sticky top-4">
      <CardHeader className="pb-3">
        <CardTitle className="text-sm flex items-center gap-1.5">
          <Sparkles className="h-3.5 w-3.5 text-primary" /> Live cost estimate
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="grid grid-cols-2 gap-2">
          <Tile icon={Users} label="Audience" value={formatCount(audienceSize)} />
          <Tile
            icon={Send}
            label="Est. reach"
            value={formatCount(estReach)}
            hint={`${reachPct}%`}
          />
        </div>

        <div>
          <div className="flex items-center justify-between text-[11px] text-muted-foreground mb-1.5">
            <span>Channel breakdown</span>
            <span>Per {breakdown.length} channel(s)</span>
          </div>
          <div className="space-y-2">
            {breakdown.length === 0 && (
              <div className="text-xs text-muted-foreground text-center py-3 border border-dashed rounded-md">
                Select a channel to estimate cost
              </div>
            )}
            {breakdown.map((b) => {
              const meta = CHANNELS.find((c) => c.id === b.id)!;
              const Icon = meta.icon;
              return (
                <div key={b.id} className="flex items-center justify-between gap-2 text-xs">
                  <div className="flex items-center gap-2 min-w-0">
                    <span className="h-6 w-6 grid place-items-center rounded-md bg-muted">
                      <Icon className="h-3 w-3" />
                    </span>
                    <div className="min-w-0">
                      <div className="font-medium truncate">{b.name}</div>
                      <div className="text-[10px] text-muted-foreground">
                        {formatCount(b.targetCount)} target · {formatCount(b.billableUnits)} × ₦
                        {b.unitCost.toFixed(2)}/{b.unit}
                      </div>
                    </div>
                  </div>
                  <div className="font-mono text-[11px] font-semibold">{formatNaira(b.cost)}</div>
                </div>
              );
            })}
          </div>
        </div>

        <div className="rounded-lg border bg-gradient-to-br from-primary/5 to-accent/5 p-3">
          <div className="flex items-center justify-between">
            <span className="text-xs text-muted-foreground">Campaign total</span>
            <span className="text-lg font-bold tabular-nums">{formatNaira(total)}</span>
          </div>
          <div className="mt-2 flex items-center gap-1.5 text-[10px] text-muted-foreground">
            <Wallet className="h-3 w-3" />
            Wallet: {formatNaira(walletBalance)} · uses {walletPct.toFixed(1)}%
          </div>
          <div className="mt-1 text-[10px] text-muted-foreground">
            Includes {formatNaira(estimate.platformFee)} platform fee + {formatNaira(estimate.complianceFee)} compliance hold
          </div>
          <Progress value={walletPct} className="mt-1.5 h-1" />
          {total > walletBalance && (
            <Badge variant="destructive" className="mt-2 text-[9px]">
              Insufficient balance — top up wallet
            </Badge>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

function Tile({
  icon: Icon,
  label,
  value,
  hint,
}: {
  icon: typeof Users;
  label: string;
  value: string;
  hint?: string;
}) {
  return (
    <div className="rounded-md border bg-muted/30 p-2">
      <div className="flex items-center gap-1 text-[10px] text-muted-foreground">
        <Icon className="h-3 w-3" /> {label}
      </div>
      <div className="text-base font-semibold tabular-nums leading-tight">{value}</div>
      {hint && <div className="text-[10px] text-muted-foreground">{hint} of base</div>}
    </div>
  );
}
