import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  useIntegrations,
  useOffice365Emails,
  useOffice365Calendar,
  useOffice365Contacts,
  useOffice365Tasks,
} from '../hooks';
import { integrationsApi } from '../api';
import type { M365Email, M365CalendarEvent, M365Contact, M365TaskList } from '../types';
import styles from './Office365Page.module.css';

// ── Helpers ──────────────────────────────────────────────────────────────────

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

function formatDateOnly(iso: string) {
  return new Date(iso).toLocaleDateString('de-DE', {
    weekday: 'short',
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  });
}

type Tab = 'emails' | 'calendar' | 'contacts' | 'tasks';

const TAB_LABELS: { id: Tab; label: string }[] = [
  { id: 'emails', label: 'E-Mails' },
  { id: 'calendar', label: 'Kalender' },
  { id: 'contacts', label: 'Kontakte' },
  { id: 'tasks', label: 'Aufgaben' },
];

// ── E-Mails ───────────────────────────────────────────────────────────────────

function EmailsList() {
  const { data, isLoading, error } = useOffice365Emails();
  const emails: M365Email[] = data?.data ?? [];

  if (isLoading) return <p className={styles.loadingText}>E-Mails werden geladen…</p>;
  if (error) return <p className={styles.errorText}>E-Mails konnten nicht geladen werden.</p>;
  if (!emails.length) return <p className={styles.emptyText}>Keine E-Mails gefunden.</p>;

  return (
    <div className={styles.list}>
      {emails.map((email) => (
        <a
          key={email.id}
          href={email.webLink}
          target="_blank"
          rel="noopener noreferrer"
          className={styles.emailCard}
        >
          <div className={styles.emailHeader}>
            <span className={`${styles.emailSubject} ${!email.isRead ? styles.unread : ''}`}>
              {email.subject || '(Kein Betreff)'}
            </span>
            <span className={styles.emailDate}>
              {formatDate(email.receivedDateTime)}
            </span>
          </div>
          <div className={styles.emailMeta}>
            <span className={styles.emailFrom}>
              {email.from?.emailAddress?.name || email.from?.emailAddress?.address || '—'}
            </span>
            {email.hasAttachments && (
              <span className={styles.attachmentBadge}>📎</span>
            )}
          </div>
          {email.bodyPreview && (
            <p className={styles.emailPreview}>{email.bodyPreview}</p>
          )}
        </a>
      ))}
    </div>
  );
}

// ── Kalender ──────────────────────────────────────────────────────────────────

function CalendarList() {
  const { data, isLoading, error } = useOffice365Calendar();
  const events: M365CalendarEvent[] = data?.data ?? [];

  if (isLoading) return <p className={styles.loadingText}>Termine werden geladen…</p>;
  if (error) return <p className={styles.errorText}>Kalendertermine konnten nicht geladen werden.</p>;
  if (!events.length) return <p className={styles.emptyText}>Keine Termine in den nächsten 30 Tagen.</p>;

  return (
    <div className={styles.list}>
      {events.map((event) => (
        <a
          key={event.id}
          href={event.webLink}
          target="_blank"
          rel="noopener noreferrer"
          className={styles.calendarCard}
        >
          <div className={styles.calendarDate}>
            <span className={styles.calendarDay}>
              {new Date(event.start.dateTime).toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: 'short' })}
            </span>
            <span className={styles.calendarTime}>
              {new Date(event.start.dateTime).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
              {' – '}
              {new Date(event.end.dateTime).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })}
            </span>
          </div>
          <div className={styles.calendarContent}>
            <span className={styles.calendarSubject}>{event.subject}</span>
            {event.location?.displayName && (
              <span className={styles.calendarLocation}>📍 {event.location.displayName}</span>
            )}
            {event.attendees && event.attendees.length > 0 && (
              <span className={styles.calendarAttendees}>
                {event.attendees.slice(0, 3).map((a) => a.emailAddress.name || a.emailAddress.address).join(', ')}
                {event.attendees.length > 3 && ` +${event.attendees.length - 3}`}
              </span>
            )}
          </div>
          {event.isOnlineMeeting && (
            <span className={styles.onlineBadge}>Online</span>
          )}
        </a>
      ))}
    </div>
  );
}

// ── Outlook-Kontakte ──────────────────────────────────────────────────────────

