import { useState } from 'react';
import { useCompanyActivities, useCreateActivity } from '../hooks';
import type { Activity, ActivityType } from '../types';
import styles from './CompanyDetailPage.module.css';

// ============================================================
//  Constants
// ============================================================

const ACTIVITY_TYPE_LABELS: Record<ActivityType, string> = {
  NOTE: 'Notiz',
  CALL: 'Anruf',
  EMAIL: 'E-Mail',
  MEETING: 'Meeting',
  TASK: 'Aufgabe',
  FOLLOWUP: 'Follow-Up',
};

const iconSvgProps = {
  width: 14,
  height: 14,
  stroke: 'currentColor',
  fill: 'none',
  strokeWidth: 1.5,
  strokeLinecap: 'round' as const,
  strokeLinejoin: 'round' as const,
};

function ActivityIcon({ type }: { type: ActivityType }) {
  switch (type) {
    case 'NOTE':
      return (
        <svg {...iconSvgProps} viewBox="0 0 16 16">
          <rect x="2" y="2" width="12" height="12" rx="1" />
          <path d="M5 5h6M5 8h6M5 11h3" />
        </svg>
      );
    case 'CALL':
      return (
        <svg {...iconSvgProps} viewBox="0 0 16 16">
          <path d="M3 2h3l1.5 3L6 6.5c.7 1.4 2.1 2.8 3.5 3.5L11 8.5l3 1.5v3a1 1 0 01-1 1C7 14 2 9 2 3a1 1 0 011-1z" />
        </svg>
      );
    case 'EMAIL':
      return (
        <svg {...iconSvgProps} viewBox="0 0 16 16">
          <rect x="1" y="3" width="14" height="10" rx="1" />
          <path d="M1 4l7 5 7-5" />
        </svg>
      );
    case 'MEETING':
      return (
        <svg {...iconSvgProps} viewBox="0 0 16 16">
          <circle cx="5" cy="5" r="2" />
          <circle cx="11" cy="5" r="2" />
          <path d="M1 12c0-2 2-3 4-3s4 1 4 3M7 12c0-2 2-3 4-3s4 1 4 3" />
        </svg>
      );
    case 'TASK':
      return (
        <svg {...iconSvgProps} viewBox="0 0 16 16">
          <rect x="2" y="2" width="12" height="12" rx="1" />
          <path d="M5 8l2 2 4-4" />
        </svg>
      );
    default:
      return null;
  }
}

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

function contactDisplayName(a: Activity): string | null {
  if (!a.contact) return null;
  const parts = [a.contact.firstName, a.contact.lastName].filter(Boolean);
  return parts.length > 0 ? parts.join(' ') : a.contact.companyName ?? null;
}

// ============================================================
//  Feed Tabs
// ============================================================

type FeedTab = 'NOTE' | 'EMAIL' | 'TASK';

const FEED_TABS: { key: FeedTab; label: string; enabled: boolean }[] = [
  { key: 'NOTE', label: 'Notiz', enabled: true },
  { key: 'EMAIL', label: 'E-Mail', enabled: false },
  { key: 'TASK', label: 'Aufgabe', enabled: false },
];

// ============================================================
//  Component
// ============================================================

interface ActivityFeedProps {
  companyId: string;
}

export function ActivityFeed({ companyId }: ActivityFeedProps) {
  const { data, isLoading } = useCompanyActivities(companyId);
  const createMut = useCreateActivity();

  const [activeTab, setActiveTab] = useState<FeedTab>('NOTE');
  const [subject, setSubject] = useState('');
  const [description, setDescription] = useState('');

  const activities: Activity[] = data?.data ?? [];

  const handleSubmit = () => {
    if (!subject.trim()) return;
    createMut.mutate(
      {
        companyId,
        type: activeTab as ActivityType,
        subject: subject.trim(),
        ...(description.trim() ? { description: description.trim() } : {}),
      },
      {
        onSuccess: () => {
          setSubject('');
          setDescription('');
        },
      },
    );
  };

  return (
    <div className={styles.card}>
      <h2 className={styles.cardTitle}>Aktivitäten</h2>

      {/* Input Area */}
      <div className={styles.feedInputArea}>
        <div className={styles.feedTabs}>
          {FEED_TABS.map((tab) => (
            <button
              key={tab.key}
              className={`${styles.feedTab} ${activeTab === tab.key ? styles.feedTabActive : ''}`}
              onClick={() => tab.enabled && setActiveTab(tab.key)}
              disabled={!tab.enabled}
              style={!tab.enabled ? { opacity: 0.4, cursor: 'not-allowed' } : undefined}
              title={!tab.enabled ? 'Bald verfügbar' : undefined}
            >
              {tab.label}
            </button>
          ))}
        </div>

        <div className={styles.feedForm}>
          <input
            className={styles.feedSubjectInput}
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            placeholder="Betreff..."
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSubmit();
              }
            }}
          />
          <textarea
            className={styles.feedTextarea}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Beschreibung (optional)..."
            rows={2}
          />
          <div className={styles.feedSubmitRow}>
            <button
              className={styles.feedSubmitBtn}
              onClick={handleSubmit}
              disabled={!subject.trim() || createMut.isPending}
            >
              {createMut.isPending ? 'Speichern...' : 'Hinzufügen'}
            </button>
          </div>
        </div>
      </div>

      {/* Activity List */}
      {isLoading ? (
        <p style={{ color: 'var(--color-text-muted)', fontSize: '0.875rem' }}>
          Laden...
        </p>
      ) : activities.length === 0 ? (
        <div className={styles.feedEmpty}>
          Noch keine Aktivitäten vorhanden
        </div>
      ) : (
        <div className={styles.feedList}>
          {activities.map((activity) => {
            const viaName = contactDisplayName(activity);
            return (
              <div key={activity.id} className={styles.feedItem}>
                <div className={styles.feedIcon}>
                  <ActivityIcon type={activity.type} />
                </div>
                <div className={styles.feedContent}>
                  <div className={styles.feedSubject}>{activity.subject}</div>
                  <div className={styles.feedMeta}>
                    <span>{ACTIVITY_TYPE_LABELS[activity.type]}</span>
                    <span>·</span>
                    <span>{formatDateTime(activity.createdAt)}</span>
                    {viaName && activity.contactId && !activity.companyId && (
                      <span className={styles.feedViaBadge}>
                        via {viaName}
                      </span>
                    )}
                  </div>
                  {activity.description && (
                    <div className={styles.feedDesc}>
                      {activity.description}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
