'use client';

import { useEffect, useState, useMemo } from 'react';
import { api } from '@/lib/api';
import { showError } from '@/lib/confirm';
import { formatDateTime } from '@/lib/dates';
import { toast } from 'react-toastify';

export interface NotifyCandidate {
  id: number;
  full_name: string;
  first_name?: string;
  last_name?: string;
  email: string;
  phone_number: string;
  company_name?: string;
  job_title?: string;
  current_location?: string;
}

interface NotifyCandidateModalProps {
  open: boolean;
  onClose: () => void;
  candidates: any[]; // Accepts any candidate object structure
}

export default function NotifyCandidateModal({ open, onClose, candidates }: NotifyCandidateModalProps) {
  // Normalize candidate structure to match what is needed by templates and UI
  const normalizedCandidates = useMemo(() => {
    return candidates.map((c) => {
      const rawName = c.full_name || c.name || 'Candidate';
      const email = c.email || c.candidate_email || '';
      const phone = c.phone_number || c.phone || c.candidate_mobile || '';
      const parts = rawName.trim().split(/\s+/);
      const first_name = c.first_name || parts[0] || '';
      const last_name = c.last_name || parts.slice(1).join(' ') || '';
      return {
        id: c.id ?? c.candidate_id,
        full_name: rawName,
        first_name,
        last_name,
        email,
        phone_number: phone,
        company_name: c.company_name || c.current_company || c.company || '',
        job_title: c.job_title || c.current_role || c.jobTitle || '',
        current_location: c.current_location || c.city || '',
      };
    });
  }, [candidates]);

  const [notifyTab, setNotifyTab] = useState<'send' | 'history'>('send');
  const [notifyChannels, setNotifyChannels] = useState<string[]>(['EMAIL']);
  const [notifySubject, setNotifySubject] = useState('');
  const [notifyCc, setNotifyCc] = useState('');
  const [notifyMessage, setNotifyMessage] = useState('');
  const [notifySending, setNotifySending] = useState(false);
  const [notifyHistory, setNotifyHistory] = useState<any[]>([]);
  const [notifyHistoryLoading, setNotifyHistoryLoading] = useState(false);
  const [notifyTemplates, setNotifyTemplates] = useState<any[]>([]);
  const [notifyWaTemplate, setNotifyWaTemplate] = useState('');
  const [notifySmsContent, setNotifySmsContent] = useState('');
  const [notifyTemplateId, setNotifyTemplateId] = useState('');
  // Raw template body (with {{placeholders}}) of the applied template — kept so
  // we can extract the ORDERED variable values for a multi-variable WhatsApp send.
  const [notifyRawBody, setNotifyRawBody] = useState('');
  // Optional job used to fill {{job_title}} / {{apply_link}} / {{company}}.
  const [jobs, setJobs] = useState<{ id: number; title: string; public_id?: string; short_code?: string; client_name?: string; location?: string }[]>([]);
  const [selectedJobId, setSelectedJobId] = useState('');

  const loadNotifyJobs = async () => {
    try {
      const r = (await api.get('/jobs/?status=Published&page_size=500')) as any;
      const d = r?.data?.results ?? r?.data ?? [];
      setJobs(Array.isArray(d) ? d : []);
    } catch {
      setJobs([]);
    }
  };

  const selectedJob = useMemo(
    () => jobs.find((j) => String(j.id) === String(selectedJobId)) || null,
    [jobs, selectedJobId],
  );

  const loadNotifyTemplates = async () => {
    try {
      const r = (await api.get('/notifications/templates/active/')) as any;
      setNotifyTemplates(r?.data ?? []);
    } catch {
      setNotifyTemplates([]);
    }
  };

  // Per-channel tracked apply URLs for the selected job (from the backend), so
  // the apply link captures the sourcing channel (WhatsApp/Email/SMS/Telegram/
  // LinkedIn) when the candidate applies — same opaque ?t=<token> as LinkedIn.
  const [applyUrls, setApplyUrls] = useState<Record<string, string>>({});

  // Which channel the {{apply_link}} is tagged as when several are ticked.
  const sourceChannel = ['WHATSAPP', 'EMAIL', 'SMS', 'TELEGRAM'].find((ch) => notifyChannels.includes(ch)) || 'EMAIL';

  const buildApplyLink = (job: any): string => {
    if (!job) return '';
    const tracked = applyUrls[sourceChannel];
    if (tracked) return tracked;
    if (typeof window === 'undefined') return '';
    // Fallback: plain short link if tracked URLs haven't loaded yet.
    return `${window.location.origin}/careers/jobs/${job.short_code || job.public_id || job.id}`;
  };

  // Resolve a single {{placeholder}} to its value from candidate + (optional) job.
  const varValue = (key: string, c: any, job: any): string => {
    switch (key.toLowerCase()) {
      case 'first_name': return c?.first_name || '';
      case 'last_name': return c?.last_name || '';
      case 'name': return c?.full_name || '';
      case 'job_title': return job?.title || c?.job_title || '';
      case 'company': return job?.client_name || c?.company_name || 'Indovision';
      case 'location': return job?.location || c?.current_location || '';
      case 'apply_link': return buildApplyLink(job);
      default: return '';
    }
  };

  const fillTemplate = (text: string, c: any, job: any = null): string =>
    (text || '').replace(/\{\{\s*(\w+)\s*\}\}/g, (_m, k) => varValue(k, c, job));

  // Does the applied template need a job (job_title / apply_link / company)?
  const templateNeedsJob = /\{\{\s*(job_title|apply_link|company)\s*\}\}/i.test(notifyRawBody);

  const applyNotifyTemplate = (tplId: string) => {
    const t = notifyTemplates.find((x) => String(x.id) === String(tplId));
    if (!t) return;
    setNotifyChannels([t.channel]);
    setNotifyRawBody(t.body || '');
    const previewCand = normalizedCandidates[0] || {};
    const job = jobs.find((j) => String(j.id) === String(selectedJobId)) || null;
    if (t.channel === 'EMAIL') setNotifySubject(fillTemplate(t.subject, previewCand, job));
    setNotifyMessage(fillTemplate(t.body, previewCand, job));
    setNotifyWaTemplate(t.channel === 'WHATSAPP' ? (t.provider_template_name || '') : '');
    setNotifySmsContent(t.channel === 'SMS' ? (t.provider_template_name || '') : '');
  };

  // Fetch per-channel tracked apply URLs for the chosen job.
  useEffect(() => {
    if (!selectedJobId) { setApplyUrls({}); return; }
    let cancelled = false;
    (async () => {
      try {
        const r = (await api.get(`/jobs/${selectedJobId}/apply-urls/`)) as any;
        if (!cancelled) setApplyUrls(r?.data ?? {});
      } catch { if (!cancelled) setApplyUrls({}); }
    })();
    return () => { cancelled = true; };
  }, [selectedJobId]);

  // Re-fill the preview message/subject when job, tracked URLs, or source
  // channel changes (so {{apply_link}} reflects the right tracked link).
  useEffect(() => {
    if (!notifyTemplateId) return;
    const t = notifyTemplates.find((x) => String(x.id) === String(notifyTemplateId));
    if (!t) return;
    const previewCand = normalizedCandidates[0] || {};
    if (t.channel === 'EMAIL') setNotifySubject(fillTemplate(t.subject, previewCand, selectedJob));
    setNotifyMessage(fillTemplate(t.body, previewCand, selectedJob));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedJobId, applyUrls, sourceChannel]);

  const loadNotifyHistory = async () => {
    if (normalizedCandidates.length === 0) return;
    setNotifyHistoryLoading(true);
    try {
      if (normalizedCandidates.length === 1) {
        const r = (await api.get(`/candidates/${normalizedCandidates[0].id}/notifications/`)) as any;
        const candidateName = normalizedCandidates[0].full_name;
        const data = (r?.data ?? []).map((item: any) => ({ ...item, candidate_name: candidateName }));
        setNotifyHistory(data);
      } else {
        const results = await Promise.all(
          normalizedCandidates.map(async (c) => {
            try {
              const r = (await api.get(`/candidates/${c.id}/notifications/`)) as any;
              return (r?.data ?? []).map((item: any) => ({ ...item, candidate_name: c.full_name }));
            } catch {
              return [];
            }
          })
        );
        const merged = results.flat();
        merged.sort((a: any, b: any) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
        setNotifyHistory(merged);
      }
    } catch {
      setNotifyHistory([]);
    } finally {
      setNotifyHistoryLoading(false);
    }
  };

  useEffect(() => {
    if (open && normalizedCandidates.length > 0) {
      setNotifyTab('send');
      setNotifyChannels(['EMAIL']);
      setNotifySubject('');
      setNotifyCc('');
      setNotifyMessage('');
      setNotifyHistory([]);
      setNotifyTemplateId('');
      setNotifyRawBody('');
      setSelectedJobId('');
      setApplyUrls({});
      loadNotifyTemplates();
      loadNotifyJobs();
    }
  }, [open, normalizedCandidates]);

  const handleSendNotification = async () => {
    if (!normalizedCandidates.length) return;
    if (!notifyChannels.length) {
      showError('Select at least one channel (Email / WhatsApp / SMS).', 'Nothing selected');
      return;
    }
    if (!notifyMessage.trim()) {
      showError('Please write a message.', 'Message required');
      return;
    }
    if (notifyChannels.includes('EMAIL') && !notifySubject.trim()) {
      showError('Subject is required for email.', 'Subject required');
      return;
    }
    if (templateNeedsJob && !selectedJob) {
      showError('This template references a job — please select a job to fill the title & apply link.', 'Select a job');
      return;
    }

    setNotifySending(true);
    try {
      const promises = normalizedCandidates.map(async (c) => {
        const subject = fillTemplate(notifySubject, c, selectedJob);
        const message = fillTemplate(notifyMessage, c, selectedJob);
        return api.post(`/candidates/${c.id}/notify/`, {
          channels: notifyChannels,
          subject: subject.trim(),
          message: message.trim(),
          cc: notifyCc.split(/[,;]/).map((x) => x.trim()).filter(Boolean),
          wa_template: notifyWaTemplate,
          sms_content_id: notifySmsContent,
        });
      });
      const results = await Promise.all(promises);
      let sentCount = 0;
      let failedCount = 0;
      results.forEach((r: any) => {
        const d = r?.data || {};
        sentCount += d.sent ?? 0;
        failedCount += d.failed ?? 0;
      });
      if (failedCount > 0) {
        toast.warn(`${sentCount} notification(s) sent, ${failedCount} failed.`);
      } else {
        toast.success(`Notifications sent successfully!`);
      }
      setNotifyTab('history');
      loadNotifyHistory();
    } catch (err: any) {
      showError(err?.message || 'Could not send notification.', 'Send failed');
    } finally {
      setNotifySending(false);
    }
  };

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
      <div
        className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm"
        onClick={() => !notifySending && onClose()}
      />
      <div className="relative z-10 w-full max-w-3xl bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none shadow-2xl p-6 max-h-[88vh] flex flex-col text-slate-800 dark:text-slate-100">
        <div className="flex items-center justify-between mb-3 shrink-0">
          <div className="w-full pr-8">
            <h3 className="text-lg font-bold text-slate-900 dark:text-white">Notify Candidate</h3>
            {normalizedCandidates.length > 1 ? (
              <div className="mt-2">
                <h4 className="text-xs font-bold text-slate-500 dark:text-slate-400">Selected Candidates ({normalizedCandidates.length})</h4>
                <div className="max-h-24 overflow-y-auto mt-1 border border-slate-200 dark:border-slate-800 p-2 space-y-1 bg-slate-50 dark:bg-slate-950/40 rounded-none custom-scrollbar">
                  {normalizedCandidates.map((c) => (
                    <p key={c.id} className="text-xs text-slate-600 dark:text-slate-400">
                      <span className="font-bold text-slate-850 dark:text-white">{c.full_name}</span> · {c.email || 'no email'} · {c.phone_number || 'no phone'}
                    </p>
                  ))}
                </div>
              </div>
            ) : normalizedCandidates.length === 1 ? (
              <p className="text-xs text-slate-400 mt-0.5">
                {normalizedCandidates[0].full_name} · {normalizedCandidates[0].email || 'no email'} · {normalizedCandidates[0].phone_number || 'no phone'}
              </p>
            ) : null}
          </div>
          <button
            onClick={() => !notifySending && onClose()}
            className="w-8 h-8 rounded-none flex items-center justify-center text-slate-400 hover:text-slate-700 hover:bg-slate-100 dark:hover:bg-slate-800 transition cursor-pointer"
          >
            <i className="fa-solid fa-xmark"></i>
          </button>
        </div>

        {/* Tabs */}
        <div className="flex gap-1.5 border-b border-slate-100 dark:border-slate-800 pb-3 mb-4 shrink-0">
          {([
            ['send', 'Compose Message', 'fa-pen-to-square'],
            ['history', 'Sent / Failed History', 'fa-clock-rotate-left'],
          ] as const).map(([id, label, icon]) => (
            <button
              key={id}
              type="button"
              onClick={() => {
                setNotifyTab(id);
                if (id === 'history') loadNotifyHistory();
              }}
              className={`flex items-center gap-2 px-4 py-2 rounded-none text-xs font-bold transition cursor-pointer ${
                notifyTab === id
                  ? 'bg-[#405189] text-white shadow-md'
                  : 'bg-slate-50 hover:bg-slate-100 dark:bg-slate-950 dark:hover:bg-slate-800 text-slate-600 dark:text-slate-400'
              }`}
            >
              <i className={`fa-solid ${icon}`}></i> {label}
            </button>
          ))}
        </div>

        <div className="overflow-y-auto flex-1 min-h-0 custom-scrollbar">
          {notifyTab === 'send' ? (
            <div className="space-y-4">
              {/* Template picker */}
              {notifyTemplates.length > 0 && (
                <div>
                  <label className="block text-[11px] font-bold uppercase tracking-wide text-slate-500 mb-1">
                    Use a saved template
                  </label>
                  <select
                    value={notifyTemplateId}
                    onChange={(e) => {
                      setNotifyTemplateId(e.target.value);
                      applyNotifyTemplate(e.target.value);
                    }}
                    className="w-full px-3 py-2.5 text-sm border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 rounded-none focus:outline-none focus:border-[#405189] text-slate-850 dark:text-white"
                  >
                    <option value="">— Select a template —</option>
                    {notifyTemplates.map((t) => (
                      <option key={t.id} value={t.id}>
                        [{t.channel_label}] {t.name}
                      </option>
                    ))}
                  </select>
                  <p className="text-[10px] text-slate-400 mt-1">
                    Fills the channel, subject &amp; message with the candidate&apos;s details.
                  </p>
                </div>
              )}

              {/* Job selector — needed to fill {{job_title}} / {{apply_link}} */}
              {templateNeedsJob && (
                <div>
                  <label className="block text-[11px] font-bold uppercase tracking-wide text-slate-500 mb-1">
                    Job for this alert <span className="text-rose-500">*</span>
                  </label>
                  <select
                    value={selectedJobId}
                    onChange={(e) => setSelectedJobId(e.target.value)}
                    className="w-full px-3 py-2.5 text-sm border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 rounded-none focus:outline-none focus:border-[#405189] text-slate-850 dark:text-white"
                  >
                    <option value="">— Select a job —</option>
                    {jobs.map((j) => (
                      <option key={j.id} value={j.id}>
                        {j.title}{j.client_name ? ` · ${j.client_name}` : ''}{j.location ? ` · ${j.location}` : ''}
                      </option>
                    ))}
                  </select>
                  <p className="text-[10px] text-slate-400 mt-1">
                    Fills the job title &amp; apply link in the message.
                  </p>
                </div>
              )}

              {/* Channel selection */}
              <div className="grid grid-cols-3 gap-3">
                {([
                  ['EMAIL', 'Email', 'fa-envelope'],
                  ['WHATSAPP', 'WhatsApp', 'fa-brands fa-whatsapp'],
                  ['SMS', 'Mobile SMS', 'fa-comment-sms'],
                ] as const).map(([ch, label, icon]) => {
                  const checked = notifyChannels.includes(ch);
                  return (
                    <div
                      key={ch}
                      onClick={() => setNotifyChannels((prev) => (checked ? prev.filter((x) => x !== ch) : [...prev, ch]))}
                      className={`rounded-none border p-3 text-left transition cursor-pointer select-none ${
                        checked ? 'border-[#0ab39c] bg-[#0ab39c]/5' : 'border-slate-200 dark:border-slate-800 hover:border-slate-300'
                      }`}
                    >
                      <div className="flex items-center gap-2">
                        <input
                          type="checkbox"
                          readOnly
                          checked={checked}
                          className="accent-[#0ab39c] cursor-pointer"
                        />
                        <i
                          className={`${
                            String(icon).startsWith('fa-brands') ? icon : `fa-solid ${icon}`
                          } ${checked ? 'text-[#0ab39c]' : 'text-slate-400'}`}
                        ></i>
                        <span className="text-xs font-extrabold text-slate-700 dark:text-slate-200">{label}</span>
                      </div>
                      {normalizedCandidates.length > 1 ? (
                        <ul
                          className="list-disc list-inside mt-1.5 pl-1.5 max-h-16 overflow-y-auto text-[10px] text-slate-450 dark:text-slate-450 space-y-0.5 custom-scrollbar"
                          onClick={(e) => e.stopPropagation()}
                        >
                          {normalizedCandidates.map((c) => {
                            const val = ch === 'EMAIL' ? c.email : c.phone_number;
                            return (
                              <li key={c.id} className="truncate text-slate-500 dark:text-slate-400" title={val || `No ${ch === 'EMAIL' ? 'email' : 'phone'}`}>
                                {val || `No ${ch === 'EMAIL' ? 'email' : 'phone'}`}
                              </li>
                            );
                          })}
                        </ul>
                      ) : (
                        <p className="text-[10px] text-slate-400 mt-1 truncate">
                          {normalizedCandidates[0]
                            ? (ch === 'EMAIL' ? normalizedCandidates[0].email : normalizedCandidates[0].phone_number) ||
                              `No ${ch === 'EMAIL' ? 'email' : 'phone'} on profile`
                            : ''}
                        </p>
                      )}
                    </div>
                  );
                })}
              </div>

              {notifyChannels.includes('EMAIL') && (
                <>
                  <div>
                    <label className="block text-[10px] uppercase font-bold text-slate-450 dark:text-slate-400 mb-1">
                      Email Subject
                    </label>
                    <input
                      value={notifySubject}
                      onChange={(e) => setNotifySubject(e.target.value)}
                      placeholder="e.g. Interview scheduled — TA-ATS"
                      className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-2.5 text-xs focus:outline-none text-slate-800 dark:text-white"
                    />
                  </div>
                  <div>
                    <label className="block text-[10px] uppercase font-bold text-slate-450 dark:text-slate-400 mb-1">
                      CC{' '}
                      <span className="normal-case font-semibold">
                        — copy other people (comma-separated emails, optional)
                      </span>
                    </label>
                    <input
                      value={notifyCc}
                      onChange={(e) => setNotifyCc(e.target.value)}
                      placeholder="e.g. manager@company.com, hr@company.com"
                      className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-2.5 text-xs focus:outline-none text-slate-800 dark:text-white"
                    />
                  </div>
                </>
              )}

              <div>
                <label className="block text-[10px] uppercase font-bold text-slate-450 dark:text-slate-400 mb-1">
                  Message
                </label>
                <textarea
                  value={notifyMessage}
                  onChange={(e) => setNotifyMessage(e.target.value)}
                  rows={6}
                  placeholder={
                    normalizedCandidates[0]
                      ? `Hi ${normalizedCandidates[0].first_name || ''}, ...`
                      : 'Hi, ...'
                  }
                  className="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-2.5 text-xs focus:outline-none text-slate-800 dark:text-white font-sans"
                />
                <p className="text-[10px] text-slate-400 mt-1">
                  The same message is used for Email, WhatsApp &amp; SMS.
                </p>
              </div>

              {/* Tracked apply URL preview — captures the sourcing channel on apply */}
              {selectedJob && applyUrls[sourceChannel] && (
                <div className="border border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-950/40 rounded-none p-3">
                  <p className="text-[10px] uppercase font-bold text-slate-400 mb-1">
                    <i className="fa-solid fa-link mr-1 text-[#405189]"></i>
                    Apply link (tracked as {sourceChannel})
                  </p>
                  <div className="flex items-center gap-2">
                    <code className="flex-1 min-w-0 truncate text-[11px] text-[#405189] dark:text-indigo-300">{applyUrls[sourceChannel]}</code>
                    <button
                      type="button"
                      onClick={() => { navigator.clipboard?.writeText(applyUrls[sourceChannel]); toast.success('Apply link copied'); }}
                      className="shrink-0 text-[10px] font-bold text-slate-500 hover:text-[#405189] border border-slate-200 dark:border-slate-700 px-2 py-1 rounded-none"
                    >
                      <i className="fa-regular fa-copy mr-1"></i>Copy
                    </button>
                  </div>
                  <p className="text-[10px] text-slate-400 mt-1">
                    When the candidate applies through this link, their source is recorded as <b>{sourceChannel}</b>.
                  </p>
                </div>
              )}

              <div className="flex justify-end gap-3 pt-3 pb-1 sticky bottom-0 bg-white dark:bg-slate-900 border-t border-slate-100 dark:border-slate-800 -mx-1 px-1">
                <button
                  type="button"
                  onClick={onClose}
                  className="bg-slate-50 dark:bg-slate-950 hover:bg-slate-100 dark:hover:bg-slate-800 border border-slate-200 dark:border-slate-800 rounded-none px-5 py-2.5 text-xs font-semibold transition cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="button"
                  disabled={notifySending || !notifyChannels.length}
                  onClick={handleSendNotification}
                  className="bg-[#405189] hover:bg-[#364574] disabled:opacity-50 text-white rounded-none px-6 py-2.5 text-xs font-extrabold shadow-md transition cursor-pointer"
                >
                  {notifySending ? (
                    <>
                      <i className="fa-solid fa-spinner fa-spin mr-1.5"></i>Sending…
                    </>
                  ) : (
                    <>
                      <i className="fa-solid fa-paper-plane mr-1.5"></i>Send Notification
                    </>
                  )}
                </button>
              </div>
            </div>
          ) : (
            <div>
              {notifyHistoryLoading ? (
                <p className="text-xs text-slate-400 py-8 text-center">
                  <i className="fa-solid fa-spinner fa-spin mr-2"></i>Loading history…
                </p>
              ) : notifyHistory.length === 0 ? (
                <p className="text-xs text-slate-400 py-8 text-center">
                  No notifications sent to {normalizedCandidates.length > 1 ? 'these candidates' : 'this candidate'} yet.
                </p>
              ) : (
                <div className="border border-slate-200 dark:border-slate-800 rounded-none overflow-hidden">
                  <table className="w-full text-xs">
                    <thead className="bg-slate-50 dark:bg-slate-950/40 text-slate-400 text-left text-[10px] uppercase">
                      <tr>
                        <th className="px-3 py-2 font-semibold">S.No.</th>
                        {normalizedCandidates.length > 1 && <th className="px-3 py-2 font-semibold">Candidate</th>}
                        <th className="px-3 py-2 font-semibold">Channel</th>
                        <th className="px-3 py-2 font-semibold">Status</th>
                        <th className="px-3 py-2 font-semibold">Subject / Message</th>
                        <th className="px-3 py-2 font-semibold">Date</th>
                      </tr>
                    </thead>
                    <tbody>
                      {notifyHistory.map((n, idx) => (
                        <tr key={n.id} className="border-t border-slate-100 dark:border-slate-800 align-top">
                          <td className="px-3 py-2 text-slate-400 font-semibold">{idx + 1}</td>
                          {normalizedCandidates.length > 1 && (
                            <td className="px-3 py-2 font-bold text-slate-700 dark:text-slate-200 whitespace-nowrap">
                              {n.candidate_name}
                            </td>
                          )}
                          <td className="px-3 py-2 whitespace-nowrap font-bold text-slate-700 dark:text-slate-200">
                            <i
                              className={`mr-1.5 ${
                                n.channel === 'WHATSAPP'
                                  ? 'fa-brands fa-whatsapp text-[#0ab39c]'
                                  : n.channel === 'SMS'
                                  ? 'fa-solid fa-comment-sms text-[#f7b84b]'
                                  : 'fa-solid fa-envelope text-[#405189]'
                              }`}
                            ></i>
                            {n.channel === 'WHATSAPP' ? 'WhatsApp' : n.channel === 'SMS' ? 'SMS' : 'Email'}
                          </td>
                          <td className="px-3 py-2">
                            <span
                              className={`inline-flex px-2 py-0.5 rounded-none text-[10px] font-bold whitespace-nowrap ${
                                n.status === 'SENT'
                                  ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300'
                                  : 'bg-rose-50 text-rose-700 dark:bg-rose-950/40 dark:text-rose-300'
                              }`}
                            >
                              {n.status === 'SENT' ? '✓ Sent' : '✕ Failed'}
                            </span>
                          </td>
                          <td className="px-3 py-2">
                            {n.subject && <p className="font-bold text-slate-650 dark:text-slate-350">{n.subject}</p>}
                            <p className="text-slate-500 dark:text-slate-400 line-clamp-2">{n.message}</p>
                            {n.error && (
                              <p className="text-rose-500 mt-0.5">
                                <i className="fa-solid fa-circle-exclamation mr-1"></i>
                                {n.error}
                              </p>
                            )}
                          </td>
                          <td className="px-3 py-2 text-slate-400 whitespace-nowrap">
                            {formatDateTime(n.created_at)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
