'use client';

import { useState, useEffect, useCallback } from 'react';
import { Phone, Users, CheckCircle2, Clock, AlertTriangle } from 'lucide-react';
import { cn } from '../utils';
import { useCrmApi } from '../context';
import type { ActivityData } from '../types';

interface ActivityListProps {
  entityType: string;
  entityId: string;
}

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

export function ActivityList({ entityType, entityId }: ActivityListProps) {
  const api = useCrmApi();
  const [activities, setActivities] = useState<ActivityData[]>([]);
  const [loading, setLoading] = useState(true);

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

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

  const handleComplete = async (id: string) => {
    try {
      await api.post(`/crm/activities/${id}/complete`, {});
      await fetchActivities();
    } catch {
      //
    }
  };

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

  return (
    <div className="space-y-2">
      {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={() => void handleComplete(activity.id)}
                className="px-3 py-1.5 text-xs bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shrink-0"
              >
                Выполнить
              </button>
            )}
          </div>
        );
      })}

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