'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  MessageSquare,
  Phone,
  ArrowRightLeft,
  FileText,
  CheckCircle2,
  Dumbbell,
  Pin,
  Send,
  Settings2,
} from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';

interface TimelineEntry {
  id: string;
  type: string;
  subject?: string;
  content?: string;
  metadata?: Record<string, any>;
  pinnedAt?: string | null;
  user?: { id: string; firstName: string; lastName: string } | null;
  createdAt: string;
}

interface TimelineFeedProps {
  dealId: string;
  refreshKey?: number;
}

const typeConfig: Record<string, { icon: any; color: string; label: string }> = {
  COMMENT: { icon: MessageSquare, color: 'text-blue-500 bg-blue-100', label: 'Комментарий' },
  CALL: { icon: Phone, color: 'text-green-500 bg-green-100', label: 'Звонок' },
  STAGE_CHANGE: {
    icon: ArrowRightLeft,
    color: 'text-purple-500 bg-purple-100',
    label: 'Смена стадии',
  },
  FORM_SUBMISSION: { icon: FileText, color: 'text-orange-500 bg-orange-100', label: 'Заявка' },
  ACTIVITY_CREATED: { icon: Settings2, color: 'text-cyan-500 bg-cyan-100', label: 'Дело создано' },
  ACTIVITY_DONE: {
    icon: CheckCircle2,
    color: 'text-green-500 bg-green-100',
    label: 'Дело выполнено',
  },
  TRAINING_CREATED: { icon: Dumbbell, color: 'text-indigo-500 bg-indigo-100', label: 'Тренировка' },
  MESSAGE: { icon: Send, color: 'text-sky-500 bg-sky-100', label: 'Сообщение' },
  SYSTEM: { icon: Settings2, color: 'text-gray-500 bg-gray-100', label: 'Система' },
};

export function TimelineFeed({ dealId, refreshKey }: TimelineFeedProps) {
  const [entries, setEntries] = useState<TimelineEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [comment, setComment] = useState('');
  const [sending, setSending] = useState(false);

  const fetchTimeline = useCallback(async () => {
    try {
      const res = await api.get<{ data: TimelineEntry[] }>(`/crm/deals/${dealId}/timeline`);
      setEntries(res.data);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, [dealId]);

  useEffect(() => {
    void fetchTimeline();
  }, [fetchTimeline, refreshKey]);

  const handleAddComment = async () => {
    if (!comment.trim()) return;
    setSending(true);
    try {
      await api.post(`/crm/deals/${dealId}/timeline/comment`, {
        content: comment.trim(),
      });
      setComment('');
      await fetchTimeline();
    } catch {
      // ignore
    } finally {
      setSending(false);
    }
  };

  const handlePin = async (id: string, pinned: boolean) => {
    try {
      await api.patch(`/crm/deals/${dealId}/timeline/${id}/${pinned ? 'unpin' : 'pin'}`);
      await fetchTimeline();
    } catch {
      // ignore
    }
  };

  if (loading) {
    return <div className="text-center py-8 text-muted text-sm">Загрузка таймлайна...</div>;
  }

  return (
    <div>
      {/* Comment input */}
      <div className="flex gap-2 mb-4">
        <input
          type="text"
          value={comment}
          onChange={(e) => setComment(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleAddComment()}
          placeholder="Написать комментарий..."
          className="flex-1 px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary bg-background text-text"
        />
        <button
          onClick={handleAddComment}
          disabled={sending || !comment.trim()}
          className="px-3 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 disabled:opacity-50 transition-colors"
        >
          <Send className="h-4 w-4" />
        </button>
      </div>

      {/* Pinned entries */}
      {entries.filter((e) => e.pinnedAt).length > 0 && (
        <div className="mb-4 space-y-2">
          {entries
            .filter((e) => e.pinnedAt)
            .map((entry) => (
              <TimelineItem
                key={`pinned-${entry.id}`}
                entry={entry}
                pinned
                onPin={() => handlePin(entry.id, true)}
              />
            ))}
        </div>
      )}

      {/* Timeline entries */}
      <div className="space-y-3">
        {entries
          .filter((e) => !e.pinnedAt)
          .map((entry) => (
            <TimelineItem key={entry.id} entry={entry} onPin={() => handlePin(entry.id, false)} />
          ))}
        {entries.length === 0 && (
          <div className="text-center py-8 text-muted text-sm">Пока нет записей в таймлайне</div>
        )}
      </div>
    </div>
  );
}

function TimelineItem({
  entry,
  pinned,
  onPin,
}: {
  entry: TimelineEntry;
  pinned?: boolean;
  onPin: () => void;
}) {
  const cfg = typeConfig[entry.type] ?? typeConfig.SYSTEM;
  const config = cfg ?? {
    icon: MessageSquare,
    label: 'Событие',
    color: 'bg-gray-100 text-gray-600',
  };
  const Icon = config.icon;

  return (
    <div
      className={cn(
        'flex gap-3 p-3 rounded-lg border transition-colors',
        pinned ? 'border-primary/30 bg-primary/5' : 'border-border/50 hover:bg-background/50',
      )}
    >
      <div
        className={cn(
          'h-8 w-8 rounded-full flex items-center justify-center shrink-0',
          config.color,
        )}
      >
        <Icon className="h-4 w-4" />
      </div>
      <div className="flex-1 min-w-0">
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-2 min-w-0">
            {entry.subject && (
              <span className="text-sm font-medium text-text truncate">{entry.subject}</span>
            )}
            <span className="text-[10px] text-muted shrink-0">{config.label}</span>
          </div>
          <div className="flex items-center gap-1 shrink-0">
            <button
              onClick={onPin}
              className="p-1 rounded hover:bg-background/50 text-muted hover:text-text transition-colors"
              title={pinned ? 'Открепить' : 'Закрепить'}
            >
              <Pin className={cn('h-3 w-3', pinned && 'fill-current text-primary')} />
            </button>
            <span className="text-[10px] text-muted">
              {new Date(entry.createdAt).toLocaleString('ru-RU', {
                day: '2-digit',
                month: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
              })}
            </span>
          </div>
        </div>
        {entry.content && <p className="text-sm text-muted mt-1">{entry.content}</p>}
        {entry.user && (
          <span className="text-[10px] text-muted mt-1 inline-block">
            {entry.user.firstName} {entry.user.lastName}
          </span>
        )}
        {entry.type === 'STAGE_CHANGE' && entry.metadata && (
          <div className="text-xs text-muted mt-1">
            {entry.metadata.fromStageName} → {entry.metadata.toStageName}
          </div>
        )}
      </div>
    </div>
  );
}
