// Reusable admin UI building blocks for MyMarian.

const ADMIN_TONES = {
  success: { fg: '#166534', bg: '#dcfce7', border: '#bbf7d0' },
  warning: { fg: '#92400e', bg: '#fef3c7', border: '#fde68a' },
  danger: { fg: '#991b1b', bg: '#fee2e2', border: '#fecaca' },
  info: { fg: '#1d4ed8', bg: '#dbeafe', border: '#bfdbfe' },
  neutral: { fg: '#374151', bg: '#f3f4f6', border: '#e5e7eb' },
  dark: { fg: '#fff', bg: BRAND.dark, border: BRAND.dark },
};

function AdminToneForStatus(status) {
  const normalized = String(status || '').toLowerCase();
  if (['paid', 'synced', 'active', 'success'].includes(normalized)) return 'success';
  if (['pending', 'retrying', 'waiting_payment', 'needs_review', 'warning'].includes(normalized)) return 'warning';
  if (['failed', 'blocked', 'inactive', 'danger'].includes(normalized)) return 'danger';
  if (['staff', 'support_admin', 'super_admin'].includes(normalized)) return 'info';
  return 'neutral';
}

function AdminMoney(value) {
  return `${Number(value || 0).toLocaleString()} ETB`;
}

function AdminCard({ children, style = {}, ...props }) {
  return (
    <div style={{
      background: '#fff',
      border: `1px solid ${BRAND.border}`,
      borderRadius: 8,
      boxShadow: '0 1px 3px rgba(15,23,42,0.05)',
      ...style,
    }} {...props}>
      {children}
    </div>
  );
}

function AdminStatusBadge({ status, tone }) {
  const selectedTone = tone || AdminToneForStatus(status);
  const palette = ADMIN_TONES[selectedTone] || ADMIN_TONES.neutral;
  const label = String(status || 'unknown').replace(/_/g, ' ');
  return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      height: 24,
      padding: '0 9px',
      borderRadius: 99,
      border: `1px solid ${palette.border}`,
      background: palette.bg,
      color: palette.fg,
      fontSize: 11,
      fontWeight: 800,
      textTransform: 'capitalize',
      whiteSpace: 'nowrap',
    }}>
      {label}
    </span>
  );
}

function AdminMetricCard({ label, value, detail, tone = 'neutral', trend }) {
  const palette = ADMIN_TONES[tone] || ADMIN_TONES.neutral;
  return (
    <AdminCard style={{ padding: 18, minHeight: 128 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'flex-start' }}>
        <div>
          <div style={{ color: BRAND.muted, fontSize: 12, fontWeight: 800, textTransform: 'uppercase', letterSpacing: 0.5 }}>
            {label}
          </div>
          <div style={{ marginTop: 8, color: BRAND.dark, fontSize: 28, fontWeight: 900, lineHeight: 1 }}>
            {value}
          </div>
        </div>
        <div style={{
          width: 34,
          height: 34,
          borderRadius: 8,
          border: `1px solid ${palette.border}`,
          background: palette.bg,
          color: palette.fg,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 14,
          fontWeight: 900,
        }}>
          {trend || '+'}
        </div>
      </div>
      <div style={{ marginTop: 14, color: BRAND.muted, fontSize: 12, lineHeight: 1.45 }}>{detail}</div>
    </AdminCard>
  );
}

function AdminSectionHeader({ title, subtitle, action }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap', marginBottom: 14 }}>
      <div>
        <h2 style={{ margin: 0, color: BRAND.dark, fontSize: 18, fontWeight: 900 }}>{title}</h2>
        {subtitle && <p style={{ margin: '5px 0 0', color: BRAND.muted, fontSize: 13, lineHeight: 1.5 }}>{subtitle}</p>}
      </div>
      {action}
    </div>
  );
}

function AdminTabButton({ active, label, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        height: 36,
        padding: '0 13px',
        borderRadius: 7,
        border: `1px solid ${active ? BRAND.primary : BRAND.border}`,
        background: active ? BRAND.primary : '#fff',
        color: active ? '#fff' : BRAND.dark,
        fontFamily: 'inherit',
        fontSize: 12,
        fontWeight: 800,
        cursor: 'pointer',
        whiteSpace: 'nowrap',
      }}
    >
      {label}
    </button>
  );
}

function AdminInput({ value, onChange, placeholder, type = 'text', style = {}, ...props }) {
  return (
    <input
      type={type}
      value={value}
      onChange={(event) => onChange(event.target.value)}
      placeholder={placeholder}
      {...props}
      style={{
        height: 38,
        minWidth: 220,
        border: `1px solid ${BRAND.border}`,
        borderRadius: 7,
        padding: '0 12px',
        fontSize: 13,
        color: BRAND.dark,
        outline: 'none',
        background: '#fff',
        ...style,
      }}
    />
  );
}

function AdminSelect({ value, onChange, options }) {
  return (
    <select
      value={value}
      onChange={(event) => onChange(event.target.value)}
      style={{
        height: 38,
        border: `1px solid ${BRAND.border}`,
        borderRadius: 7,
        padding: '0 10px',
        fontSize: 13,
        fontWeight: 700,
        color: BRAND.dark,
        outline: 'none',
        background: '#fff',
      }}
    >
      {options.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
    </select>
  );
}

function AdminActionButton({ children, onClick, variant = 'primary', disabled = false }) {
  const styles = {
    primary: { background: BRAND.primary, color: '#fff', border: BRAND.primary },
    ghost: { background: '#fff', color: BRAND.dark, border: BRAND.border },
    danger: { background: '#fff', color: '#991b1b', border: '#fecaca' },
  };
  const selected = styles[variant] || styles.primary;
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      style={{
        height: 36,
        padding: '0 12px',
        borderRadius: 7,
        border: `1px solid ${selected.border}`,
        background: selected.background,
        color: selected.color,
        fontFamily: 'inherit',
        fontSize: 12,
        fontWeight: 800,
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.65 : 1,
        whiteSpace: 'nowrap',
      }}
    >
      {children}
    </button>
  );
}

