'use client';

import React from 'react';
import { CLIENT_GROUP_CONFIG } from '@/lib/api/mappers/leads.mappers';
import type { LeadAnalytics } from '@/lib/api/types/leads.types';

interface Props {
  analytics: LeadAnalytics | null;
  loading?: boolean;
}

/**
 * Totals across the whole pipeline, not the current page and not narrowed
 * by the table filters — same choice as MyAuditsAnalyticsInline. An active
 * "Lost" filter should never make the "Converted" number read zero.
 */
export default function LeadsAnalyticsInline({ analytics, loading }: Props) {
  const kpis = analytics
    ? [
        { label: 'Total leads', value: analytics.total, accent: '#0f766e', tint: '#f0fdfa' },
        { label: 'New this month', value: analytics.new_month, accent: '#1d4ed8', tint: '#eff6ff' },
        { label: 'Converted', value: analytics.converted, accent: '#15803d', tint: '#f0fdf4' },
        { label: 'Lost', value: analytics.lost, accent: '#b91c1c', tint: '#fef2f2' },
      ]
    : [];

  const groups = analytics?.by_client_group ?? {};
  const groupTotal = Object.values(groups).reduce((a, b) => a + b, 0);
  const groupKeys = ['QRS', 'TQS', 'QRS_NEW', 'unassigned'].filter(
    (k) => (groups[k] ?? 0) > 0,
  );

  const conversionRate =
    analytics && analytics.total > 0
      ? Math.round((analytics.converted / analytics.total) * 100)
      : 0;

  return (
    <div
      style={{
        marginBottom: 20,
        padding: 16,
        backgroundColor: '#f0fdfa',
        borderRadius: 12,
        border: '1px solid #99f6e4',
      }}
    >
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 8,
          marginBottom: 16,
          flexWrap: 'wrap',
        }}
      >
        <span style={{ fontSize: 16 }}>📊</span>
        <h2
          style={{ margin: 0, fontSize: 14, fontWeight: 700, color: '#0f766e' }}
        >
          Lead Analytics
        </h2>
        <span
          style={{
            padding: '2px 10px',
            borderRadius: 99,
            fontSize: 11,
            fontWeight: 600,
            backgroundColor: '#fff',
            color: '#0f766e',
            border: '1px solid #99f6e4',
          }}
        >
          All leads
        </span>
        {analytics && (
          <span style={{ marginLeft: 'auto', fontSize: 12, color: '#6b7280' }}>
            {conversionRate}% conversion rate
          </span>
        )}
      </div>

      {loading || !analytics ? (
        <div style={{ padding: 24, textAlign: 'center', color: '#6b7280', fontSize: 13 }}>
          Loading numbers…
        </div>
      ) : (
        <>
          {/* KPI strip */}
          <div
            style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
              gap: 12,
              marginBottom: 16,
            }}
          >
            {kpis.map((k) => (
              <div
                key={k.label}
                style={{
                  padding: '14px 16px',
                  background: '#fff',
                  border: '1px solid #e2e8f0',
                  borderRadius: 10,
                  borderLeft: `3px solid ${k.accent}`,
                }}
              >
                <div
                  style={{
                    fontSize: 24,
                    fontWeight: 800,
                    color: k.accent,
                    lineHeight: 1.1,
                  }}
                >
                  {k.value.toLocaleString()}
                </div>
                <div
                  style={{
                    fontSize: 11,
                    fontWeight: 600,
                    color: '#64748b',
                    textTransform: 'uppercase',
                    letterSpacing: '0.04em',
                    marginTop: 4,
                  }}
                >
                  {k.label}
                </div>
              </div>
            ))}
          </div>

          {/* Client group split */}
          <div
            style={{
              padding: 14,
              background: '#fff',
              border: '1px solid #e2e8f0',
              borderRadius: 10,
            }}
          >
            <div
              style={{
                fontSize: 11,
                fontWeight: 700,
                color: '#64748b',
                textTransform: 'uppercase',
                letterSpacing: '0.05em',
                marginBottom: 10,
              }}
            >
              By client group
              <span
                style={{
                  marginLeft: 6,
                  fontWeight: 500,
                  textTransform: 'none',
                  letterSpacing: 0,
                  color: '#94a3b8',
                }}
              >
                — legacy QRS_B records counted under QRS
              </span>
            </div>

            {groupKeys.length === 0 ? (
              <div style={{ fontSize: 13, color: '#9ca3af' }}>
                No leads carry a client group yet.
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                {groupKeys.map((key) => {
                  const count = groups[key] ?? 0;
                  const pct = groupTotal ? Math.round((count / groupTotal) * 100) : 0;
                  const cfg =
                    key === 'unassigned'
                      ? {
                          label: 'Not set',
                          bg: '#f8fafc',
                          fg: '#64748b',
                          border: '#e2e8f0',
                        }
                      : CLIENT_GROUP_CONFIG[key as 'QRS' | 'TQS' | 'QRS_NEW'];

                  return (
                    <div
                      key={key}
                      style={{ display: 'flex', alignItems: 'center', gap: 10 }}
                    >
                      <span
                        style={{
                          minWidth: 78,
                          display: 'inline-flex',
                          justifyContent: 'center',
                          padding: '3px 9px',
                          borderRadius: 99,
                          background: cfg.bg,
                          color: cfg.fg,
                          border: `1px solid ${cfg.border}`,
                          fontSize: 11,
                          fontWeight: 700,
                        }}
                      >
                        {cfg.label}
                      </span>

                      <div
                        style={{
                          flex: 1,
                          height: 8,
                          borderRadius: 99,
                          background: '#f1f5f9',
                          overflow: 'hidden',
                        }}
                      >
                        <div
                          style={{
                            width: `${pct}%`,
                            height: '100%',
                            background: cfg.fg,
                            borderRadius: 99,
                            transition: 'width 0.3s',
                          }}
                        />
                      </div>

                      <span
                        style={{
                          minWidth: 78,
                          textAlign: 'right',
                          fontSize: 12,
                          color: '#475569',
                          fontWeight: 600,
                        }}
                      >
                        {count.toLocaleString()} · {pct}%
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}
