'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  MessageSquare,
  Phone,
  ArrowRightLeft,
  FileText,
  CheckCircle2,
  Dumbbell,
  Pin,
  Send,
  Settings2,
} from 'lucide-react';
import { cn } from '../utils';
import { useCrmApi } from '../context';
import type { EntityConfig, TimelineEntryData } from '../types';

interface TimelineFeedProps {
  config: EntityConfig;
  entityId: string;
}

const typeConfig: Record<string, { icon: typeof MessageSquare; 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({ config, entityId }: TimelineFeedProps) {
  const api = useCrmApi();
  const [entries, setEntries] = useState<TimelineEntryData[]>([]);
  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: TimelineEntryData[] }>(
        `${config.apiPrefix}/${entityId}/timeline`,
      );
      setEntries(res.data);
    } catch {
      //
    } finally {
      setLoading(false);
    }
  }, [api, config.apiPrefix, entityId]);

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

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

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

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

  return (
    <div>
      <div className="flex gap-2 mb-4">
        <input
          type="text"
          value={comment}
          onChange={(e) => setComment(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') void 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={() => void 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>

      {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={() => void handlePin(entry.id, true)}
              />
            ))}
        </div>
      )}

      <div className="space-y-3">
        {entries
          .filter((e) => !e.pinnedAt)
          .map((entry) => (
            <TimelineItem
              key={entry.id}
              entry={entry}
              onPin={() => void 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: TimelineEntryData;
  pinned?: boolean;
  onPin: () => void;
}) {
  const cfg = (typeConfig[entry.type] ?? typeConfig.SYSTEM)!;
  const Icon = cfg.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', cfg.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">{cfg.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>
  );
}
