'use client';

/**
 * Sales Performance — Deal heat section (between leaderboard + tables).
 *
 * Three things in one section:
 *   1. Hot deals count (KPI tile)
 *   2. Heat distribution mini-chart (3-segment horizontal bar)
 *   3. Hottest deals right now (top 5 table)
 *
 * Pulls from /api/v1/reports/sales `dealHeat`. Heat semantics defined
 * in the service (sales.service.ts § getDealHeat).
 */

import Link from 'next/link';
import type { Route } from 'next';
import { Flame } from 'lucide-react';

import { Card } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { STAGE_LABELS, type PipelineStage } from '@/lib/constants';
import { useUIStore } from '@/stores/ui-store';
import { formatMoneyCompact as formatMoney } from '@/lib/reports/format-currency';

type HeatBucket = 'hot' | 'warm' | 'cold';

interface DealHeatSummary {
  distribution: Record<HeatBucket, number>;
  topDeals: Array<{
    id: string;
    clientName: string;
    mooringNumber: string | null;
    stage: PipelineStage;
    bucket: HeatBucket;
    daysSinceLastContact: number | null;
    pipelineValue: number;
    pipelineValueCurrency: string;
  }>;
}

interface Props {
  data: DealHeatSummary;
}

const HEAT_LABEL: Record<HeatBucket, string> = { hot: 'Hot', warm: 'Warm', cold: 'Cold' };
const HEAT_COLOR: Record<HeatBucket, string> = {
  hot: 'bg-rose-500',
  warm: 'bg-amber-400',
  cold: 'bg-slate-400',
};
const HEAT_BADGE: Record<HeatBucket, string> = {
  hot: 'bg-rose-100 text-rose-800',
  warm: 'bg-amber-100 text-amber-800',
  cold: 'bg-slate-100 text-slate-700',
};

export function SalesDealHeat({ data }: Props) {
  const portSlug = useUIStore((s) => s.currentPortSlug) ?? '';
  const total = data.distribution.hot + data.distribution.warm + data.distribution.cold;

  return (
    <div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
      {/* Hot deals tile + distribution bar (lg col-span 1) */}
      <Card className="p-4 lg:col-span-1 space-y-3">
        <div className="flex items-center justify-between">
          <p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
            Hot deals right now
          </p>
          <Flame className="h-4 w-4 text-rose-500" aria-hidden />
        </div>
        <div className="flex items-baseline gap-1.5">
          <p className="text-2xl font-semibold tracking-tight text-foreground tabular-nums">
            {data.distribution.hot}
          </p>
          <p className="text-xs text-muted-foreground">
            of {total} active {total === 1 ? 'deal' : 'deals'}
          </p>
        </div>

        {/* Distribution bar */}
        {total > 0 ? (
          <div className="space-y-2 pt-2">
            <div className="relative h-2.5 rounded-full bg-muted/40 overflow-hidden flex">
              {(['hot', 'warm', 'cold'] as HeatBucket[]).map((bucket) => {
                const count = data.distribution[bucket];
                if (count === 0) return null;
                const pct = (count / total) * 100;
                return (
                  <div
                    key={bucket}
                    className={cn(HEAT_COLOR[bucket], 'h-full')}
                    style={{ width: `${pct}%` }}
                    title={`${HEAT_LABEL[bucket]}: ${count}`}
                    aria-hidden
                  />
                );
              })}
            </div>
            <div className="flex justify-between text-[11px] text-muted-foreground">
              {(['hot', 'warm', 'cold'] as HeatBucket[]).map((bucket) => (
                <span key={bucket} className="inline-flex items-center gap-1">
                  <span className={cn('h-1.5 w-1.5 rounded-sm', HEAT_COLOR[bucket])} aria-hidden />
                  {HEAT_LABEL[bucket]} {data.distribution[bucket]}
                </span>
              ))}
            </div>
          </div>
        ) : null}
      </Card>

      {/* Hottest 5 deals (lg col-span 2) */}
      <Card className="p-4 lg:col-span-2 space-y-3">
        <p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
          Hottest deals right now
        </p>
        {data.topDeals.length === 0 ? (
          <p className="text-sm text-muted-foreground py-4 text-center">No active deals yet.</p>
        ) : (
          <ul className="divide-y divide-border">
            {data.topDeals.map((deal) => (
              <li key={deal.id} className="py-2 flex items-center gap-3">
                <Link
                  href={`/${portSlug}/interests/${deal.id}` as Route}
                  className="text-sm font-medium text-foreground hover:text-primary transition-colors flex-1 truncate"
                >
                  {deal.clientName}
                  {deal.mooringNumber ? (
                    <span className="text-muted-foreground font-normal">
                      {' '}
                      · {deal.mooringNumber}
                    </span>
                  ) : null}
                </Link>
                <span
                  className={cn(
                    'text-[10px] uppercase tracking-wider font-semibold rounded px-1.5 py-0.5',
                    HEAT_BADGE[deal.bucket],
                  )}
                >
                  {HEAT_LABEL[deal.bucket]}
                </span>
                <span className="text-xs text-muted-foreground">{STAGE_LABELS[deal.stage]}</span>
                <span className="text-xs text-muted-foreground tabular-nums w-24 text-right">
                  {deal.pipelineValue > 0
                    ? formatMoney(deal.pipelineValue, deal.pipelineValueCurrency)
                    : '—'}
                </span>
                <span className="text-xs text-muted-foreground tabular-nums w-20 text-right hidden sm:inline">
                  {deal.daysSinceLastContact === null
                    ? 'never contacted'
                    : `${deal.daysSinceLastContact}d ago`}
                </span>
              </li>
            ))}
          </ul>
        )}
      </Card>
    </div>
  );
}
