// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * ConversationsPage — Communication Center, live.
 *
 * Data source: customer-api conversations module via TanStack Query.
 * - Inbox list: 5 s poll, paused while tab hidden, immediate refetch on visible.
 * - Selected conversation detail: 3 s poll under same visibility rules.
 * - Queue counts: 5 s poll, drives QueueMetricsHeader.
 *
 * No mock data, no demo banner — every count, badge, status, avatar, and
 * page-trail item is wired to the DB row served by /conversations.
 */

import { useEffect, useMemo, useState } from 'react';
import { MessagesSquare, Search } from 'lucide-react';
import { PageLayout } from '@/components/shared';
import { useTranslation } from '@/i18n/TranslationProvider';
import { useTenants } from '@/features/tenants/hooks';
import { ConversationListItem } from './components/ConversationListItem';
import { ConversationDetail } from './components/ConversationDetail';
import { VisitorContextPanel } from './components/VisitorContextPanel';
import { QueueMetricsHeader } from './components/QueueMetricsHeader';
import { OperatorAvailabilityToggle } from './components/OperatorAvailabilityToggle';
import {
  useConversationsList,
  useConversationDetail,
  useQueueCounts,
  useInterceptMutation,
  useReleaseMutation,
  useSendMessageMutation,
  useMarkSeenMutation,
} from './hooks/useConversations';
import type { ConversationStatus, ListFilter } from './lib/types';

const ALL_TENANTS = '__all__';
const STATUS_FILTERS: (ConversationStatus | 'all')[] = ['all', 'active', 'intercepted', 'idle', 'closed'];

