'use client';

import React from 'react';
import { STAGE_META, computeDealPulse, dealsApi, notifyDealsChanged, type DealStage, type DealStats } from '../../lib/deals';
import { inr, inrFull } from '../../lib/leads';
import { notifyAccountsChanged } from '../../lib/accounts';
import { useCrmOptions } from '../../lib/options';
import { useConfirmDeleteRecord } from '../crm/useConfirmDeleteRecord';
import { StatusBadge } from '../platform/PlatformPrimitives';

export function DealStageBadge({ stage }: { stage: DealStage }) {
  const meta = STAGE_META[stage] ?? {
    label: stage,
    tone: 'gray' as const,
  };
  return <StatusBadge label={meta.label} tone={meta.tone} dot />;
}

export function DealPulse({ stage, daysInStage, big = false, short = false }: { stage: DealStage; daysInStage: number; big?: boolean; short?: boolean }) {
  const { dealStages } = useCrmOptions();
  const openStages = dealStages.filter((s) => s.isOpen).map((s) => s.value);
  const pulse = computeDealPulse(stage, daysInStage, openStages, short);
  return (
    <div className={`tcx-pulse tcx-pulse-${pulse.status} ${big ? 'tcx-pulse-big' : ''}`}>
      <div className="tcx-pulse-bar" aria-hidden="true">
        {[0, 1, 2, 3, 4].map((idx) => (
          <i key={idx} className={idx < pulse.litBars ? 'on' : ''} />
        ))}
      </div>
      <span className="tcx-pulse-lbl">{pulse.label}</span>
    </div>
  );
}

/** 4-column KPI strip shared across Deals list and Pipeline Kanban views. */
export function DealStatsStrip({ stats }: { stats: DealStats | null }) {
  const openPipeline = stats?.openPipeline ?? 0;
  const openCount = stats?.openCount ?? 0;
  const wonValue = stats?.wonValue ?? 0;
  const averageDealSize = stats?.averageDealSize ?? 0;

  return (
    <div className="tcx-surface-card tcx-stats-strip">
      <div className="tcx-stat">
        <span>Open deals value</span>
        <b title={inrFull(openPipeline)}>{inr(openPipeline)}</b>
      </div>
      <div className="tcx-stat">
        <span>Active deals</span>
        <b>{openCount}</b>
      </div>
      <div className="tcx-stat">
        <span>Won revenue</span>
        <b title={inrFull(wonValue)}>{inr(wonValue)}</b>
      </div>
      <div className="tcx-stat">
        <span>Avg. deal size</span>
        <b title={inrFull(averageDealSize)}>{inr(averageDealSize)}</b>
      </div>
    </div>
  );
}

export function useDeleteDeal(onDeleted?: () => void) {
  return useConfirmDeleteRecord<{ id: string; title: string }>({
    title: (d) => `Delete "${d.title}"?`,
    content: () => 'This removes the deal, its stage history, and its notes from your workspace. Deals linked to converted leads cannot be deleted.',
    successMessage: 'Deal deleted',
    fallbackError: 'The deal could not be deleted.',
    onDelete: async (d) => {
      await dealsApi.remove(d.id);
      notifyDealsChanged();
      notifyAccountsChanged();
    },
    onDeleted: () => onDeleted?.(),
  });
}