function AdminBar({ label, value, max, color = BRAND.primary, rightLabel }) {
  const width = max ? Math.max(4, Math.min(100, (Number(value || 0) / max) * 100)) : 0;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr 54px', alignItems: 'center', gap: 10 }}>
      <div style={{ color: BRAND.dark, fontSize: 12, fontWeight: 800, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</div>
      <div style={{ height: 9, background: '#edf1ed', borderRadius: 99, overflow: 'hidden' }}>
        <div style={{ width: `${width}%`, height: '100%', background: color, borderRadius: 99 }} />
      </div>
      <div style={{ color: BRAND.muted, fontSize: 11, fontWeight: 800, textAlign: 'right' }}>{rightLabel || value}</div>
    </div>
  );
}

function AdminTable({ columns, rows, emptyText = 'No records found.' }) {
  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 760 }}>
        <thead>
          <tr>
            {columns.map(column => (
              <th key={column.key} style={{
                padding: '11px 14px',
                borderBottom: `1px solid ${BRAND.border}`,
                color: BRAND.muted,
                fontSize: 11,
                fontWeight: 900,
                textAlign: column.align || 'left',
                textTransform: 'uppercase',
                letterSpacing: 0.5,
                background: '#fbfcfb',
              }}>
                {column.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.length === 0 && (
            <tr>
              <td colSpan={columns.length} style={{ padding: 24, color: BRAND.muted, fontSize: 13, textAlign: 'center' }}>
                {emptyText}
              </td>
            </tr>
          )}
          {rows.map((row, rowIndex) => (
            <tr key={row.id || row.courseId || rowIndex}>
              {columns.map(column => (
                <td key={column.key} style={{
                  padding: '13px 14px',
                  borderBottom: `1px solid ${BRAND.border}`,
                  color: BRAND.dark,
                  fontSize: 13,
                  textAlign: column.align || 'left',
                  verticalAlign: 'middle',
                  background: '#fff',
                }}>
                  {column.render ? column.render(row) : row[column.key]}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminUserCell({ user }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 220 }}>
      <Avatar name={user.name} size={34} bg={user.role === 'student' ? BRAND.primary : '#1d4ed8'} />
      <div style={{ minWidth: 0 }}>
        <div style={{ color: BRAND.dark, fontSize: 13, fontWeight: 900 }}>{user.name}</div>
        <div style={{ color: BRAND.muted, fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.email}</div>
      </div>
    </div>
  );
}

function AdminMiniChart({ series }) {
  const [hoveredBar, setHoveredBar] = React.useState('');
  const maxValue = Math.max(...series.map(item => item.users), 1);
  const roundedMax = maxValue <= 10 ? maxValue : Math.ceil(maxValue / 5) * 5;
  const ticks = [...new Set([roundedMax, Math.round(roundedMax / 2), 0])];
  const chartBar = (key, value, color, label) => (
    <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', height: '100%' }}>
      <div
        onMouseEnter={() => setHoveredBar(key)}
        onMouseLeave={() => setHoveredBar('')}
        title={`${label}: ${value}`}
        style={{
          width: '100%',
          height: `${Math.max(6, (value / roundedMax) * 100)}%`,
          background: color,
          borderRadius: '5px 5px 0 0',
          position: 'relative',
          cursor: 'default',
        }}
      >
        {hoveredBar === key && (
          <span style={{
            position: 'absolute',
            left: '50%',
            bottom: 'calc(100% + 6px)',
            transform: 'translateX(-50%)',
            background: BRAND.dark,
            color: '#fff',
            borderRadius: 6,
            padding: '3px 7px',
            fontSize: 10,
            fontWeight: 900,
            whiteSpace: 'nowrap',
            boxShadow: '0 8px 18px rgba(15,23,42,0.18)',
          }}>
            {value}
          </span>
        )}
      </div>
    </div>
  );

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '38px minmax(0, 1fr)', gap: 10, height: 196 }}>
      <div style={{ height: 156, paddingTop: 8, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        {ticks.map(tick => (
          <span key={tick} style={{ color: BRAND.muted, fontSize: 11, fontWeight: 900, textAlign: 'right' }}>{tick}</span>
        ))}
      </div>

      <div style={{ position: 'relative', height: 196, minWidth: 0 }}>
        <div style={{ position: 'absolute', top: 8, left: 0, right: 0, height: 156, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
          {ticks.map(tick => (
            <div key={tick} style={{ height: 1, background: tick === 0 ? BRAND.border : '#e8eee8' }} />
          ))}
        </div>

        <div style={{ position: 'relative', zIndex: 1, display: 'flex', alignItems: 'flex-end', gap: 8, height: 196 }}>
          {series.map(item => (
            <div key={item.label} style={{ flex: 1, minWidth: 34, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
              <div style={{ width: '100%', height: 156, display: 'flex', alignItems: 'flex-end', gap: 3 }}>
                {chartBar(`${item.label}-users`, item.users, BRAND.primary, 'Users')}
                {chartBar(`${item.label}-paid`, item.paid, BRAND.gold, 'Paid')}
              </div>
              <span style={{ color: BRAND.muted, fontSize: 11, fontWeight: 800 }}>{item.label}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
