import { useState } from 'react';
import { useContactEmails, useIntegrations, useCreateActivity } from '../hooks';
import { integrationsApi } from '../api';
import type { M365Email, M365EmailAddress } from '../types';
import styles from './EmailsTab.module.css';

interface Props {
  contactId: string;
}

function formatEmailDate(iso: string): string {
  return new Date(iso).toLocaleString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

function formatEmailTime(iso: string): string {
  const d = new Date(iso);
  const now = new Date();
  if (d.toDateString() === now.toDateString()) {
    return d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
  }
  return d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

function recipientsText(
  recipients: Array<{ emailAddress: M365EmailAddress }>,
): string {
  return recipients
    .map((r) => r.emailAddress.name ?? r.emailAddress.address ?? '—')
    .join(', ');
}

type SaveState = 'idle' | 'saving' | 'saved' | 'error';

/* ── Detail-Popup (Outlook-ähnlich) ───────────────────────────────────────── */

function EmailDetailModal({
  email,
  contactId,
  onClose,
}: {
  email: M365Email;
  contactId: string;
  onClose: () => void;
}) {
  const createActivity = useCreateActivity();
  const [saveState, setSaveState] = useState<SaveState>('idle');

  const fromName =
    email.from?.emailAddress?.name ?? email.from?.emailAddress?.address ?? '—';
  const toText = email.toRecipients?.length
    ? recipientsText(email.toRecipients)
    : '—';

  async function handleSave() {
    if (saveState === 'saved') return;
    setSaveState('saving');
    try {
      await createActivity.mutateAsync({
        contactId,
        type: 'EMAIL',
        subject: email.subject ?? '(kein Betreff)',
        description: email.bodyPreview ?? undefined,
        scheduledAt: email.receivedDateTime,
        completedAt: email.receivedDateTime,
      });
      setSaveState('saved');
    } catch {
      setSaveState('error');
    }
  }

  return (
    <div className={styles.backdrop} onClick={onClose}>
      <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div className={styles.modalHeader}>
          <div className={styles.modalHeaderLeft}>
            <h2 className={styles.modalSubject}>{email.subject ?? '(kein Betreff)'}</h2>
            {!email.isRead && (
              <span className={styles.modalUnreadBadge}>Ungelesen</span>
            )}
          </div>
          <button
            type="button"
            className={styles.modalClose}
            onClick={onClose}
            aria-label="Schließen"
          >
            ×
          </button>
        </div>

        {/* Body */}
        <div className={styles.modalBody}>
          {/* Meta: Von / An / Datum / Anhang */}
          <div className={styles.metaTable}>
            <span className={styles.metaLabel}>Von</span>
            <span className={styles.metaValue}>{fromName}</span>

            <span className={styles.metaLabel}>An</span>
            <span className={styles.metaValue}>{toText}</span>

            <span className={styles.metaLabel}>Datum</span>
            <span className={styles.metaValue}>{formatEmailDate(email.receivedDateTime)}</span>

            {email.hasAttachments && (
              <>
                <span className={styles.metaLabel}>Anhang</span>
                <span className={styles.metaValue}>📎 Anhänge vorhanden</span>
              </>
            )}
          </div>

          {/* Body-Vorschau */}
          {email.bodyPreview ? (
            <>
              <div className={styles.bodyPreview}>{email.bodyPreview}</div>
              <p className={styles.bodyHint}>
                Vorschau — vollständige E-Mail in Outlook öffnen
              </p>
            </>
          ) : (
            <p className={styles.bodyHint}>Kein Vorschautext verfügbar</p>
          )}

          {/* In Kontakt speichern */}
          <div className={styles.saveSection}>
            <button
              type="button"
              className={`${styles.saveBtn}${saveState === 'saved' ? ` ${styles.saveBtnSuccess}` : ''}${saveState === 'error' ? ` ${styles.saveBtnError}` : ''}`}
              onClick={handleSave}
              disabled={saveState === 'saving' || saveState === 'saved'}
            >
              {saveState === 'idle' && '+ In Kontakt speichern'}
              {saveState === 'saving' && 'Speichern…'}
              {saveState === 'saved' && '✓ Gespeichert'}
              {saveState === 'error' && '✗ Fehler – erneut versuchen'}
            </button>
            {saveState === 'saved' && (
              <span className={styles.saveMsg}>
                E-Mail als Aktivität gespeichert
              </span>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className={styles.modalFooter}>
          <span className={styles.modalFooterDate}>
            {formatEmailDate(email.receivedDateTime)}
          </span>
          <a
            href={email.webLink}
            target="_blank"
            rel="noopener noreferrer"
            className={styles.outlookBtn}
          >
            <svg
              width="13"
              height="13"
              viewBox="0 0 16 16"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M6 2H2a1 1 0 00-1 1v10a1 1 0 001 1h12a1 1 0 001-1V8" />
              <path d="M10 1h5v5" />
              <path d="M6 10L15 1" />
            </svg>
            In Outlook öffnen
          </a>
        </div>
      </div>
    </div>
  );
}

/* ── Hauptkomponente ──────────────────────────────────────────────────────── */

export function EmailsTab({ contactId }: Props) {
  const { data: integrationsData } = useIntegrations();
  const isConnected =
    (integrationsData?.data?.some(
      (i) => i.provider === 'MICROSOFT_365' && i.connected,
    ) ?? false);

  const { data, isLoading, error } = useContactEmails(contactId);
  const emails: M365Email[] = data?.data ?? [];
  const [selectedEmail, setSelectedEmail] = useState<M365Email | null>(null);

  if (!isConnected) {
    return (
      <div style={{ padding: '1.5rem 0', textAlign: 'center' }}>
        <p
          style={{
            color: 'var(--color-text-muted)',
            fontSize: '0.9375rem',
            marginBottom: '1rem',
          }}
        >
          Verbinden Sie Microsoft 365, um E-Mails zu diesem Kontakt zu sehen.
        </p>
        <button
          type="button"
          onClick={() => integrationsApi.connectM365()}
          style={{
            display: 'inline-flex',
            alignItems: 'center',
            gap: '0.5rem',
            padding: '0.4375rem 1rem',
            background: 'var(--color-primary)',
            color: 'white',
            border: 'none',
            borderRadius: 'var(--radius-sm)',
            fontSize: '0.875rem',
            fontWeight: 600,
            cursor: 'pointer',
          }}
        >
          Microsoft 365 verbinden
        </button>
      </div>
    );
  }

  if (isLoading) {
    return (
      <p
        style={{
          color: 'var(--color-text-muted)',
          fontSize: '0.875rem',
          padding: '1rem 0',
        }}
      >
        Laden…
      </p>
    );
  }

  if (error) {
    return (
      <p
        style={{
          color: 'var(--color-error)',
          fontSize: '0.875rem',
          padding: '1rem 0',
        }}
      >
        E-Mails konnten nicht geladen werden.
      </p>
    );
  }

  if (emails.length === 0) {
    return (
      <p
        style={{
          color: 'var(--color-text-muted)',
          fontSize: '0.875rem',
          padding: '1rem 0',
        }}
      >
        Keine E-Mails gefunden.
      </p>
    );
  }

  return (
    <>
      <div className={styles.emailList}>
        {emails.map((email) => (
          <button
            key={email.id}
            type="button"
            className={`${styles.emailItem}${!email.isRead ? ` ${styles.emailItemUnread}` : ''}`}
            onClick={() => setSelectedEmail(email)}
          >
            {!email.isRead ? (
              <span className={styles.unreadDot} aria-hidden="true" />
            ) : (
              <span className={styles.readSpacer} />
            )}
            <div className={styles.emailMeta}>
              <div className={styles.emailRow1}>
                <span
                  className={`${styles.emailSubject}${!email.isRead ? ` ${styles.emailSubjectUnread}` : ''}`}
                >
                  {email.subject ?? '(kein Betreff)'}
                </span>
                <span className={styles.emailTime}>
                  {formatEmailTime(email.receivedDateTime)}
                </span>
              </div>
              <div className={styles.emailFrom}>
                Von:{' '}
                {email.from?.emailAddress?.name ??
                  email.from?.emailAddress?.address ??
                  '—'}
              </div>
              {email.bodyPreview && (
                <div className={styles.emailPreview}>{email.bodyPreview}</div>
              )}
            </div>
            {email.hasAttachments && (
              <span className={styles.attachBadge} title="Anhänge vorhanden">
                📎
              </span>
            )}
          </button>
        ))}
      </div>

      {selectedEmail !== null && (
        <EmailDetailModal
          email={selectedEmail}
          contactId={contactId}
          onClose={() => setSelectedEmail(null)}
        />
      )}
    </>
  );
}
