import React, {useState, useEffect, useRef} from "react";
import { useNavigate } from "react-router-dom";
import { AuthService, MessageService, CustomerService } from "../../services";
import { Breadcrumb, Tabs, Tab, Modal, Button, Dropdown } from "react-bootstrap";
import { PencilSquare, Plus, Trash, Send, Eye, ArrowLeft, Filter, Calendar3, Search, ChevronLeft, ChevronRight } from "react-bootstrap-icons";
import Select from 'react-select';
import { MultiSelectDropdown } from '../../shared';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';

const MessageList = () => {
  const navigate = useNavigate();
  const [messages, setMessages] = useState([]);
  const [activeTab, setActiveTab] = useState('allMessages');

  // Custom template state
  const [customTemplates, setCustomTemplates] = useState([]);
  const [showCreateTemplateModal, setShowCreateTemplateModal] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState(null);
  const [templateTitle, setTemplateTitle] = useState('');
  const [templateChinese, setTemplateChinese] = useState('');
  const [templateEnglish, setTemplateEnglish] = useState('');

  // Send message state
  const [showSendModal, setShowSendModal] = useState(false);
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [eligibleCustomers, setEligibleCustomers] = useState([]);
  const [selectedRecipients, setSelectedRecipients] = useState([]);
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [sendTitle, setSendTitle] = useState('');
  const [sendChinese, setSendChinese] = useState('');
  const [sendEnglish, setSendEnglish] = useState('');

  // Preview state
  const [placeholders, setPlaceholders] = useState([]);
  const [placeholderValues, setPlaceholderValues] = useState({});
  const [sending, setSending] = useState(false);

  // Search, Filter, Date state for All Sent Messages
  const [searchText, setSearchText] = useState('');
  const [filterLanguage, setFilterLanguage] = useState('');
  const [showFilterDropdown, setShowFilterDropdown] = useState(false);
  const [filterDate, setFilterDate] = useState(null);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const datePickerRef = useRef(null);

  // Pagination state
  const [sentPage, setSentPage] = useState(1);
  const [sentPageSize, setSentPageSize] = useState(10);
  const [templatePage, setTemplatePage] = useState(1);
  const [templatePageSize, setTemplatePageSize] = useState(10);

  useEffect(() => {
    if (!AuthService.canAddOrEditRoutes() && !AuthService.canViewRoutes() &&!AuthService.canAccessLegacySystem()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change a dispatcher or admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
    fetchMessages();
    fetchCustomTemplates();
    CustomerService.getAllActiveCustomers().then(data => {
      const all = data?.data || [];
      setEligibleCustomers(all.filter(c => c.text_msg_enabled === true));
    });
  }, []);

  // Close date picker on outside click
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (datePickerRef.current && !datePickerRef.current.contains(e.target)) {
        setShowDatePicker(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const fetchMessages = () => {
    MessageService.getMessages().then(data => {
      setMessages(data?.data || []);
    });
  };

  const fetchCustomTemplates = () => {
    MessageService.getCustomTemplates().then(data => {
      setCustomTemplates(data?.data || []);
    });
  };

  // ---- Custom Template CRUD ----
  const openCreateTemplateModal = () => {
    setEditingTemplate(null);
    setTemplateTitle('');
    setTemplateChinese('');
    setTemplateEnglish('');
    setShowCreateTemplateModal(true);
  };

  const openEditTemplateModal = (template) => {
    setEditingTemplate(template);
    setTemplateTitle(template.title || '');
    setTemplateChinese(template.chinese || '');
    setTemplateEnglish(template.english || '');
    setShowCreateTemplateModal(true);
  };

  const closeTemplateModal = () => {
    setShowCreateTemplateModal(false);
    setEditingTemplate(null);
    setTemplateTitle('');
    setTemplateChinese('');
    setTemplateEnglish('');
  };

  const handleSaveTemplate = () => {
    if (!templateTitle.trim()) { window.alert('Template Title is required.'); return; }
    if (!templateChinese.trim()) { window.alert('Message Content (Chinese) is required.'); return; }
    if (!templateEnglish.trim()) { window.alert('Message Content (English) is required.'); return; }
    const userName = localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name;
    const data = { title: templateTitle.trim(), chinese: templateChinese.trim(), english: templateEnglish.trim() };
    if (editingTemplate) {
      data.edit_by = userName;
      data.edit_date = new Date();
      MessageService.updateCustomTemplate(editingTemplate.id, data).then(() => { fetchCustomTemplates(); closeTemplateModal(); });
    } else {
      data.create_by = userName;
      data.create_date = new Date();
      MessageService.createCustomTemplate(data).then(() => { fetchCustomTemplates(); closeTemplateModal(); });
    }
  };

  const handleDeleteTemplate = (id) => {
    if (window.confirm('Are you sure you want to delete this template?')) {
      MessageService.deleteCustomTemplate(id).then(() => { fetchCustomTemplates(); });
    }
  };

  // ---- Send New Message ----
  const openSendModal = () => {
    setSelectedRecipients([]);
    setSelectedTemplate(null);
    setSendTitle('');
    setSendChinese('');
    setSendEnglish('');
    setShowSendModal(true);
  };

  const closeSendModal = () => {
    setShowSendModal(false);
    setSelectedRecipients([]);
    setSelectedTemplate(null);
    setSendTitle('');
    setSendChinese('');
    setSendEnglish('');
  };

  const handleTemplateSelect = (option) => {
    setSelectedTemplate(option);
    if (option && option.value) {
      const tmpl = customTemplates.find(t => t.id === option.value);
      if (tmpl) {
        setSendTitle(tmpl.title || '');
        setSendChinese(tmpl.chinese || '');
        setSendEnglish(tmpl.english || '');
      }
    }
  };

  const handleSelectAll = () => {
    if (selectedRecipients.length === eligibleCustomers.length) {
      setSelectedRecipients([]);
    } else {
      setSelectedRecipients(eligibleCustomers.map(c => ({ value: c.id, label: c.name })));
    }
  };

  const extractPlaceholders = (chinese, english) => {
    const regex = /\{([^}]+)\}/g;
    const set = new Set();
    let match;
    while ((match = regex.exec(chinese)) !== null) set.add(match[1]);
    while ((match = regex.exec(english)) !== null) set.add(match[1]);
    return Array.from(set);
  };

  const openPreview = () => {
    if (!selectedRecipients.length) { window.alert('Please select at least one recipient.'); return; }
    if (!sendChinese.trim() && !sendEnglish.trim()) { window.alert('Please enter message content.'); return; }
    const phs = extractPlaceholders(sendChinese, sendEnglish);
    setPlaceholders(phs);
    const initValues = {};
    phs.forEach(p => { initValues[p] = ''; });
    setPlaceholderValues(initValues);
    setShowSendModal(false);
    setShowPreviewModal(true);
  };

  const backToEditing = () => {
    setShowPreviewModal(false);
    setShowSendModal(true);
  };

  const replacePlaceholders = (text) => {
    if (!text) return '';
    let result = text;
    Object.entries(placeholderValues).forEach(([key, val]) => {
      if (val) {
        result = result.replace(new RegExp(`\\{${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\}`, 'g'), val);
      }
    });
    return result;
  };

  const handleSendNow = async () => {
    setSending(true);
    const userName = localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name;
    const now = new Date();
    const entries = selectedRecipients.map(recipient => {
      const customer = eligibleCustomers.find(c => c.id === recipient.value);
      const lang = customer?.preferred_text_language === 'chinese' ? 'chinese' : 'english';
      const rawContent = lang === 'chinese' ? sendChinese : sendEnglish;
      const finalContent = replacePlaceholders(rawContent);
      return {
        title: sendTitle,
        language: lang,
        sent_date: now,
        message: finalContent,
        recipient_name: recipient.label,
        recipient_id: recipient.value,
        create_by: userName,
        create_date: now
      };
    });
    try {
      await MessageService.bulkCreateMessages({ entries });
      setShowPreviewModal(false);
      closeSendModal();
      fetchMessages();
      window.alert('Messages sent successfully!');
    } catch (err) {
      window.alert('Failed to send messages. Please try again.');
    }
    setSending(false);
  };

  const previewChinese = replacePlaceholders(sendChinese);
  const previewEnglish = replacePlaceholders(sendEnglish);

  // ---- Filtering & Search for Sent Messages ----
  const allSentMessages = messages.filter(m => m.title || m.sent_date);

  const filteredSentMessages = allSentMessages.filter(msg => {
    // Search filter
    if (searchText.trim()) {
      const q = searchText.toLowerCase();
      const name = (msg?.recipient_name || msg?.message_name || '').toLowerCase();
      const title = (msg?.title || msg?.message_title || '').toLowerCase();
      const content = (msg?.message || msg?.message_body || '').toLowerCase();
      if (!name.includes(q) && !title.includes(q) && !content.includes(q)) return false;
    }
    // Language filter
    if (filterLanguage) {
      if ((msg?.language || '').toLowerCase() !== filterLanguage.toLowerCase()) return false;
    }
    // Date filter
    if (filterDate) {
      if (!msg?.sent_date) return false;
      const msgDate = moment(msg.sent_date).format('MM/DD/YYYY');
      const selectedDateStr = moment(filterDate).format('MM/DD/YYYY');
      if (msgDate !== selectedDateStr) return false;
    }
    return true;
  });

  // ---- Pagination helpers ----
  const paginate = (items, page, pageSize) => {
    const start = (page - 1) * pageSize;
    return items.slice(start, start + pageSize);
  };

  const totalSentPages = Math.ceil(filteredSentMessages.length / sentPageSize) || 1;
  const paginatedSent = paginate(filteredSentMessages, sentPage, sentPageSize);

  const totalTemplatePages = Math.ceil(customTemplates.length / templatePageSize) || 1;
  const paginatedTemplates = paginate(customTemplates, templatePage, templatePageSize);

  // Reset to page 1 when filters change
  useEffect(() => { setSentPage(1); }, [searchText, filterLanguage, filterDate]);

  const renderPagination = (currentPage, totalPages, setPage, totalItems, pageSize) => {
    if (totalItems === 0) return null;
    const startItem = (currentPage - 1) * pageSize + 1;
    const endItem = Math.min(currentPage * pageSize, totalItems);

    const maxButtons = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxButtons / 2));
    let endPage = Math.min(totalPages, startPage + maxButtons - 1);
    if (endPage - startPage + 1 < maxButtons) {
      startPage = Math.max(1, endPage - maxButtons + 1);
    }
    const pageNumbers = [];
    for (let i = startPage; i <= endPage; i++) pageNumbers.push(i);

    return (
      <div className="d-flex align-items-center justify-content-between mt-3" style={{ fontSize: '13px' }}>
        <div className="d-flex align-items-center" style={{ gap: '8px' }}>
          <span>Showing</span>
          <select
            className="form-select form-select-sm"
            style={{ width: '70px' }}
            value={pageSize}
            onChange={(e) => {
              const newSize = parseInt(e.target.value);
              if (setPage === setSentPage) { setSentPageSize(newSize); setSentPage(1); }
              else { setTemplatePageSize(newSize); setTemplatePage(1); }
            }}
          >
            <option value={10}>10</option>
            <option value={25}>25</option>
            <option value={50}>50</option>
          </select>
        </div>
        <span className="text-muted">Showing {startItem} to {endItem} out of {totalItems} records</span>
        <div className="d-flex align-items-center" style={{ gap: '4px' }}>
          <button className="btn btn-outline-secondary btn-sm" disabled={currentPage === 1} onClick={() => setPage(currentPage - 1)}>
            <ChevronLeft size={14} />
          </button>
          {pageNumbers.map(num => (
            <button
              key={num}
              className={`btn btn-sm ${num === currentPage ? 'btn-primary' : 'btn-outline-secondary'}`}
              onClick={() => setPage(num)}
              style={{ minWidth: '32px' }}
            >
              {num}
            </button>
          ))}
          <button className="btn btn-outline-secondary btn-sm" disabled={currentPage === totalPages} onClick={() => setPage(currentPage + 1)}>
            <ChevronRight size={14} />
          </button>
        </div>
      </div>
    );
  };

  // Get unique languages for the filter dropdown
  const availableLanguages = [...new Set(allSentMessages.map(m => m?.language).filter(Boolean))];

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/">General</Breadcrumb.Item>
          <Breadcrumb.Item active>Messaging</Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>Message</h4>
        </div>
      </div>
      <div className="app-main-content-list-container">
        <div className="app-main-content-list-func-container">
          <Tabs activeKey={activeTab} onSelect={(k) => setActiveTab(k)} id="messages-tab">
            <Tab eventKey="allMessages" title="All Sent Messages">
              <table className="personnel-info-table" style={{ marginTop: '16px' }}>
                <thead>
                  <tr>
                    <th className="th-index">No.</th>
                    <th>Recipient Name</th>
                    <th>Message Title</th>
                    <th>Message Language</th>
                    <th>Sent Date</th>
                    <th>Message Content</th>
                  </tr>
                </thead>
                <tbody>
                  {paginatedSent.map((msg, index) => (
                    <tr key={msg.id}>
                      <td className="td-index">{(sentPage - 1) * sentPageSize + index + 1}</td>
                      <td>{msg?.recipient_name || msg?.message_name || ''}</td>
                      <td>{msg?.title || msg?.message_title || ''}</td>
                      <td>{msg?.language || ''}</td>
                      <td>{msg?.sent_date ? moment(msg.sent_date).format('MM/DD/YYYY') : ''}</td>
                      <td style={{ maxWidth: '400px', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{msg?.message || msg?.message_body || ''}</td>
                    </tr>
                  ))}
                  {filteredSentMessages.length === 0 && (
                    <tr><td colSpan="6" style={{ textAlign: 'center', color: '#999', padding: '24px' }}>No sent messages found.</td></tr>
                  )}
                </tbody>
              </table>
              {renderPagination(sentPage, totalSentPages, setSentPage, filteredSentMessages.length, sentPageSize)}
            </Tab>
            <Tab eventKey="messageTemplate" title="Message Template">
              <table className="personnel-info-table" style={{ marginTop: '16px' }}>
                <thead>
                  <tr>
                    <th className="th-index">No.</th>
                    <th>Template Title</th>
                    <th>Message Content (Chinese)</th>
                    <th>Message Content (English)</th>
                    <th style={{ width: '80px' }}>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {paginatedTemplates.map((template, index) => (
                    <tr key={template.id}>
                      <td className="td-index">{(templatePage - 1) * templatePageSize + index + 1}</td>
                      <td>{template?.title}</td>
                      <td style={{ maxWidth: '300px', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{template?.chinese}</td>
                      <td style={{ maxWidth: '300px', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{template?.english}</td>
                      <td>
                        <PencilSquare size={16} className="clickable me-2" onClick={() => openEditTemplateModal(template)} />
                        <Trash size={16} className="clickable" color="#dc3545" onClick={() => handleDeleteTemplate(template.id)} />
                      </td>
                    </tr>
                  ))}
                  {customTemplates.length === 0 && (
                    <tr><td colSpan="5" style={{ textAlign: 'center', color: '#999', padding: '24px' }}>No templates yet. Create one to get started.</td></tr>
                  )}
                </tbody>
              </table>
              {renderPagination(templatePage, totalTemplatePages, setTemplatePage, customTemplates.length, templatePageSize)}
            </Tab>
          </Tabs>
          <div className="list-func-panel" style={{ gap: '8px', alignItems: 'center' }}>
            {activeTab === 'allMessages' && (
              <>
                <div className="d-flex align-items-center" style={{ position: 'relative' }}>
                  <Search size={12} style={{ position: 'absolute', left: '10px', color: '#999' }} />
                  <input
                    type="text"
                    className="form-control"
                    placeholder="Search"
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    style={{ paddingLeft: '30px', width: '180px', borderRadius: '6px', height: '31px', fontSize: '13px' }}
                  />
                </div>
                <Dropdown show={showFilterDropdown} onToggle={(isOpen) => { setShowFilterDropdown(isOpen); if (isOpen) setShowDatePicker(false); }}>
                  <Dropdown.Toggle variant="outline-secondary" size="sm">
                    <Filter size={14} className="me-1" />Filter{filterLanguage ? `: ${filterLanguage}` : ''}
                  </Dropdown.Toggle>
                  <Dropdown.Menu>
                    <Dropdown.Item active={!filterLanguage} onClick={() => { setFilterLanguage(''); setShowFilterDropdown(false); }}>All Languages</Dropdown.Item>
                    {availableLanguages.map(lang => (
                      <Dropdown.Item key={lang} active={filterLanguage === lang} onClick={() => { setFilterLanguage(lang); setShowFilterDropdown(false); }}>
                        {lang.charAt(0).toUpperCase() + lang.slice(1)}
                      </Dropdown.Item>
                    ))}
                  </Dropdown.Menu>
                </Dropdown>
                <div style={{ position: 'relative' }} ref={datePickerRef}>
                  <button
                    className="btn btn-outline-secondary btn-sm"
                    onClick={() => { setShowDatePicker(!showDatePicker); setShowFilterDropdown(false); }}
                  >
                    <Calendar3 size={14} className="me-1" />
                    {filterDate ? moment(filterDate).format('MM/DD/YYYY') : 'Select Date to View'}
                  </button>
                  {filterDate && (
                    <button
                      className="btn btn-link btn-sm p-0 ms-1"
                      onClick={(e) => { e.stopPropagation(); setFilterDate(null); setShowDatePicker(false); }}
                      title="Clear date"
                      style={{ fontSize: '14px', textDecoration: 'none', color: '#999' }}
                    >
                      ✕
                    </button>
                  )}
                  {showDatePicker && (
                    <div style={{ position: 'absolute', top: '100%', right: 0, zIndex: 1000, marginTop: '4px' }}>
                      <DatePicker
                        selected={filterDate}
                        onChange={(date) => { setFilterDate(date); setShowDatePicker(false); }}
                        inline
                      />
                    </div>
                  )}
                </div>
                <button className="btn btn-primary btn-sm" onClick={openSendModal}><Send size={14} className="me-1" />Send New Message</button>
              </>
            )}
            {activeTab === 'messageTemplate' && (
              <button className="btn btn-primary btn-sm" onClick={openCreateTemplateModal}><Plus size={16} className="me-1" />Create Message Template</button>
            )}
          </div>
        </div>
      </div>

      {/* Create / Edit Message Template Modal */}
      <Modal show={showCreateTemplateModal} onHide={closeTemplateModal} centered>
        <Modal.Header closeButton>
          <Modal.Title>{editingTemplate ? 'Edit Message Template' : 'Create New Message Template'}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div className="mb-3">
            <label className="form-label"><strong>Template Title</strong> <span className="text-danger">*</span></label>
            <input type="text" className="form-control" placeholder="e.g., Pick Up" value={templateTitle} onChange={(e) => setTemplateTitle(e.target.value)} />
          </div>
          <div className="mb-3">
            <label className="form-label"><strong>Message Content (Chinese)</strong> <span className="text-danger">*</span></label>
            <textarea className="form-control" rows={4} placeholder="e.g., 尊敬的{Name}:您的今天乘坐的车辆已于{Time}出发，司机{Driver}，车号{VehicleNum},请及时做好准备准时登车。" value={templateChinese} onChange={(e) => setTemplateChinese(e.target.value)} />
          </div>
          <div className="mb-3">
            <label className="form-label"><strong>Message Content (English)</strong> <span className="text-danger">*</span></label>
            <textarea className="form-control" rows={4} placeholder="e.g., {Name}: Your vehicle today has departed at {Time}, driver {Driver}, vehicle number {VehicleNum}, please be ready to board on time." value={templateEnglish} onChange={(e) => setTemplateEnglish(e.target.value)} />
          </div>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="primary" onClick={handleSaveTemplate}>Save</Button>
          <Button variant="light" onClick={closeTemplateModal}>Cancel</Button>
        </Modal.Footer>
      </Modal>

      {/* Send New Message Modal */}
      <Modal show={showSendModal} onHide={closeSendModal} centered size="lg">
        <Modal.Header closeButton>
          <Modal.Title>Send New Message</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div className="mb-3">
            <label className="form-label"><strong>Select Recipient</strong> <span className="text-danger">*</span></label>
            <MultiSelectDropdown
              value={selectedRecipients}
              onChange={(val) => setSelectedRecipients(val || [])}
              options={eligibleCustomers.map(c => ({ value: c.id, label: c.name }))}
              placeholder="e.g., Recipient Name"
            />
          </div>
          <div className="mb-3">
            <label className="form-label"><strong>Select Template</strong></label>
            <Select
              isClearable
              value={selectedTemplate}
              onChange={handleTemplateSelect}
              options={customTemplates.map(t => ({ value: t.id, label: t.title }))}
              placeholder="e.g., Template 1"
              styles={{
                control: (base) => ({ ...base, borderRadius: '8px' }),
                indicatorSeparator: () => ({ display: 'none' })
              }}
            />
          </div>
          <hr />
          <div className="mb-3">
            <label className="form-label"><strong>Message Title</strong></label>
            <input type="text" className="form-control" placeholder="e.g., Pick Up" value={sendTitle} onChange={(e) => setSendTitle(e.target.value)} />
          </div>
          <div className="mb-3">
            <label className="form-label"><strong>Message Content (Chinese)</strong></label>
            <textarea className="form-control" rows={4} placeholder="e.g., 尊敬的{Name}:您的今天乘坐的车辆已于{Time}出发，司机{Driver}，车号{VehicleNum},请及时做好准备准时登车。" value={sendChinese} onChange={(e) => setSendChinese(e.target.value)} />
          </div>
          <div className="mb-3">
            <label className="form-label"><strong>Message Content (English)</strong></label>
            <textarea className="form-control" rows={4} placeholder="e.g., {Name}: Your vehicle today has departed at {Time}, driver {Driver}, vehicle number {VehicleNum}, please be ready to board on time." value={sendEnglish} onChange={(e) => setSendEnglish(e.target.value)} />
          </div>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="primary" onClick={openPreview}><Eye size={16} className="me-2" />Preview</Button>
          <Button variant="light" onClick={closeSendModal}>Cancel</Button>
        </Modal.Footer>
      </Modal>

      {/* Preview Modal */}
      <Modal show={showPreviewModal} onHide={() => setShowPreviewModal(false)} centered size="lg">
        <Modal.Header closeButton>
          <Modal.Title>Message Preview</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {placeholders.length > 0 && (
            <div className="mb-4">
              <h6>Fill in Placeholders</h6>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                {placeholders.map((ph) => (
                  <div key={ph}>
                    <label className="form-label" style={{ fontSize: '13px', fontWeight: 600 }}>{`{${ph}}`}</label>
                    <input
                      type="text"
                      className="form-control form-control-sm"
                      placeholder={`Enter ${ph}`}
                      value={placeholderValues[ph] || ''}
                      onChange={(e) => setPlaceholderValues(prev => ({ ...prev, [ph]: e.target.value }))}
                    />
                  </div>
                ))}
              </div>
            </div>
          )}

          <h6>Preview</h6>
          <table className="personnel-info-table" style={{ marginTop: '8px' }}>
            <thead>
              <tr>
                <th className="th-index">No.</th>
                <th>Message Content</th>
              </tr>
            </thead>
            <tbody>
              {previewChinese && (
                <tr>
                  <td className="td-index">1</td>
                  <td style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', padding: '12px 16px' }}>{previewChinese}</td>
                </tr>
              )}
              {previewEnglish && (
                <tr>
                  <td className="td-index">{previewChinese ? 2 : 1}</td>
                  <td style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', padding: '12px 16px' }}>{previewEnglish}</td>
                </tr>
              )}
            </tbody>
          </table>

          <div className="mt-3 text-muted" style={{ fontSize: '13px' }}>
            Sending to <strong>{selectedRecipients.length}</strong> recipient{selectedRecipients.length !== 1 ? 's' : ''}. Each recipient will receive the message in their preferred language.
          </div>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="outline-secondary" onClick={backToEditing}><ArrowLeft size={16} className="me-2" />Back to Editing</Button>
          <Button variant="primary" onClick={handleSendNow} disabled={sending}>
            {sending ? 'Sending...' : 'Send Now'}
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  )
};

export default MessageList;
