import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { fetchTmUsers } from '../api';
import DashboardLoading from './DashboardLoading';
import exportCsv from './exportCsv';
const SURVEY_ORIGIN = 'https://tgics.cttr.in';
const EMPTY_TOTALS = { tms: 0, contacts_created: 0, doctors_with_surveys: 0, total_surveys: 0 };
function mrWhatsappLink(row) {
const userId = String(row.user_id || '').trim();
if (!userId) {
return { href: '', label: 'Link unavailable' };
}
let digits = String(row.phone || '').replace(/\D+/g, '');
if (digits.length === 10) {
digits = `91${digits}`;
}
if (!digits) {
return { href: '', label: 'No WhatsApp number' };
}
const name = String(row.name || '').trim();
const link = `${SURVEY_ORIGIN}/${userId}`;
const text = `Dear${name ? ` ${name}` : ''},\n\nPlease share this TGICS link with your enrolled doctors. They should open it and enter their WhatsApp mobile number to continue:\n${link}`;
return {
href: `https://api.whatsapp.com/send?phone=${digits}&text=${encodeURIComponent(text)}`,
label: '',
};
}
export default function TmUsersSection({ onUnauthorized }) {
const [items, setItems] = useState([]);
const [totals, setTotals] = useState(EMPTY_TOTALS);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [query, setQuery] = useState('');
const load = useCallback(async (refresh = false) => {
setLoading(true);
setError('');
try {
const res = await fetchTmUsers(refresh);
setItems(Array.isArray(res.data?.items) ? res.data.items : []);
setTotals({ ...EMPTY_TOTALS, ...(res.data?.totals || {}) });
} catch (err) {
if (err.status === 401) {
onUnauthorized?.();
return;
}
setError(err.message || 'Unable to load Territory Managers.');
} finally {
setLoading(false);
}
}, [onUnauthorized]);
useEffect(() => {
load(false);
}, [load]);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return items;
return items.filter((row) =>
[row.name, row.employee_code, row.position_name, row.position_code]
.some((v) => String(v || '').toLowerCase().includes(q))
);
}, [items, query]);
const handleExport = () => {
exportCsv(
'tgics_mr_dashboard',
['MR ID', 'Name', 'Employee code', 'Position name', 'Doctors Enrolled', 'Active Doctors', 'Total surveys'],
filtered.map((row) => [
row.user_id,
row.name,
row.employee_code,
row.position_name,
row.contacts_created,
row.doctors_with_surveys,
row.total_surveys,
])
);
};
return (
<>
Total MR Count
{loading ? '…' : totals.tms}
Total Doctors Enrolled
{loading ? '…' : totals.contacts_created}
Active Doctors
{loading ? '…' : totals.doctors_with_surveys}
Total Surveys
{loading ? '…' : totals.total_surveys}
{error ? {error}
: null}
{loading ? : null}
{!loading && !error && filtered.length === 0 ? (
No MRs found.
) : null}
{filtered.length > 0 ? (
| No |
Name |
Employee code |
Position name |
Doctors Enrolled |
Active Doctors |
Total surveys |
Doctors |
WhatsApp |
{filtered.map((row, index) => {
const whatsapp = mrWhatsappLink(row);
return (
| {index + 1} |
{row.name || '-'} |
{row.employee_code || '-'} |
{row.position_name || '-'} |
{row.contacts_created} |
{row.doctors_with_surveys} |
{row.total_surveys} |
{row.contacts_created > 0 ? (
View Doctors
) : (
-
)}
|
{whatsapp.href ? (
Send WhatsApp
) : (
{whatsapp.label}
)}
|
);
})}
) : null}
>
);
}