export function ConversationsPage() {
  const { t } = useTranslation();
  const tenantsQuery = useTenants();
  const tenants = tenantsQuery.data?.tenants ?? [];

  const [tenantFilter, setTenantFilter] = useState<string>(ALL_TENANTS);
  const [statusFilter, setStatusFilter] = useState<ConversationStatus | 'all'>('all');
  const [search, setSearch] = useState<string>('');
  const [selectedId, setSelectedId] = useState<string | null>(null);

  const listFilter: ListFilter = {
    tenantId: tenantFilter === ALL_TENANTS ? undefined : tenantFilter,
    status: statusFilter,
  };

  const listQuery = useConversationsList(listFilter);
  const countsQuery = useQueueCounts(tenantFilter === ALL_TENANTS ? undefined : tenantFilter);
  const detailQuery = useConversationDetail(selectedId);

  const intercept = useInterceptMutation();
  const release = useReleaseMutation();
  const sendMessage = useSendMessageMutation();
  const markSeen = useMarkSeenMutation();

  const items = listQuery.data?.conversations ?? [];
  const counts = countsQuery.data ?? {
    total: 0,
    active: 0,
    idle: 0,
    intercepted: 0,
    closed: 0,
    awaitingReply: 0,
    breaching: 0,
  };

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return [...items]
      .filter((c) => {
        if (!q) return true;
        if (c.visitorRef.toLowerCase().includes(q)) return true;
        if (c.tenantName.toLowerCase().includes(q)) return true;
        if (c.lastMessage?.content.toLowerCase().includes(q)) return true;
        return false;
      })
      .sort((a, b) => new Date(b.lastActivityAt).getTime() - new Date(a.lastActivityAt).getTime());
  }, [items, search]);

  useEffect(() => {
    if (!selectedId && filtered.length > 0) {
      setSelectedId(filtered[0].id);
    }
  }, [filtered, selectedId]);

  useEffect(() => {
    if (selectedId) markSeen.mutate(selectedId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedId]);

  const selected = detailQuery.data ?? null;

  return (
    <PageLayout
      title={t('conversations.title')}
      subtitle={t('conversations.subtitle')}
      icon={<MessagesSquare size={24} />}
      gradient
      maxWidth="full"
    >
      <div>
        <div className="flex flex-wrap items-center justify-between gap-3 mb-3" data-testid="comm-center-header">
          <QueueMetricsHeader counts={counts} />
          <OperatorAvailabilityToggle />
        </div>

        <div className="flex flex-wrap items-center gap-3 mb-3" data-testid="conversations-toolbar">
          <label htmlFor="tenant-filter" className="text-sm font-medium text-gray-700">
            {t('conversations.tenantLabel')}
          </label>
          <select
            id="tenant-filter"
            data-testid="tenant-filter-select"
            value={tenantFilter}
            onChange={(event) => setTenantFilter(event.target.value)}
            className="border border-gray-300 rounded-md px-3 py-1.5 text-sm bg-white min-w-[200px]"
          >
            <option value={ALL_TENANTS}>{t('conversations.allTenants')}</option>
            {tenants.map((tenant) => (
              <option key={tenant.id} value={tenant.id}>{tenant.name}</option>
            ))}
          </select>
          <div className="flex items-center gap-1" data-testid="status-filter">
            {STATUS_FILTERS.map((s) => (
              <button
                key={s}
                type="button"
                onClick={() => setStatusFilter(s)}
                data-testid={`status-filter-${s}`}
                className={`px-2.5 py-1 rounded-md text-xs font-medium transition-colors ${
                  statusFilter === s
                    ? 'bg-emerald-600 text-white'
                    : 'bg-white border border-gray-200 text-gray-600 hover:bg-gray-50'
                }`}
              >
                {t(`conversations.statusFilter.${s}`)}
              </button>
            ))}
          </div>
          <span className="text-xs text-gray-500 ml-auto" data-testid="filter-summary">
            {t('conversations.filterSummary', { shown: filtered.length, total: items.length })}
          </span>
        </div>
      </div>

      <div className="flex-1 min-h-0">
        <div
          className="
            bg-white border border-gray-200 rounded-lg overflow-hidden
            grid min-h-[640px]
            grid-cols-1
            md:grid-cols-[280px_1fr]
            lg:grid-cols-[320px_1fr]
            xl:grid-cols-[340px_1fr_300px]
            2xl:grid-cols-[380px_1fr_360px]
            min-[1920px]:grid-cols-[420px_1fr_400px]
            min-[2560px]:grid-cols-[480px_1fr_460px]
          "
          data-testid="comm-center"
        >
          <aside className="border-r border-gray-200 flex flex-col" data-testid="conv-list">
            <div className="border-b border-gray-200 p-3 bg-slate-50/40">
              <div className="relative">
                <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" />
                <input
                  type="search"
                  value={search}
                  onChange={(event) => setSearch(event.target.value)}
                  placeholder={t('conversations.searchPlaceholder')}
                  data-testid="conv-search"
                  className="w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-emerald-500 bg-white"
                />
              </div>
            </div>
            <div className="overflow-y-auto flex-1">
              {listQuery.isLoading ? (
                <div className="p-8 text-center text-sm text-gray-500" data-testid="conv-list-loading">
                  {t('conversations.listLoading')}
                </div>
              ) : filtered.length === 0 ? (
                <div className="p-8 text-center text-sm text-gray-500" data-testid="conv-list-empty">
                  {t('conversations.listEmpty')}
                </div>
              ) : (
                filtered.map((conv) => (
                  <ConversationListItem
                    key={conv.id}
                    conversation={conv}
                    selected={selectedId === conv.id}
                    onSelect={() => setSelectedId(conv.id)}
                  />
                ))
              )}
            </div>
          </aside>

          {selected ? (
            <ConversationDetail
              conversation={selected}
              onIntercept={() => intercept.mutate(selected.id)}
              onRelease={() => release.mutate(selected.id)}
              onSendOperatorMessage={(content) => sendMessage.mutate({ id: selected.id, content })}
            />
          ) : (
            <div className="flex items-center justify-center text-sm text-gray-500" data-testid="conv-detail-empty">
              {detailQuery.isLoading ? t('conversations.detailLoading') : t('conversations.detailEmpty')}
            </div>
          )}

          {selected && (
            <div className="hidden xl:block" data-testid="visitor-context-wrapper">
              <VisitorContextPanel conversation={selected} />
            </div>
          )}
        </div>
      </div>
    </PageLayout>
  );
}
