'use client';

import { useCallback, useRef, useState } from 'react';
import Link from 'next/link';
import { adminService } from '@/services/admin.service';
import { loggingService } from '@/services/logging.service';
import { getAdminAllReferrals } from '@/services/referral/referral.service';
import type { GlobalSearchResponse } from '@/types/admin.types';
import type { LogSearchResponse, LogSearchResult } from '@/types/logging.types';
import type { UserProfile, OrderInfo, TransactionEntry } from '@/types/admin.types';
import { Search } from 'lucide-react';

type SearchTab = 'all' | 'users' | 'orders' | 'transactions' | 'wallets' | 'referrals' | 'logs';

export default function GlobalSearchPage() {
  const [query, setQuery] = useState('');
  const [tab, setTab] = useState<SearchTab>('all');
  const [results, setResults] = useState<GlobalSearchResponse | LogSearchResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const searchedRef = useRef(false);

  const runSearch = useCallback(
    async (targetPage = 1) => {
      if (!query.trim()) {
        setError('Enter a search term');
        return;
      }
      setLoading(true);
      setError(null);
      try {
        if (tab === 'logs') {
          const res = await loggingService.searchLogs({
            query: query.trim(),
            page: targetPage,
            limit: 20,
          });
          setResults(res ?? null);
        } else if (tab === 'all') {
          const [logRes, globalRes] = await Promise.all([
            loggingService.searchLogs({
              query: query.trim(),
              page: targetPage,
              limit: 20,
            }),
            adminService.superAdminGlobalSearch(query.trim()),
          ]);
          setResults(globalRes ?? logRes ?? null);
        } else if (tab === 'wallets') {
          const res = await adminService.listWallets({ search: query.trim(), page: targetPage, limit: 20 });
          setResults({
            users: [],
            orders: [],
            transactions: [],
            logs: [],
            wallets: res.data,
            meta: res.meta,
          } as any);
        } else if (tab === 'referrals') {
          const res = await getAdminAllReferrals();
          const filtered = (Array.isArray(res) ? res : []).filter((r: any) => {
            if (!query.trim()) return true;
            const q = query.toLowerCase();
            return (
              (r.referrer?.email || '').toLowerCase().includes(q) ||
              (r.referred?.email || '').toLowerCase().includes(q) ||
              (r.referralCode || '').toLowerCase().includes(q)
            );
          });
          setResults({
            users: [],
            orders: [],
            transactions: [],
            logs: [],
            referrals: filtered,
          } as any);
        } else {
          const res = await adminService.superAdminGlobalSearch(query.trim(), tab);
          setResults(res ?? null);
        }
        setPage(targetPage);
        searchedRef.current = true;
      } catch (err: any) {
        setError(err?.response?.data?.message ?? err?.message ?? 'Search failed');
      } finally {
        setLoading(false);
      }
    },
    [query, tab],
  );

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    void runSearch(1);
  };

  const tabs: { key: SearchTab; label: string }[] = [
    { key: 'all', label: 'All' },
    { key: 'users', label: 'Users' },
    { key: 'orders', label: 'Orders' },
    { key: 'transactions', label: 'Transactions' },
    { key: 'wallets', label: 'Wallets' },
    { key: 'referrals', label: 'Referrals' },
    { key: 'logs', label: 'Logs' },
  ];

  const isLogSearch = results && 'results' in results;
  const logMeta = isLogSearch ? (results as LogSearchResponse).meta : null;
  const totalPages = logMeta ? Math.max(1, Math.ceil(logMeta.total / 20)) : 1;

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-xl font-semibold text-slate-100">Global Search</h1>
        <p className="mt-1 text-sm text-slate-400">
          Search across users, orders, transactions, wallets, referrals, and logs.
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-3 rounded-xl border border-white/5 bg-slate-900/50 p-4">
        <div className="flex flex-col gap-3 md:flex-row">
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search by email, ID, name, reference..."
            className="flex-1 rounded-lg border border-white/10 bg-slate-950 px-3 py-2 text-sm text-slate-100 outline-none placeholder:text-slate-600 focus:border-emerald-400/50"
          />
          <button
            type="submit"
            disabled={loading}
            className="rounded-lg bg-emerald-500 px-5 py-2 text-sm font-medium text-white hover:bg-emerald-400 disabled:opacity-50"
          >
            {loading ? 'Searching...' : 'Search'}
          </button>
        </div>

        <div className="flex flex-wrap gap-2">
          {tabs.map((t) => (
            <button
              key={t.key}
              type="button"
              onClick={() => {
                setTab(t.key);
                setResults(null);
                searchedRef.current = false;
              }}
              className={`rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${
                tab === t.key
                  ? 'border-emerald-400/50 bg-emerald-500/10 text-emerald-300'
                  : 'border-white/10 text-slate-400 hover:bg-white/5'
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>
      </form>

      {error && (
        <div className="rounded-xl border border-rose-500/20 bg-rose-500/10 p-4 text-sm text-rose-300">{error}</div>
      )}

      {results && isLogSearch && (
        <div className="overflow-hidden rounded-xl border border-white/5">
          <div className="border-b border-white/5 bg-slate-900/70 px-4 py-3 text-xs text-slate-400">
            {logMeta?.total.toLocaleString()} result{logMeta?.total === 1 ? '' : 's'}
          </div>
          <table className="w-full text-left text-sm">
            <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
              <tr>
                <th className="px-4 py-3">Type</th>
                <th className="px-4 py-3">Message</th>
                <th className="px-4 py-3">Timestamp</th>
                <th className="px-4 py-3 text-right">Open</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {results.results.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-4 py-10 text-center text-slate-500">
                    No results match your search.
                  </td>
                </tr>
              )}
              {(results as LogSearchResponse).results.map((r: LogSearchResult) => (
                <tr key={`${r.type}-${r.id}`} className="hover:bg-white/[0.02]">
                  <td className="px-4 py-3">
                    <span className="rounded-full bg-slate-500/15 px-2 py-0.5 text-xs font-medium capitalize text-slate-300">
                      {r.type}
                    </span>
                  </td>
                  <td className="max-w-[420px] px-4 py-3">
                    <div className="truncate text-slate-200">{r.message}</div>
                  </td>
                  <td className="px-4 py-3 text-slate-400">{new Date(r.createdAt).toLocaleString()}</td>
                  <td className="px-4 py-3 text-right">
                    <Link
                      href={
                        r.type === 'login'
                          ? '/super-admin/logs/login'
                          : r.type === 'transaction'
                            ? '/super-admin/logs/transactions'
                            : r.type === 'admin'
                              ? '/super-admin/logs/admin'
                              : r.type === 'error'
                                ? '/super-admin/logs/errors'
                                : r.type === 'system'
                                  ? '/super-admin/logs/system'
                                  : '/super-admin/logs/requests'
                      }
                      className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5"
                    >
                      View
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          <div className="flex items-center justify-between px-4 py-3 text-xs text-slate-400">
            <span>
              Page {page} of {totalPages}
            </span>
            <div className="flex gap-2">
              <button
                onClick={() => void runSearch(page - 1)}
                disabled={page <= 1}
                className="rounded-lg border border-white/10 px-3 py-1.5 hover:bg-white/5 disabled:opacity-40"
              >
                Prev
              </button>
              <button
                onClick={() => void runSearch(page + 1)}
                disabled={page >= totalPages}
                className="rounded-lg border border-white/10 px-3 py-1.5 hover:bg-white/5 disabled:opacity-40"
              >
                Next
              </button>
            </div>
          </div>
        </div>
      )}

      {results && !isLogSearch && (
        <div className="space-y-4">
          {(tab === 'all' || tab === 'users') && (
            <ResultsSection title="Users" count={(results as GlobalSearchResponse).users?.length ?? 0}>
              <table className="w-full text-left text-sm">
                <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
                  <tr>
                    <th className="px-4 py-3">User</th>
                    <th className="px-4 py-3">Email</th>
                    <th className="px-4 py-3">Role</th>
                    <th className="px-4 py-3 text-right">Open</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {(results as GlobalSearchResponse).users?.length === 0 ? (
                    <tr><td colSpan={4} className="px-4 py-6 text-center text-slate-500">No users found.</td></tr>
                  ) : (
                    (results as GlobalSearchResponse).users?.map((u: UserProfile) => (
                      <tr key={u.id} className="hover:bg-white/[0.02]">
                        <td className="px-4 py-3 text-white">{u.firstName || u.lastName ? `${u.firstName || ''} ${u.lastName || ''}`.trim() : u.email}</td>
                        <td className="px-4 py-3 text-slate-300">{u.email}</td>
                        <td className="px-4 py-3 text-slate-300">{u.role?.name ?? '-'}</td>
                        <td className="px-4 py-3 text-right">
                          <Link href={`/super-admin/users/${u.id}`} className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5">View</Link>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </ResultsSection>
          )}

          {(tab === 'all' || tab === 'orders') && (
            <ResultsSection title="Orders" count={(results as GlobalSearchResponse).orders?.length ?? 0}>
              <table className="w-full text-left text-sm">
                <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
                  <tr>
                    <th className="px-4 py-3">Order ID</th>
                    <th className="px-4 py-3">Status</th>
                    <th className="px-4 py-3">Currency</th>
                    <th className="px-4 py-3 text-right">Open</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {(results as GlobalSearchResponse).orders?.length === 0 ? (
                    <tr><td colSpan={4} className="px-4 py-6 text-center text-slate-500">No orders found.</td></tr>
                  ) : (
                    (results as GlobalSearchResponse).orders?.map((o: OrderInfo) => (
                      <tr key={o.id} className="hover:bg-white/[0.02]">
                        <td className="px-4 py-3 font-mono text-xs text-slate-300">{o.id}</td>
                        <td className="px-4 py-3 text-slate-300">{o.status}</td>
                        <td className="px-4 py-3 text-slate-300">{o.currency}</td>
                        <td className="px-4 py-3 text-right">
                          <Link href={`/admin/orders/${o.id}`} className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5">View</Link>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </ResultsSection>
          )}

          {(tab === 'all' || tab === 'transactions') && (
            <ResultsSection title="Transactions" count={(results as GlobalSearchResponse).transactions?.length ?? 0}>
              <table className="w-full text-left text-sm">
                <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
                  <tr>
                    <th className="px-4 py-3">ID</th>
                    <th className="px-4 py-3">Type</th>
                    <th className="px-4 py-3">Amount</th>
                    <th className="px-4 py-3 text-right">Open</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {(results as GlobalSearchResponse).transactions?.length === 0 ? (
                    <tr><td colSpan={4} className="px-4 py-6 text-center text-slate-500">No transactions found.</td></tr>
                  ) : (
                    (results as GlobalSearchResponse).transactions?.map((t: TransactionEntry) => (
                      <tr key={t.id} className="hover:bg-white/[0.02]">
                        <td className="px-4 py-3 font-mono text-xs text-slate-300">{t.id}</td>
                        <td className="px-4 py-3 text-slate-300">{t.type}</td>
                        <td className="px-4 py-3 text-slate-300">{t.amount}</td>
                        <td className="px-4 py-3 text-right">
                          <Link href="/super-admin/logs/transactions" className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5">View</Link>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </ResultsSection>
          )}

          {(tab === 'all' || tab === 'wallets') && (results as any).wallets && (
            <ResultsSection title="Wallets" count={(results as any).wallets?.length ?? 0}>
              <table className="w-full text-left text-sm">
                <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
                  <tr>
                    <th className="px-4 py-3">User</th>
                    <th className="px-4 py-3">Balance</th>
                    <th className="px-4 py-3">Locked</th>
                    <th className="px-4 py-3">Frozen</th>
                    <th className="px-4 py-3 text-right">Open</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {(results as any).wallets?.length === 0 ? (
                    <tr><td colSpan={5} className="px-4 py-6 text-center text-slate-500">No wallets found.</td></tr>
                  ) : (
                    (results as any).wallets?.map((w: any) => (
                      <tr key={w.id} className="hover:bg-white/[0.02]">
                        <td className="px-4 py-3 text-slate-300">{w.user?.email || w.userId}</td>
                        <td className="px-4 py-3 text-slate-300">{Number(w.balance).toFixed(2)}</td>
                        <td className="px-4 py-3 text-slate-300">{Number(w.locked).toFixed(2)}</td>
                        <td className="px-4 py-3 text-slate-300">{w.isFrozen ? 'Yes' : 'No'}</td>
                        <td className="px-4 py-3 text-right">
                          <Link href={`/super-admin/users/${w.userId}`} className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5">View User</Link>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </ResultsSection>
          )}

          {(tab === 'all' || tab === 'referrals') && (results as any).referrals && (
            <ResultsSection title="Referrals" count={(results as any).referrals?.length ?? 0}>
              <table className="w-full text-left text-sm">
                <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
                  <tr>
                    <th className="px-4 py-3">Referrer</th>
                    <th className="px-4 py-3">Referred</th>
                    <th className="px-4 py-3">Code</th>
                    <th className="px-4 py-3">Status</th>
                    <th className="px-4 py-3 text-right">Open</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/5">
                  {(results as any).referrals?.length === 0 ? (
                    <tr><td colSpan={5} className="px-4 py-6 text-center text-slate-500">No referrals found.</td></tr>
                  ) : (
                    (results as any).referrals?.map((r: any) => (
                      <tr key={r.id} className="hover:bg-white/[0.02]">
                        <td className="px-4 py-3 text-slate-300">{r.referrer?.email || 'N/A'}</td>
                        <td className="px-4 py-3 text-slate-300">{r.referred?.email || 'N/A'}</td>
                        <td className="px-4 py-3 font-mono text-xs text-slate-300">{r.referralCode || 'N/A'}</td>
                        <td className="px-4 py-3 text-slate-300">{r.status}</td>
                        <td className="px-4 py-3 text-right">
                          <Link href={`/super-admin/users/${r.referred?.id || r.referrer?.id}`} className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5">View</Link>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </ResultsSection>
          )}
        </div>
      )}

      {!results && !searchedRef.current && !loading && (
        <div className="rounded-xl border border-dashed border-white/10 p-10 text-center text-sm text-slate-500">
          Enter a keyword and press Search to find users, orders, transactions, wallets, referrals, and logs.
        </div>
      )}
      {loading && (
        <div className="flex items-center justify-center gap-2 py-16 text-sm text-slate-400">
          <span className="h-4 w-4 animate-spin rounded-full border-2 border-slate-500 border-t-emerald-400" />
          Searching...
        </div>
      )}
    </div>
  );
}

function ResultsSection({ title, count, children }: { title: string; count: number; children: React.ReactNode }) {
  return (
    <div className="overflow-hidden rounded-xl border border-white/5">
      <div className="border-b border-white/5 bg-slate-900/70 px-4 py-3 text-xs text-slate-400">
        {title} — {count} result{count === 1 ? '' : 's'}
      </div>
      {children}
    </div>
  );
}
