'use client';

import React from 'react';
import { FiEye, FiEdit2, FiUserPlus, FiTrash2 } from 'react-icons/fi';
import type { Lead } from '@/lib/api/types/leads.types';
import {
  STATUS_CONFIG,
  PRIORITY_CONFIG,
  CLIENT_GROUP_CONFIG,
  formatUserName,
  initialsOf,
  formatDateWithHint,
  timeAgo,
} from '@/lib/api/mappers/leads.mappers';

interface Props {
  row: Lead;
  onOpen: (row: Lead) => void;
  onEdit: (row: Lead) => void;
  onAssign: (row: Lead) => void;
  onDelete: (row: Lead) => void;
  isSelected?: boolean;
  onToggleSelect?: (row: Lead) => void;
  /** Permitted action keys for this user on the leads module. */
  permittedActions: Set<string>;
  /** Flashes the row when a live notification touches it. */
  isHighlighted?: boolean;
}

const td: React.CSSProperties = {
  padding: '10px',
  fontSize: 13,
  color: '#374151',
  verticalAlign: 'middle',
};

function Badge({
  label,
  bg,
  fg,
  border,
  title,
}: {
  label: string;
  bg: string;
  fg: string;
  border: string;
  title?: string;
}) {
  return (
    <span
      title={title}
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        padding: '3px 9px',
        borderRadius: 99,
        background: bg,
        color: fg,
        border: `1px solid ${border}`,
        fontSize: 11,
        fontWeight: 600,
        whiteSpace: 'nowrap',
      }}
    >
      {label}
    </span>
  );
}

export default function LeadRow({
  row,
  onOpen,
  onEdit,
  onAssign,
  onDelete,
  isSelected = false,
  onToggleSelect,
  permittedActions,
  isHighlighted = false,
}: Props) {
  const status = STATUS_CONFIG[row.status];
  const priority = PRIORITY_CONFIG[row.priority];
  const group = row.client_group ? CLIENT_GROUP_CONFIG[row.client_group] : null;
  const created = formatDateWithHint(row.created_at);
  const handedOver = timeAgo(row.assigned_at);

  const iconBtn = (
    key: string,
    title: string,
    color: string,
    icon: React.ReactNode,
    action: () => void,
  ) => {
    if (!permittedActions.has(key)) return null;
    return (
      <button
        key={key}
        title={title}
        aria-label={title}
        onClick={(e) => {
          e.stopPropagation();
          action();
        }}
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          width: 28,
          height: 28,
          borderRadius: 6,
          border: `1px solid ${color}33`,
          background: `${color}15`,
          color,
          cursor: 'pointer',
        }}
      >
        {icon}
      </button>
    );
  };

  return (
    <tr
      onClick={() => onOpen(row)}
      style={{
        cursor: 'pointer',
        borderBottom: '1px solid #f1f5f9',
        background: isHighlighted
          ? '#f0fdfa'
          : isSelected
            ? '#f8fafc'
            : undefined,
        transition: 'background 0.4s',
      }}
    >
      {onToggleSelect && (
        <td style={td} onClick={(e) => e.stopPropagation()}>
          <input
            type="checkbox"
            aria-label={`Select ${row.lead_code}`}
            checked={isSelected}
            onChange={() => onToggleSelect(row)}
            style={{ cursor: 'pointer' }}
          />
        </td>
      )}

      {/* Lead code */}
      <td style={{ ...td, fontWeight: 700, color: '#0f766e' }}>
        {row.lead_code}
      </td>

      {/* Company + contact */}
      <td style={td}>
        <div style={{ fontWeight: 600, color: '#111827' }}>{row.company}</div>
        {row.contact && (
          <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>
            {row.contact}
          </div>
        )}
      </td>

      {/* 🆕 Client group. QRS_B renders in the QRS palette with a small
          superscript, because the business treats it as QRS but the record
          itself still says otherwise — hiding that would make the data look
          edited. */}
      <td style={td}>
        {group ? (
          <Badge
            label={group.label}
            bg={group.bg}
            fg={group.fg}
            border={group.border}
            title={
              row.client_group === 'QRS_B'
                ? 'Stored as QRS_B (legacy) — counted and filtered as QRS'
                : group.label
            }
          />
        ) : (
          <span style={{ color: '#9ca3af', fontSize: 12 }}>—</span>
        )}
      </td>

      {/* Contact details */}
      <td style={td}>
        {row.email && (
          <div style={{ fontSize: 12, color: '#374151' }}>{row.email}</div>
        )}
        {row.phone && (
          <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>
            {row.phone}
          </div>
        )}
        {!row.email && !row.phone && (
          <span style={{ color: '#9ca3af', fontSize: 12 }}>—</span>
        )}
      </td>

      {/* Owner */}
      <td style={td}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
          <span
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: 26,
              height: 26,
              borderRadius: 99,
              background: '#0f766e',
              color: '#fff',
              fontSize: 10,
              fontWeight: 700,
              flexShrink: 0,
            }}
          >
            {initialsOf(row.assignedUser)}
          </span>
          <div style={{ minWidth: 0 }}>
            <div
              style={{
                fontSize: 12,
                fontWeight: 600,
                color: '#111827',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
              }}
            >
              {formatUserName(row.assignedUser)}
            </div>
            {handedOver && row.assignedByUser && (
              <div style={{ fontSize: 10, color: '#6b7280' }}>
                by {formatUserName(row.assignedByUser)} · {handedOver}
              </div>
            )}
          </div>
        </div>
      </td>

      {/* Priority */}
      <td style={td}>
        <Badge
          label={priority.label}
          bg={priority.bg}
          fg={priority.fg}
          border={priority.border}
        />
      </td>

      {/* Status */}
      <td style={td}>
        <Badge
          label={`${status.icon} ${status.label}`}
          bg={status.bg}
          fg={status.fg}
          border={status.border}
          title={
            row.status === 'Lost' && row.lost_reason
              ? `Lost: ${row.lost_reason}`
              : undefined
          }
        />
      </td>

      {/* Created */}
      <td style={td}>
        <div style={{ fontSize: 12 }}>{created.main}</div>
        {created.hint && (
          <div style={{ fontSize: 10, color: '#6b7280' }}>{created.hint}</div>
        )}
      </td>

      {/* Actions */}
      <td style={td} onClick={(e) => e.stopPropagation()}>
        <div style={{ display: 'flex', gap: 6 }}>
          {iconBtn('view', 'Open lead', '#0f766e', <FiEye size={14} />, () =>
            onOpen(row),
          )}
          {iconBtn('update', 'Edit lead', '#2563eb', <FiEdit2 size={14} />, () =>
            onEdit(row),
          )}
          {iconBtn(
            'assign',
            'Assign to someone',
            '#7c3aed',
            <FiUserPlus size={14} />,
            () => onAssign(row),
          )}
          {iconBtn('delete', 'Delete lead', '#dc2626', <FiTrash2 size={14} />, () =>
            onDelete(row),
          )}
        </div>
      </td>
    </tr>
  );
}
