import { useEffect, useMemo, useState } from 'react';
import { useInbox } from '../context/InboxContext';
import { useLanguage } from '../context/LanguageContext';
import { useToast } from '../context/ToastContext';

const FILTERS = [
  { key: 'inbox', label: 'Inbox' },
  { key: 'starred', label: 'Starred' },
  { key: 'archive', label: 'Archive' },
  { key: 'trash', label: 'Trash' },
];

const AVATARS = [
  { bg: '#e8f0fe', color: '#1a4fa8' },
  { bg: '#e3f7ef', color: '#1c7a50' },
  { bg: '#fdeaea', color: '#a32828' },
  { bg: '#fef3db', color: '#93590a' },
  { bg: '#f0eeff', color: '#4a35b0' },
];

function MailIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="2" y="4" width="20" height="16" rx="3" />
      <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
    </svg>
  );
}

function CopyIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <rect x="9" y="9" width="13" height="13" rx="2" />
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
    </svg>
  );
}

function StarIcon({ filled = false }) {
  if (filled) {
    return (
      <svg viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
      </svg>
    );
  }

  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
    </svg>
  );
}

function ArchiveIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <polyline points="21 8 21 21 3 21 3 8" />
      <rect x="1" y="3" width="22" height="5" />
      <line x1="10" y1="12" x2="14" y2="12" />
    </svg>
  );
}

function TrashIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <polyline points="3 6 5 6 21 6" />
      <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6" />
      <path d="M10 11v6" />
      <path d="M14 11v6" />
      <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
    </svg>
  );
}

function FileIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
    </svg>
  );
}

function AttachmentIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M21.44 11.05 12.25 20.24a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.82-2.82l8.49-8.48" />
    </svg>
  );
}

function MarkUnreadIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M22 8.5V19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8.5" />
      <path d="m22 6-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 6" />
      <path d="M4 4h16" />
    </svg>
  );
}

function formatListDate(value) {
  if (!value) return '';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '';
  const now = new Date();
  const sameDay = date.toDateString() === now.toDateString();
  if (sameDay) {
    return new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date);
  }
  return new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' }).format(date);
}

