import React, { memo, useMemo, useState } from "react";

function EventsTab({ accountEvents, formatTimestamp, onClearEvents }) {
  const [typeFilter, setTypeFilter] = useState("all");
  const [query, setQuery] = useState("");

  const eventTypes = useMemo(() => {
    const types = new Set(accountEvents.map((event) => event.eventType));
    return ["all", ...Array.from(types)];
  }, [accountEvents]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return accountEvents.filter((event) => {
      if (typeFilter !== "all" && event.eventType !== typeFilter) return false;
      if (!q) return true;
      const text = [event.eventType, event.message, event.phone, event.accountId]
        .join(" ")
        .toLowerCase();
      return text.includes(q);
    });
  }, [accountEvents, typeFilter, query]);

  return (
    <section className="card logs">
      <div className="row-header">
        <h2>События аккаунтов</h2>
        <button type="button" className="danger" onClick={onClearEvents}>Сбросить</button>
      </div>
      <div className="row-inline column">
        <input
          type="text"
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          placeholder="Поиск по событиям"
        />
        <div className="task-filters">
          {eventTypes.map((type) => (
            <button
              key={type}
              type="button"
              className={`chip ${typeFilter === type ? "active" : ""}`}
              onClick={() => setTypeFilter(type)}
            >
              {type === "all" ? "Все" : type}
            </button>
          ))}
        </div>
      </div>
      {filtered.length === 0 && <div className="empty">Событий нет.</div>}
      {filtered.map((event) => (
        <div key={event.id} className="log-row">
          <div className="log-time">
            <div>{formatTimestamp(event.createdAt)}</div>
            <div>{event.eventType}</div>
          </div>
          <div className="log-details">
            <div>Аккаунт: {event.phone || event.accountId}</div>
            <div className="log-errors">{event.message}</div>
          </div>
        </div>
      ))}
    </section>
  );
}

export default memo(EventsTab);
