'use client';

import { useState, useEffect, useCallback } from 'react';
import { Phone, Users, CheckCircle2, Clock, AlertTriangle, Plus, X } from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';

interface Activity {
  id: string;
  type: string;
  subject: string;
  description?: string;
  scheduledAt: string;
  completedAt?: string | null;
  result?: string | null;
  isOverdue?: boolean;
  assignee?: { firstName: string; lastName: string } | null;
  completedBy?: { firstName: string; lastName: string } | null;
}

interface ActivityListProps {
  dealId: string;
  onTimelineChanged?: () => void;
}

const typeIcons: Record<string, any> = {
  CALL: Phone,
  MEETING: Users,
  TASK: CheckCircle2,
  EMAIL: Clock,
};

const typeLabels: Record<string, string> = {
  CALL: 'Звонок',
  MEETING: 'Встреча',
  TASK: 'Задача',
  EMAIL: 'Email',
};

const inputClass =
  'w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 bg-background text-text';

export function ActivityList({ dealId, onTimelineChanged }: ActivityListProps) {
  const [activities, setActivities] = useState<Activity[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [formType, setFormType] = useState('CALL');
  const [formSubject, setFormSubject] = useState('');
  const [formScheduledAt, setFormScheduledAt] = useState('');
  const [formDescription, setFormDescription] = useState('');
  const [creating, setCreating] = useState(false);

  const fetchActivities = useCallback(async () => {
    try {
      const res = await api.get<{ data: Activity[] }>(`/crm/activities/deal/${dealId}`);
      setActivities(res.data);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, [dealId]);

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

  const [completingId, setCompletingId] = useState<string | null>(null);

  const handleComplete = async (id: string) => {
    if (completingId) return;
    setCompletingId(id);
    try {
      await api.post(`/crm/activities/${id}/complete`, {});
      await fetchActivities();
      onTimelineChanged?.();
    } catch {
      // ignore
    } finally {
      setCompletingId(null);
    }
  };

  const handleCreate = async () => {
    if (!formSubject.trim() || !formScheduledAt) return;
    setCreating(true);
    try {
      await api.post('/crm/activities', {
        dealId,
        type: formType,
        subject: formSubject.trim(),
        scheduledAt: new Date(formScheduledAt).toISOString(),
        description: formDescription.trim() || undefined,
      });
      await fetchActivities();
      onTimelineChanged?.();
      setShowForm(false);
      setFormSubject('');
      setFormScheduledAt('');
      setFormDescription('');
      setFormType('CALL');
    } catch {
      // ignore
    } finally {
      setCreating(false);
    }
  };

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

  return (
    <div className="space-y-2">
      {/* Add activity button / form */}
      {!showForm ? (
        <button
          onClick={() => setShowForm(true)}
          className="flex items-center gap-1.5 px-3 py-2 text-sm text-primary hover:bg-primary/5 rounded-lg transition-colors"
        >
          <Plus className="h-4 w-4" />
          Добавить дело
        </button>
      ) : (
        <div className="border border-border rounded-lg p-3 space-y-3 bg-card">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium text-text">Новое дело</span>
            <button onClick={() => setShowForm(false)} className="p-1 hover:bg-background rounded">
              <X className="h-4 w-4 text-muted" />
            </button>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-[10px] text-muted mb-0.5">Тип</label>
              <select
                value={formType}
                onChange={(e) => setFormType(e.target.value)}
                className={inputClass}
              >
                {Object.entries(typeLabels).map(([key, label]) => (
                  <option key={key} value={key}>
                    {label}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-[10px] text-muted mb-0.5">Дата/время *</label>
              <input
                type="datetime-local"
                value={formScheduledAt}
                onChange={(e) => setFormScheduledAt(e.target.value)}
                className={inputClass}
              />
            </div>
          </div>
          <div>
            <label className="block text-[10px] text-muted mb-0.5">Тема *</label>
            <input
              type="text"
              value={formSubject}
              onChange={(e) => setFormSubject(e.target.value)}
              placeholder="Тема дела..."
              className={inputClass}
            />
          </div>
          <div>
            <label className="block text-[10px] text-muted mb-0.5">Описание</label>
            <input
              type="text"
              value={formDescription}
              onChange={(e) => setFormDescription(e.target.value)}
              placeholder="Необязательно"
              className={inputClass}
            />
          </div>
          <div className="flex gap-2 justify-end">
            <button
              onClick={() => setShowForm(false)}
              className="px-3 py-1.5 text-xs text-muted hover:text-text transition-colors"
            >
              Отмена
            </button>
            <button
              onClick={handleCreate}
              disabled={creating || !formSubject.trim() || !formScheduledAt}
              className="px-3 py-1.5 text-xs bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50"
            >
              {creating ? 'Создание...' : 'Создать'}
            </button>
          </div>
        </div>
      )}

      {activities.map((activity) => {
        const Icon = typeIcons[activity.type] || Clock;
        const isCompleted = !!activity.completedAt;
        const isOverdue = !isCompleted && new Date(activity.scheduledAt) < new Date();

        return (
          <div
            key={activity.id}
            className={cn(
              'flex items-center gap-3 p-3 rounded-lg border transition-colors',
              isCompleted
                ? 'border-border/30 bg-background/30 opacity-60'
                : isOverdue
                  ? 'border-error/30 bg-error/5'
                  : 'border-border hover:bg-background/50',
            )}
          >
            <div
              className={cn(
                'h-8 w-8 rounded-full flex items-center justify-center shrink-0',
                isCompleted
                  ? 'bg-green-100 text-green-600'
                  : isOverdue
                    ? 'bg-red-100 text-red-600'
                    : 'bg-primary/10 text-primary',
              )}
            >
              {isCompleted ? (
                <CheckCircle2 className="h-4 w-4" />
              ) : isOverdue ? (
                <AlertTriangle className="h-4 w-4" />
              ) : (
                <Icon className="h-4 w-4" />
              )}
            </div>

            <div className="flex-1 min-w-0">
              <div className="text-sm font-medium text-text truncate">{activity.subject}</div>
              <div className="flex items-center gap-2 text-xs text-muted">
                <span>
                  {new Date(activity.scheduledAt).toLocaleString('ru-RU', {
                    day: '2-digit',
                    month: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                  })}
                </span>
                {activity.assignee && (
                  <span>
                    {activity.assignee.firstName} {activity.assignee.lastName?.[0]}.
                  </span>
                )}
              </div>
              {activity.result && (
                <div className="text-xs text-muted mt-1">Результат: {activity.result}</div>
              )}
            </div>

            {!isCompleted && (
              <button
                onClick={() => handleComplete(activity.id)}
                disabled={!!completingId}
                className="px-3 py-1.5 text-xs bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shrink-0 disabled:opacity-50"
              >
                {completingId === activity.id ? 'Загрузка...' : 'Выполнить'}
              </button>
            )}
          </div>
        );
      })}

      {activities.length === 0 && !showForm && (
        <div className="text-center py-8 text-muted text-sm">Нет запланированных дел</div>
      )}
    </div>
  );
}
