import { useContactTasks, useIntegrations } from '../hooks';
import { integrationsApi } from '../api';
import type { M365Task, M365TaskList } from '../types';

interface Props {
  contactId: string;
}

const TASK_STATUS_LABELS: Record<M365Task['status'], string> = {
  notStarted: 'Offen',
  inProgress: 'In Bearbeitung',
  completed: 'Erledigt',
  waitingOnOthers: 'Wartet',
  deferred: 'Zurückgestellt',
};

const TASK_STATUS_COLORS: Record<M365Task['status'], { bg: string; color: string }> = {
  notStarted: { bg: '#f1f5f9', color: '#475569' },
  inProgress: { bg: '#dbeafe', color: '#1e40af' },
  completed: { bg: '#d1fae5', color: '#065f46' },
  waitingOnOthers: { bg: '#fef9c3', color: '#854d0e' },
  deferred: { bg: '#f1f5f9', color: '#94a3b8' },
};

const IMPORTANCE_COLORS: Record<M365Task['importance'], string> = {
  low: 'var(--color-text-muted)',
  normal: 'var(--color-text-secondary)',
  high: 'var(--color-error, #ef4444)',
};

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

function TaskItem({ task }: { task: M365Task }) {
  const status = TASK_STATUS_COLORS[task.status];
  const isCompleted = task.status === 'completed';

  return (
    <div style={{
      display: 'flex',
      alignItems: 'flex-start',
      gap: '0.75rem',
      padding: '0.625rem 0',
      borderBottom: '1px solid var(--color-border)',
      opacity: isCompleted ? 0.6 : 1,
    }}>
      <div style={{
        width: 14,
        height: 14,
        borderRadius: '50%',
        border: `2px solid ${isCompleted ? '#16a34a' : 'var(--color-border)'}`,
        background: isCompleted ? '#16a34a' : 'transparent',
        flexShrink: 0,
        marginTop: 2,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
        {isCompleted && (
          <svg width="8" height="8" viewBox="0 0 8 8" fill="white">
            <path d="M1 4l2 2 4-4" stroke="white" strokeWidth="1.5" fill="none" strokeLinecap="round" />
          </svg>
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: '0.875rem',
          fontWeight: 500,
          color: 'var(--color-text)',
          textDecoration: isCompleted ? 'line-through' : undefined,
        }}>
          {task.title}
        </div>
        <div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.25rem', flexWrap: 'wrap', alignItems: 'center' }}>
          <span style={{
            fontSize: '0.6875rem',
            fontWeight: 600,
            padding: '0.125rem 0.375rem',
            borderRadius: '999px',
            ...status,
          }}>
            {TASK_STATUS_LABELS[task.status]}
          </span>
          {task.importance !== 'normal' && (
            <span style={{ fontSize: '0.75rem', color: IMPORTANCE_COLORS[task.importance], fontWeight: 600 }}>
              {task.importance === 'high' ? '↑ Hoch' : '↓ Niedrig'}
            </span>
          )}
          {task.dueDateTime && (
            <span style={{ fontSize: '0.75rem', color: 'var(--color-text-muted)' }}>
              Fällig: {formatDueDate(task.dueDateTime.dateTime)}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

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

  const { data, isLoading, error } = useContactTasks(contactId);
  const taskLists: M365TaskList[] = data?.data ?? [];

  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 Aufgaben 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' }}>Aufgaben konnten nicht geladen werden.</p>;
  }

  const allTasks = taskLists.flatMap((list) => list.tasks);

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

  return (
    <div>
      {taskLists.map((list) =>
        list.tasks.length > 0 ? (
          <div key={list.id} style={{ marginBottom: '1rem' }}>
            <div style={{
              fontSize: '0.8125rem',
              fontWeight: 600,
              color: 'var(--color-text-muted)',
              textTransform: 'uppercase',
              letterSpacing: '0.04em',
              marginBottom: '0.25rem',
            }}>
              {list.displayName}
            </div>
            {list.tasks.map((task) => (
              <TaskItem key={task.id} task={task} />
            ))}
          </div>
        ) : null,
      )}
    </div>
  );
}