function ContactsList() {
  const navigate = useNavigate();
  const { data, isLoading, error } = useOffice365Contacts();
  const contacts: M365Contact[] = data?.data ?? [];
  const [search, setSearch] = useState('');

  if (isLoading) return <p className={styles.loadingText}>Kontakte werden geladen…</p>;
  if (error) return <p className={styles.errorText}>Kontakte konnten nicht geladen werden.</p>;

  const filtered = contacts.filter((c) => {
    const q = search.toLowerCase();
    return (
      c.displayName.toLowerCase().includes(q) ||
      c.emailAddresses.some((e) => e.address?.toLowerCase().includes(q)) ||
      c.companyName?.toLowerCase().includes(q)
    );
  });

  return (
    <div>
      <input
        type="search"
        placeholder="Kontakte durchsuchen…"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        className={styles.searchInput}
      />
      {!filtered.length ? (
        <p className={styles.emptyText}>Keine Kontakte gefunden.</p>
      ) : (
        <div className={styles.contactGrid}>
          {filtered.map((contact) => {
            const primaryEmail = contact.emailAddresses[0]?.address;
            return (
              <div key={contact.id} className={styles.contactCard}>
                <div className={styles.contactAvatar}>
                  {contact.displayName.charAt(0).toUpperCase()}
                </div>
                <div className={styles.contactInfo}>
                  <span className={styles.contactName}>{contact.displayName}</span>
                  {contact.jobTitle && (
                    <span className={styles.contactMeta}>{contact.jobTitle}</span>
                  )}
                  {contact.companyName && (
                    <span className={styles.contactMeta}>{contact.companyName}</span>
                  )}
                  {primaryEmail && (
                    <a href={`mailto:${primaryEmail}`} className={styles.contactEmail}>
                      {primaryEmail}
                    </a>
                  )}
                  {contact.mobilePhone && (
                    <span className={styles.contactMeta}>{contact.mobilePhone}</span>
                  )}
                </div>
                {primaryEmail && (
                  <button
                    type="button"
                    className={styles.importButton}
                    title="In CRM-Kontakten suchen"
                    onClick={() => navigate(`/crm/contacts?search=${encodeURIComponent(primaryEmail)}`)}
                  >
                    CRM
                  </button>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ── Aufgaben ─────────────────────────────────────────────────────────────────

const importanceColors = { high: '#ef4444', normal: 'var(--color-text-muted)', low: '#9ca3af' };
const importanceLabel = { high: '!', normal: '', low: '' };

function TasksList() {
  const { data, isLoading, error } = useOffice365Tasks();
  const taskLists: M365TaskList[] = data?.data ?? [];

  if (isLoading) return <p className={styles.loadingText}>Aufgaben werden geladen…</p>;
  if (error) return <p className={styles.errorText}>Aufgaben konnten nicht geladen werden.</p>;

  const allTasks = taskLists.flatMap((l) =>
    l.tasks.map((t) => ({ ...t, listName: l.displayName })),
  );

  if (!allTasks.length) return <p className={styles.emptyText}>Keine offenen Aufgaben.</p>;

  return (
    <div className={styles.list}>
      {allTasks.map((task) => (
        <div key={task.id} className={styles.taskCard}>
          <div
            className={styles.taskImportance}
            style={{ color: importanceColors[task.importance as keyof typeof importanceColors] ?? 'var(--color-text-muted)' }}
          >
            {importanceLabel[task.importance as keyof typeof importanceLabel] ?? ''}
          </div>
          <div className={styles.taskContent}>
            <span className={styles.taskTitle}>{task.title}</span>
            <span className={styles.taskMeta}>
              {task.listName}
              {task.dueDateTime && (
                <> · Fällig {formatDateOnly(task.dueDateTime.dateTime)}</>
              )}
            </span>
          </div>
          <span className={`${styles.taskStatus} ${styles[`status_${task.status}`] ?? ''}`}>
            {task.status === 'notStarted' ? 'Offen' : task.status === 'inProgress' ? 'In Arbeit' : task.status}
          </span>
        </div>
      ))}
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export function Office365Page() {
  const [activeTab, setActiveTab] = useState<Tab>('emails');
  const { data: integrationsData, isLoading: integrationsLoading } = useIntegrations();
  const isConnected = integrationsData?.data?.some(
    (i) => i.provider === 'MICROSOFT_365' && i.connected,
  ) ?? false;

  return (
    <div>
      <div className={styles.pageHeader}>
        <h1 className={styles.pageTitle}>Microsoft Office 365</h1>
        {!integrationsLoading && (
          <span className={isConnected ? styles.connectedBadge : styles.disconnectedBadge}>
            {isConnected ? '● Verbunden' : '○ Nicht verbunden'}
          </span>
        )}
      </div>

      {!integrationsLoading && !isConnected && (
        <div className={styles.connectPrompt}>
          <p>Verbinden Sie Ihr Microsoft 365-Konto, um E-Mails, Kalender, Kontakte und Aufgaben zu sehen.</p>
          <button
            type="button"
            className={styles.connectButton}
            onClick={() => integrationsApi.connectM365()}
          >
            Microsoft 365 verbinden
          </button>
        </div>
      )}

      {isConnected && (
        <>
          {/* Tab-Navigation */}
          <div className={styles.tabBar}>
            {TAB_LABELS.map((tab) => (
              <button
                key={tab.id}
                type="button"
                className={`${styles.tab} ${activeTab === tab.id ? styles.activeTab : ''}`}
                onClick={() => setActiveTab(tab.id)}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {/* Tab-Inhalt */}
          <div className={styles.tabContent}>
            {activeTab === 'emails' && <EmailsList />}
            {activeTab === 'calendar' && <CalendarList />}
            {activeTab === 'contacts' && <ContactsList />}
            {activeTab === 'tasks' && <TasksList />}
          </div>
        </>
      )}
    </div>
  );
}
