import { useMemo, useState } from "react";

const createPager = (items, page, pageSize) => {
  const pageCount = Math.max(1, Math.ceil(items.length / pageSize));
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  return { pageCount, paged: items.slice(start, end) };
};

export default function useLogsView({
  logs,
  invites,
  fallbackList,
  taskAudit,
  confirmQueue,
  queueItems
}) {
  const [logSearch, setLogSearch] = useState("");
  const [inviteSearch, setInviteSearch] = useState("");
  const [fallbackSearch, setFallbackSearch] = useState("");
  const [auditSearch, setAuditSearch] = useState("");
  const [confirmSearch, setConfirmSearch] = useState("");
  const [logPage, setLogPage] = useState(1);
  const [invitePage, setInvitePage] = useState(1);
  const [fallbackPage, setFallbackPage] = useState(1);
  const [auditPage, setAuditPage] = useState(1);
  const [confirmPage, setConfirmPage] = useState(1);
  const [inviteFilter, setInviteFilter] = useState("all");
  const [queueSearch, setQueueSearch] = useState("");
  const [queuePage, setQueuePage] = useState(1);

  const filteredLogs = useMemo(() => {
    const query = logSearch.trim().toLowerCase();
    if (!query) return logs;
    return logs.filter((log) => {
      const text = [
        log.startedAt,
        log.finishedAt,
        String(log.invitedCount),
        (log.successIds || []).join(","),
        (log.errors || []).join("|")
      ]
        .join(" ")
        .toLowerCase();
      return text.includes(query);
    });
  }, [logs, logSearch]);

  const filteredInvites = useMemo(() => {
    const query = inviteSearch.trim().toLowerCase();
    return invites.filter((invite) => {
      if (inviteFilter === "success" && invite.status !== "success") return false;
      if (inviteFilter === "error" && invite.status !== "failed") return false;
      if (inviteFilter === "skipped" && invite.status !== "skipped") return false;
      if (inviteFilter === "unconfirmed" && invite.status !== "unconfirmed") return false;
      const text = [
        invite.invitedAt,
        invite.userId,
        invite.username,
        invite.sourceChat,
        invite.accountPhone,
        invite.watcherPhone,
        invite.strategy,
        invite.strategyMeta,
        invite.error,
        invite.skippedReason,
        invite.confirmError
      ]
        .join(" ")
        .toLowerCase();
      if (!query) return true;
      return text.includes(query);
    });
  }, [invites, inviteSearch, inviteFilter]);

  const filteredFallback = useMemo(() => {
    const query = fallbackSearch.trim().toLowerCase();
    return fallbackList.filter((item) => {
      const text = [
        item.userId,
        item.username,
        item.reason,
        item.route,
        item.sourceChat,
        item.targetChat,
        item.status,
        item.createdAt
      ]
        .join(" ")
        .toLowerCase();
      if (!query) return true;
      return text.includes(query);
    });
  }, [fallbackList, fallbackSearch]);

  const filteredConfirmQueue = useMemo(() => {
    const query = confirmSearch.trim().toLowerCase();
    if (!query) return confirmQueue;
    return confirmQueue.filter((item) => {
      const text = [
        item.user_id,
        item.username,
        item.account_id,
        item.watcher_account_id,
        item.last_error,
        item.next_check_at
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();
      return text.includes(query);
    });
  }, [confirmQueue, confirmSearch]);

  const filteredAudit = useMemo(() => {
    const query = auditSearch.trim().toLowerCase();
    if (!query) return taskAudit;
    return taskAudit.filter((item) => {
      const text = [item.action, item.details, item.createdAt].join(" ").toLowerCase();
      return text.includes(query);
    });
  }, [taskAudit, auditSearch]);
  const filteredQueue = useMemo(() => {
    const query = queueSearch.trim().toLowerCase();
    if (!query) return queueItems || [];
    return (queueItems || []).filter((item) => {
      const text = [
        item.user_id,
        item.username,
        item.source_chat,
        item.watcher_account_id,
        item.attempts,
        item.created_at
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();
      return text.includes(query);
    });
  }, [queueItems, queueSearch]);

  const inviteStrategyStats = useMemo(() => {
    let success = 0;
    let failed = 0;
    invites.forEach((invite) => {
      if (!invite.strategyMeta) return;
      try {
        const parsed = JSON.parse(invite.strategyMeta);
        if (!Array.isArray(parsed) || !parsed.length) return;
        const hasOk = parsed.some((item) => item.ok);
        if (hasOk) success += 1;
        else failed += 1;
      } catch (error) {
        // ignore parse errors
      }
    });
    return { success, failed };
  }, [invites]);

  const inviteStats = useMemo(() => {
    const stats = {
      total: invites.length,
      success: 0,
      failed: 0,
      skipped: 0,
      unconfirmed: 0
    };
    invites.forEach((invite) => {
      switch (invite.status) {
        case "success":
          stats.success += 1;
          break;
        case "failed":
          stats.failed += 1;
          break;
        case "skipped":
          stats.skipped += 1;
          break;
        case "unconfirmed":
          stats.unconfirmed += 1;
          break;
        default:
          break;
      }
    });
    return stats;
  }, [invites]);

  const logPageSize = 20;
  const invitePageSize = 20;
  const fallbackPageSize = 20;
  const auditPageSize = 20;
  const confirmPageSize = 20;
  const queuePageSize = 20;

  const { pageCount: logPageCount, paged: pagedLogs } = createPager(filteredLogs, logPage, logPageSize);
  const { pageCount: invitePageCount, paged: pagedInvites } = createPager(filteredInvites, invitePage, invitePageSize);
  const { pageCount: fallbackPageCount, paged: pagedFallback } = createPager(filteredFallback, fallbackPage, fallbackPageSize);
  const { pageCount: auditPageCount, paged: pagedAudit } = createPager(filteredAudit, auditPage, auditPageSize);
  const { pageCount: confirmPageCount, paged: pagedConfirmQueue } = createPager(filteredConfirmQueue, confirmPage, confirmPageSize);
  const { pageCount: queuePageCount, paged: pagedQueue } = createPager(filteredQueue, queuePage, queuePageSize);

  const mutualContactDiagnostics = useMemo(() => {
    const items = invites
      .filter((invite) => invite.error === "USER_NOT_MUTUAL_CONTACT")
      .slice()
      .sort((a, b) => (b.invitedAt || "").localeCompare(a.invitedAt || ""));
    return {
      count: items.length,
      recent: items.slice(0, 5)
    };
  }, [invites]);

  return {
    logSearch,
    setLogSearch,
    inviteSearch,
    setInviteSearch,
    fallbackSearch,
    setFallbackSearch,
    auditSearch,
    setAuditSearch,
    confirmSearch,
    setConfirmSearch,
    logPage,
    setLogPage,
    invitePage,
    setInvitePage,
    fallbackPage,
    setFallbackPage,
    auditPage,
    setAuditPage,
    confirmPage,
    setConfirmPage,
    queueSearch,
    setQueueSearch,
    queuePage,
    setQueuePage,
    inviteFilter,
    setInviteFilter,
    filteredLogs,
    filteredInvites,
    filteredFallback,
    filteredAudit,
    filteredConfirmQueue,
    logPageCount,
    invitePageCount,
    fallbackPageCount,
    auditPageCount,
    confirmPageCount,
    queuePageCount,
    pagedLogs,
    pagedInvites,
    pagedFallback,
    pagedAudit,
    pagedConfirmQueue,
    pagedQueue,
    inviteStrategyStats,
    inviteStats,
    mutualContactDiagnostics
  };
}
