'use client';

import React from 'react';
import Link from 'next/link';
import { STAGE_META, type Deal, type DealDetail, type DealStage, type DealStageHistoryEntry } from '../../lib/deals';
import { inrFull } from '../../lib/leads';
import { useCrmOptions } from '../../lib/options';
import { fmtDate, relTime } from '../platform/platformFormat';
import { DealStageBadge } from './DealBits';

function dealRows(deal: Deal | DealDetail, onNavigate?: () => void): Array<[string, React.ReactNode]> {
  const leads = 'convertedLeads' in deal && deal.convertedLeads.length > 0 ? deal.convertedLeads : [];

  return [
    [
      'Deal ID',
      <span key="num" className="font-mono">
        {deal.dealNumber}
      </span>,
    ],
    [
      'Customer',
      <Link key="acc" href={`/app/customers/${deal.account.id}`} onClick={() => onNavigate?.()} className="font-medium text-[var(--tcx-primary)] hover:underline">
        {deal.account.name}
      </Link>,
    ],
    [
      'Primary contact',
      deal.contact ? (
        <span key="con" className="font-medium text-[var(--tcx-text)]">
          {deal.contact.name}
        </span>
      ) : (
        '—'
      ),
    ],
    ['Deal value', inrFull(deal.amount)],
    ['Estimated effort', deal.estimatedHours !== null ? `${deal.estimatedHours} hrs` : '—'],
    ['Expected close', deal.closeDate ? fmtDate(deal.closeDate) : '—'],
    ['Owner', deal.owner?.name ?? 'Unassigned'],
    ...(leads.length > 0
      ? [
          [
            'Converted from',
            <span key="leads" className="inline-flex flex-wrap gap-2">
              {leads.map((l) => (
                <Link key={l.id} href={`/app/leads/${l.id}`} onClick={() => onNavigate?.()} className="font-medium text-[var(--tcx-primary)] hover:underline">
                  {l.name}
                </Link>
              ))}
            </span>,
          ] as [string, React.ReactNode],
        ]
      : []),
  ];
}

export function DealDetailsGrid({ deal }: { deal: DealDetail }) {
  return (
    <dl className="m-0 grid grid-cols-1 gap-x-6 gap-y-3 sm:grid-cols-2">
      {dealRows(deal).map(([label, value]) => (
        <div key={label} className="min-w-0">
          <dt className="text-[12px] text-[var(--tcx-muted)]">{label}</dt>
          <dd className="m-0 mt-0.5 truncate text-[13.5px] font-medium text-[var(--tcx-text)]">{value}</dd>
        </div>
      ))}
    </dl>
  );
}

export function DealDetailsList({ deal, onNavigate }: { deal: DealDetail; onNavigate?: () => void }) {
  return (
    <dl className="m-0 divide-y divide-[var(--tcx-border)]">
      {dealRows(deal, onNavigate).map(([label, value]) => (
        <div key={label} className="flex items-start justify-between gap-3 py-2 text-[13px] first:pt-0 last:pb-0">
          <dt className="shrink-0 text-[var(--tcx-muted)]">{label}</dt>
          <dd className="m-0 min-w-0 truncate text-right font-medium text-[var(--tcx-text)]">{value}</dd>
        </div>
      ))}
    </dl>
  );
}

export function DealStageBar({ currentStage, busy = false, onSelectStage }: { currentStage: DealStage; busy?: boolean; onSelectStage: (stage: DealStage) => void }) {
  const { dealStages } = useCrmOptions();
  const stages = dealStages.map((s) => s.value);
  const openStages = dealStages.filter((s) => s.isOpen).map((s) => s.value);
  const openIdx = openStages.indexOf(currentStage);

  return (
    <div className="tcx-stages" role="group" aria-label="Deal stages">
      {stages.map((stage, idx) => {
        const isCurrent = stage === currentStage;
        const isDone = !isCurrent && ((currentStage === 'CLOSED_WON' && idx < openStages.length) || (openIdx >= 0 && idx < openIdx));

        let stateClass = '';
        if (isCurrent) {
          stateClass = stage === 'CLOSED_LOST' ? 'cur-lost' : 'cur';
        } else if (isDone) {
          stateClass = 'done';
        }

        return (
          <button key={stage} type="button" disabled={busy || isCurrent} onClick={() => onSelectStage(stage)} className={`tcx-stage-btn ${stateClass}`} aria-pressed={isCurrent}>
            {STAGE_META[stage].label}
          </button>
        );
      })}
    </div>
  );
}

export function DealLossBanner({ deal }: { deal: Deal }) {
  if (deal.stage !== 'CLOSED_LOST') return null;

  return (
    <div className="rounded-[12px] border border-[var(--tcx-error)]/30 bg-[var(--tcx-soft-red)] px-4 py-3 text-[13px]">
      <div className="font-semibold text-[var(--tcx-error)]">
        Deal closed as lost
        {deal.lossReason ? ` · ${deal.lossReason}` : ''}
      </div>
      {deal.competitor ? (
        <div className="mt-1 text-[var(--tcx-text-2)]">
          Competitor: <span className="font-medium">{deal.competitor}</span>
        </div>
      ) : null}
      {deal.lostNotes ? <div className="mt-1 text-[var(--tcx-text-2)]">{deal.lostNotes}</div> : null}
    </div>
  );
}

export function DealStageHistoryList({ history }: { history: DealStageHistoryEntry[] }) {
  if (history.length === 0) {
    return <p className="m-0 text-[13px] text-[var(--tcx-muted)]">No stage changes recorded yet.</p>;
  }

  return (
    <div className="divide-y divide-[var(--tcx-border)]">
      {history.map((item) => (
        <div key={item.id} className="py-2.5 first:pt-0 last:pb-0">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div className="flex flex-wrap items-center gap-1.5 text-[12.5px]">
              {item.fromStage ? (
                <>
                  <DealStageBadge stage={item.fromStage} />
                  <span className="text-[var(--tcx-muted)]">to</span>
                </>
              ) : (
                <span className="text-[var(--tcx-muted)]">Created at</span>
              )}
              <DealStageBadge stage={item.toStage} />
            </div>
            <span className="text-[12px] text-[var(--tcx-muted)]">
              {item.changedBy ? `${item.changedBy.name} · ` : ''}
              {relTime(item.createdAt)}
            </span>
          </div>
          {item.note ? <div className="mt-1 text-[12.5px] text-[var(--tcx-text-2)]">{item.note}</div> : null}
        </div>
      ))}
    </div>
  );
}