function formatDetailDate(value) {
  if (!value) return '';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return '';
  return new Intl.DateTimeFormat(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(date);
}

function formatCountdown(totalSeconds) {
  const seconds = Math.max(0, Number(totalSeconds || 0));
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return [hours, minutes, secs].map((value) => String(value).padStart(2, '0')).join(':');
}

function makeHtmlBody(message) {
  if (message?.htmlBody) return message.htmlBody;
  const text = String(message?.bodyText || message?.snippet || '').trim();
  return `<p>${text.replace(/\n/g, '<br />')}</p>`;
}

function getInitials(name) {
  return String(name || '')
    .split(/\s+/)
    .filter(Boolean)
    .map((part) => part[0])
    .join('')
    .slice(0, 2)
    .toUpperCase();
}

function getAvatarColors(seed) {
  const text = String(seed || '0');
  const total = Array.from(text).reduce((sum, char) => sum + char.charCodeAt(0), 0);
  return AVATARS[total % AVATARS.length];
}

function getFolderKey(message) {
  if (message?.deleted || message?.isDeleted || message?.trashed || message?.folder === 'trash') return 'trash';
  if (message?.archived || message?.isArchived || message?.folder === 'archive') return 'archive';
  return 'inbox';
}

function getMessageSender(message) {
  return message?.from || message?.fromName || message?.fromEmail || 'Unknown sender';
}

function getMessagePreview(message) {
  return String(message?.snippet || message?.bodyText || message?.plainText || '').trim();
}

function getAttachmentItems(message) {
  if (Array.isArray(message?.attachments) && message.attachments.length) {
    return message.attachments;
  }
  if (message?.hasAttachments) {
    return [{ id: 'pending', filename: 'Attachments loading...', size: '', type: '' }];
  }
  return [];
}

export default function InboxPage() {
  const {
    session,
    sessionLoading,
    messages,
    messagesLoading,
    remainingSeconds,
    isGuestInbox,
    inboxAddress,
    fetchMessage,
    markUnread,
    toggleStar,
  } = useInbox();
  const { isRtl } = useLanguage();
  const toast = useToast();

  const [currentFilter, setCurrentFilter] = useState('inbox');
  const [selectedEmailId, setSelectedEmailId] = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [copyLabel, setCopyLabel] = useState('Copy');

  useEffect(() => {
    const fontLinkId = 'messages-redesign-fonts';
    if (!document.getElementById(fontLinkId)) {
      const link = document.createElement('link');
      link.id = fontLinkId;
      link.rel = 'stylesheet';
      link.href = 'https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;1,9..40,400&family=DM+Mono:wght@400;500&display=swap';
      document.head.appendChild(link);
    }
  }, []);

  const decoratedMessages = useMemo(
    () => (Array.isArray(messages) ? messages : []).map((item) => ({
      ...item,
      folderKey: getFolderKey(item),
      senderName: getMessageSender(item),
      previewText: getMessagePreview(item),
      timeLabel: formatListDate(item?.receivedAt),
      detailTimeLabel: formatDetailDate(item?.receivedAt),
      attachmentItems: getAttachmentItems(item),
    })),
    [messages],
  );

  const folderCounts = useMemo(
    () => FILTERS.reduce((acc, filter) => {
      acc[filter.key] = decoratedMessages.filter((message) => {
        if (filter.key === 'starred') return Boolean(message.starred);
        return message.folderKey === filter.key;
      }).length;
      return acc;
    }, {}),
    [decoratedMessages],
  );

  const filteredMessages = useMemo(
    () => decoratedMessages.filter((message) => {
      if (currentFilter === 'starred') return Boolean(message.starred);
      return message.folderKey === currentFilter;
    }),
    [currentFilter, decoratedMessages],
  );

  const selectedEmail = useMemo(
    () => decoratedMessages.find((message) => message.id === selectedEmailId) || null,
    [decoratedMessages, selectedEmailId],
  );

  useEffect(() => {
    if (selectedEmailId && !decoratedMessages.some((message) => message.id === selectedEmailId)) {
      setSelectedEmailId(null);
    }
  }, [decoratedMessages, selectedEmailId]);

  async function handleCopyInboxEmail() {
    try {
      await navigator.clipboard.writeText(inboxAddress || '');
      setCopyLabel('Copied!');
      toast.success('Email copied');
      window.setTimeout(() => setCopyLabel('Copy'), 1800);
    } catch {
      toast.error('Copy failed');
    }
  }

  async function handleSelectEmail(id) {
    setSelectedEmailId(id);
    setDetailLoading(true);
    try {
      await fetchMessage(id);
    } catch {
      toast.error('Failed to load email');
    } finally {
      setDetailLoading(false);
    }
  }

  async function handleToggleStar(email, event) {
    if (event) event.stopPropagation();
    try {
      await toggleStar(email.id, !email.starred);
    } catch {
      toast.error('Failed to update star');
    }
  }

  async function handleMarkUnread(messageId, event) {
    if (event) event.stopPropagation();
    try {
      await markUnread(messageId);
      toast.success('Marked as unread');
    } catch {
      toast.error('Failed to mark unread');
    }
  }

  function handleArchiveSelected() {
    toast.info('Archive action is not connected yet');
  }

  function handleDeleteSelected() {
    toast.info('Delete action is not connected yet');
  }

  if (sessionLoading && !session) {
    return (
      <div className="messages-react-page" dir={isRtl ? 'rtl' : 'ltr'}>
        <div className="messages-loading-shell">Loading inbox...</div>
      </div>
    );
  }

  return (
    <div className="messages-react-page" dir={isRtl ? 'rtl' : 'ltr'}>
      <div className="shell">
        <div className="subheader">
          <div className="subheader-left">
            <div className="email-strip">
              <span className="email-addr">{inboxAddress || 'No inbox address'}</span>

              <button type="button" className="copy-btn" onClick={handleCopyInboxEmail}>
                <CopyIcon />
                <span>{copyLabel}</span>
              </button>

              <div className="timer-chip">
                <div className="timer-dot" />
                <span className="timer-val">{isGuestInbox ? formatCountdown(remainingSeconds) : 'Permanent'}</span>
              </div>
            </div>
          </div>

          <div className="filters">
            {FILTERS.map((filter) => {
              const count = folderCounts[filter.key] || 0;
              const isActive = currentFilter === filter.key;

              return (
                <button
                  key={filter.key}
                  type="button"
                  className={`filter-btn ${isActive ? 'active' : ''}`}
                  onClick={() => {
                    setCurrentFilter(filter.key);
                    setSelectedEmailId(null);
                  }}
                >
                  <span>{filter.label}</span>
                  {count > 0 ? <span className="filter-count">{count}</span> : null}
                </button>
              );
            })}
          </div>
        </div>

        <div className="split">
          <div className="msg-list-panel">
            <div className="msg-list-inner">
              {messagesLoading && !filteredMessages.length ? (
                <div className="list-empty">
                  <div className="list-empty-title">Loading messages</div>
                </div>
              ) : filteredMessages.length === 0 ? (
                <div className="list-empty">
                  <div className="list-empty-icon">
                    <MailIcon />
                  </div>
                  <div className="list-empty-title">No messages</div>
                  <div className="list-empty-copy">This folder is empty</div>
                </div>
              ) : (
                filteredMessages.map((message, index) => {
                  const avatar = getAvatarColors(message.id || message.fromEmail || message.senderName);
                  const isSelected = selectedEmailId === message.id;
                  const isUnread = !message.read;
                  const hasAttachments = message.attachmentItems.length > 0;

                  return (
                    <button
                      key={message.id}
                      type="button"
                      className={`msg-item ${isSelected ? 'active' : ''} ${isUnread ? 'unread' : 'read'}`}
                      onClick={() => handleSelectEmail(message.id)}
                      style={{ animationDelay: `${index * 40}ms` }}
                    >
                      <div className="msg-avatar" style={{ background: avatar.bg, color: avatar.color }}>
                        {getInitials(message.senderName)}
                      </div>

                      <div className="msg-content">
                        <div className="msg-top">
                          <span className="msg-sender">{message.senderName}</span>

                          <div className="msg-status">
                            {hasAttachments ? (
                              <span className="msg-attachment-icon" title="Has attachment" aria-label="Has attachment">
                                <AttachmentIcon />
                              </span>
                            ) : null}
                            <span className="msg-time">{message.timeLabel}</span>
                            {isUnread ? <span className="msg-unread-dot" aria-hidden="true" /> : null}
                          </div>
                        </div>
                        <div className="msg-subject">{message.subject || '(No subject)'}</div>
                        <div className="msg-preview">{message.previewText || 'No preview available'}</div>
                      </div>
                    </button>
                  );
                })
              )}
            </div>
          </div>

          <div className="preview-panel">
            {!selectedEmail ? (
              <div className="preview-empty-wrap">
                <div className="preview-empty-icon">
                  <MailIcon />
                </div>
                <div className="preview-empty-title">No message selected</div>
                <div className="preview-empty-sub">Pick a message from the list to read it</div>
              </div>
            ) : (
              (() => {
                const avatar = getAvatarColors(selectedEmail.id || selectedEmail.fromEmail || selectedEmail.senderName);
                const hasAttachments = selectedEmail.attachmentItems.length > 0;

                return (
                  <>
                    <div className="preview-header">
                      <div className="preview-top-row">
                        <div className="preview-avatar" style={{ background: avatar.bg, color: avatar.color }}>
                          {getInitials(selectedEmail.senderName)}
                        </div>

                        <div className="preview-sender-block">
                          <div className="preview-sender-name">{selectedEmail.senderName}</div>
                          <div className="preview-sender-email">{selectedEmail.fromEmail || 'Unknown email'}</div>
                          <div className="preview-time-inline">{selectedEmail.detailTimeLabel || selectedEmail.timeLabel}</div>
                        </div>

                        <div className="preview-actions">
                          <button
                            type="button"
                            className={`action-btn ${selectedEmail.starred ? 'star-active' : ''}`}
                            onClick={() => handleToggleStar(selectedEmail)}
                            aria-label="Toggle star"
                            title="Star"
                          >
                            <StarIcon filled={selectedEmail.starred} />
                          </button>

                          <button
                            type="button"
                            className="action-btn"
                            onClick={(event) => handleMarkUnread(selectedEmail.id, event)}
                            aria-label="Mark message as unread"
                            title="Mark message as unread"
                          >
                            <MarkUnreadIcon />
                          </button>

                          <button type="button" className="action-btn" onClick={handleArchiveSelected} aria-label="Archive" title="Archive">
                            <ArchiveIcon />
                          </button>

                          <button type="button" className="action-btn danger" onClick={handleDeleteSelected} aria-label="Delete" title="Delete">
                            <TrashIcon />
                          </button>
                        </div>
                      </div>

                      <div className="preview-subject-row">
                        <div className="preview-subject">{selectedEmail.subject || '(No subject)'}</div>
                        {hasAttachments ? <span className="tag tag-attachment">attachment</span> : null}
                        {!selectedEmail.read ? <span className="tag tag-unread">unread</span> : null}
                      </div>
                    </div>

                    <div className="preview-body-wrap">
                      <div className="preview-body">
                        {detailLoading ? (
                          <div className="preview-loading">Loading email...</div>
                        ) : (
                          <>
                            <div dangerouslySetInnerHTML={{ __html: makeHtmlBody(selectedEmail) }} />

                            {hasAttachments ? (
                              <div className="attachments">
                                <div className="attach-label">Attachments ({selectedEmail.attachmentItems.length})</div>
                                <div className="attach-list">
                                  {selectedEmail.attachmentItems.map((attachment, index) => (
                                    <div key={attachment.id || attachment.filename || attachment.original_name || index} className="attach-item">
                                      <div className="attach-icon" style={{ background: avatar.bg, color: avatar.color }}>
                                        <FileIcon />
                                      </div>
                                      <div>
                                        <div className="attach-name">{attachment.original_name || attachment.filename || attachment.name || 'Attachment'}</div>
                                        <div className="attach-meta">
                                          {[attachment.size, attachment.type || attachment.mime_type].filter(Boolean).join(' · ')}
                                        </div>
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            ) : null}
                          </>
                        )}
                      </div>
                    </div>
                  </>
                );
              })()
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
