"use client";

import { Suspense, useCallback, useEffect, useMemo, useState } from "react";
import { Search, RefreshCw, Download, Eye, FileText } from "lucide-react";
import { useSearchParams } from "next/navigation";
import { PageHeader } from "@/components/ui/PageHeader";
import { BREADCRUMBS } from "@/constants/breadcrumbs";
import { apiGet, apiPost } from "@/utils/api-client";
import type { ReactNode } from "react";

type DeepdexRow = {
  id: number;
  original_name: string;
  storage_key?: string;
  mime_type: string;
  file_size: number;
  formatted_file_size: string;
  doc_type: string;
  uploaded_at: string;
  view_url: string;
  download_url: string;
  snippet?: string;
  extracted_preview?: string;
  tag_issuer?: string;
  tag_name?: string;
  tag_isin?: string;
  tag_product_type?: string;
  tag_coupon?: string;
  tag_strike?: string;
  tag_underlying_name?: string;
  tag_underlying_isin?: string;
  tag_status?: string;
  next_coupon_date?: string | null;
  days_to_coupon?: number | null;
  next_observation_date?: string | null;
  days_to_observation?: number | null;
  maturity_date?: string | null;
  days_to_maturity?: number | null;
  strike_tier?: string;
  coupon_tier?: string;
  extracted_data?: Record<string, unknown> | null;
  [key: string]: unknown;
};

type DeepdexListResponse = {
  data?: DeepdexRow[];
  count?: number;
  total?: number;
};

type DeepdexStatsResponse = {
  total_deepdex_docs?: number;
  indexed_count?: number;
  ocr_attempted_count?: number;
  ocr_text_available_count?: number;
};

type SearchFilters = {
  doc_type: string;
  issuer: string;
  name: string;
  isin: string;
  product_type: string;
  status: string;
};

function normalizeRows(response: DeepdexListResponse | DeepdexRow[] | unknown): DeepdexRow[] {
  if (Array.isArray(response)) {
    return response as DeepdexRow[];
  }
  if (response && typeof response === "object") {
    const obj = response as DeepdexListResponse;
    if (Array.isArray(obj.data)) {
      return obj.data;
    }
  }
  return [];
}

function formatLabel(key: string): string {
  return key
    .replace(/^tag_/, "")
    .replace(/_/g, " ")
    .replace(/\b\w/g, (c) => c.toUpperCase());
}

function safeToText(value: unknown): string {
  if (value == null) return "";
  if (typeof value === "string") return value.trim();
  if (typeof value === "number" || typeof value === "boolean") return String(value);
  return "";
}

function tagColorClass(key: string): string {
  const map: Record<string, string> = {
    doc_type: "bg-blue-50 text-blue-700",
    tag_bank_name: "bg-pink-50 text-pink-700",
    tag_issuer: "bg-emerald-50 text-emerald-700",
    tag_name: "bg-green-50 text-green-700",
    tag_isin: "bg-purple-50 text-purple-700",
    tag_product_type: "bg-amber-50 text-amber-700",
    tag_coupon: "bg-indigo-50 text-indigo-700",
    tag_expiry: "bg-rose-50 text-rose-700",
    tag_ko_barrier: "bg-orange-50 text-orange-700",
    tag_strike: "bg-stone-100 text-stone-700",
    tag_settlement_date: "bg-sky-50 text-sky-700",
    tag_trade_date: "bg-cyan-50 text-cyan-700",
    tag_final_valuation_date: "bg-teal-50 text-teal-700",
    tag_status: "bg-lime-50 text-lime-700",
    strike_tier: "bg-red-50 text-red-700",
    coupon_tier: "bg-yellow-50 text-yellow-700",
  };
  if (map[key]) return map[key];

  // Fallback: deterministic palette for any additional/unmapped tags.
  const palette = [
    "bg-slate-100 text-slate-700",
    "bg-zinc-100 text-zinc-700",
    "bg-neutral-100 text-neutral-700",
    "bg-stone-100 text-stone-700",
    "bg-red-50 text-red-700",
    "bg-orange-50 text-orange-700",
    "bg-amber-50 text-amber-700",
    "bg-lime-50 text-lime-700",
    "bg-green-50 text-green-700",
    "bg-emerald-50 text-emerald-700",
    "bg-teal-50 text-teal-700",
    "bg-cyan-50 text-cyan-700",
    "bg-sky-50 text-sky-700",
    "bg-blue-50 text-blue-700",
    "bg-indigo-50 text-indigo-700",
    "bg-violet-50 text-violet-700",
    "bg-purple-50 text-purple-700",
    "bg-fuchsia-50 text-fuchsia-700",
    "bg-pink-50 text-pink-700",
    "bg-rose-50 text-rose-700",
  ];
  let hash = 0;
  for (let i = 0; i < key.length; i += 1) {
    hash = (hash << 5) - hash + key.charCodeAt(i);
    hash |= 0;
  }
  const index = Math.abs(hash) % palette.length;
  return palette[index];
}

function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function encodePathPrefix(value: string): string {
  const utf8 = encodeURIComponent(value).replace(/%([0-9A-F]{2})/g, (_, p1) =>
    String.fromCharCode(Number.parseInt(p1, 16))
  );
  return btoa(utf8).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}

function resolveDeepdexViewUrl(row: DeepdexRow): string {
  const raw = safeToText(row.storage_key);
  if (raw) {
    if (/^(https?:)?\/\//i.test(raw) || raw.startsWith("data:")) {
      return raw;
    }
    const normalizedPath = raw.replace(/^\/+/, "");
    const parts = normalizedPath.split("/").filter(Boolean);
    if (parts.length >= 2) {
      const prefix = `${parts.slice(0, -1).join("/")}/`;
      const filename = parts[parts.length - 1];
      const encodedPrefix = encodePathPrefix(prefix);
      return `/pdf-view/__enc/${encodedPrefix}/${filename}`;
    }
    if (normalizedPath) {
      return `/pdf-view/${normalizedPath}`;
    }
  }
  return `/api/deepdex/file?id=${row.id}&disposition=inline`;
}

function renderHighlightedText(text: string, query: string): ReactNode {
  const terms = query
    .trim()
    .split(/\s+/)
    .map((term) => term.trim())
    .filter((term) => term.length > 1);

  if (terms.length === 0 || !text) return text;

  const pattern = new RegExp(`(${terms.map(escapeRegExp).join("|")})`, "ig");
  const parts = text.split(pattern);
  return parts.map((part, index) =>
    terms.some((term) => term.toLowerCase() === part.toLowerCase()) ? (
      <mark key={`${part}-${index}`} className="bg-yellow-200 text-gray-900 rounded px-0.5">
        {part}
      </mark>
    ) : (
      <span key={`${part}-${index}`}>{part}</span>
    )
  );
}

const SEARCH_TAG_ORDER = [
  "doc_type",
  "tag_bank_name",
  "tag_issuer",
  "tag_name",
  "tag_isin",
  "tag_product_type",
  "tag_coupon",
  "tag_expiry",
  "tag_observations",
  "tag_ko_barrier",
  "tag_non_call_period",
  "tag_strike",
  "tag_settlement_date",
  "tag_trade_date",
  "tag_final_valuation_date",
  "tag_status",
  "tag_observation_dates",
  "tag_periods",
  "tag_frequency",
  "tag_start",
  "tag_quantity",
  "tag_spot",
  "tag_profit_taking",
  "tag_knock",
  "tag_underlying_isin",
  "tag_underlying_name",
  "tag_tarf_ccy_isin",
  "tag_underlying1_isin",
  "tag_underlying1_name",
  "tag_underlying1_currency",
  "tag_underlying1_spot",
  "tag_underlying2_isin",
  "tag_underlying2_name",
  "tag_underlying2_currency",
  "tag_underlying2_spot",
  "tag_underlying3_isin",
  "tag_underlying3_name",
  "tag_underlying3_currency",
  "tag_underlying3_spot",
  "tag_underlying4_isin",
  "tag_underlying4_name",
  "tag_underlying4_currency",
  "tag_underlying4_spot",
  "tag_underlying5_isin",
  "tag_underlying5_name",
  "tag_underlying5_currency",
  "tag_underlying5_spot",
  "tag_customers",
  "tag_rms",
] as const;

function DeepdexDocumentsContent() {
  const searchParams = useSearchParams();
  const activeTab = searchParams.get("tab") === "search" ? "search" : "view";
  const [rows, setRows] = useState<DeepdexRow[]>([]);
  const [stats, setStats] = useState<DeepdexStatsResponse>({});
  const [loading, setLoading] = useState(true);
  const [query, setQuery] = useState("");
  const [filters, setFilters] = useState<SearchFilters>({
    doc_type: "",
    issuer: "",
    name: "",
    isin: "",
    product_type: "",
    status: "",
  });
  const [searching, setSearching] = useState(false);
  const [backfilling, setBackfilling] = useState(false);

  const loadStats = useCallback(async () => {
    try {
      const response = await apiGet<DeepdexStatsResponse>("/api/deepdex/stats");
      setStats(response || {});
    } catch (error) {
      console.error("Failed to load Deepdex stats", error);
      setStats({});
    }
  }, []);

  const loadList = useCallback(async () => {
    setLoading(true);
    try {
      const response = await apiPost<DeepdexListResponse | DeepdexRow[]>("/api/deepdex/list", {
        page: 1,
        pageSize: 100,
      });
      setRows(normalizeRows(response));
    } catch (error) {
      console.error("Failed to load Deepdex list", error);
      setRows([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (activeTab === "view") {
      loadList();
    } else {
      setRows([]);
      setLoading(false);
    }
    loadStats();
  }, [activeTab, loadList, loadStats]);

  const runSearch = useCallback(async () => {
    const trimmed = query.trim();
    if (!trimmed) {
      if (activeTab === "view") {
        loadList();
      } else {
        setRows([]);
      }
      return;
    }

    setSearching(true);
    try {
      const response = await apiPost<DeepdexListResponse | DeepdexRow[]>("/api/deepdex/search", {
        q: trimmed,
        limit: 100,
        ...filters,
      });
      setRows(normalizeRows(response));
    } catch (error) {
      console.error("Deepdex search failed", error);
      setRows([]);
    } finally {
      setSearching(false);
    }
  }, [query, filters, loadList, activeTab]);

  const clearFilters = useCallback(() => {
    setFilters({
      doc_type: "",
      issuer: "",
      name: "",
      isin: "",
      product_type: "",
      status: "",
    });
  }, []);

  const runBackfill = useCallback(async () => {
    setBackfilling(true);
    try {
      await apiPost("/api/deepdex/backfill", { limit: 1000 });
      await loadList();
      await loadStats();
    } catch (error) {
      console.error("Deepdex backfill failed", error);
    } finally {
      setBackfilling(false);
    }
  }, [loadList, loadStats]);

  const actions = useMemo(
    () => (
      <div className="flex items-center gap-2">
        <button
          onClick={activeTab === "view" ? loadList : runSearch}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors"
        >
          <RefreshCw className="h-3.5 w-3.5" />
          {activeTab === "view" ? "Refresh" : "Refresh Search"}
        </button>
        <button
          onClick={loadStats}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors"
        >
          <RefreshCw className="h-3.5 w-3.5" />
          Re-check Stats
        </button>
        <button
          onClick={runBackfill}
          disabled={backfilling}
          className="inline-flex items-center gap-1.5 px-3 py-2 text-xs font-medium border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors disabled:opacity-60"
        >
          <RefreshCw className="h-3.5 w-3.5" />
          {backfilling ? "Backfilling..." : "Backfill Existing"}
        </button>
      </div>
    ),
    [activeTab, loadList, loadStats, runSearch, runBackfill, backfilling]
  );

  return (
    <div className="container mx-auto px-4 mt-6 pb-12">
      <PageHeader
        title="Deepdex Documents"
        description="Search and review your indexed documents in one place."
        breadcrumbs={[...BREADCRUMBS.deepdexDocuments]}
        actions={actions}
      />

      <div className="mt-5 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3">
        <div className="bg-white rounded-lg shadow-sm p-4">
          <div className="text-[11px] uppercase tracking-wide text-gray-500 font-semibold">Total Documents</div>
          <div className="mt-2 text-2xl font-bold text-gray-800">{stats.total_deepdex_docs ?? rows.length}</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm p-4">
          <div className="text-[11px] uppercase tracking-wide text-gray-500 font-semibold">Indexed For Search</div>
          <div className="mt-2 text-2xl font-bold text-gray-800">{stats.indexed_count ?? "-"}</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm p-4">
          <div className="text-[11px] uppercase tracking-wide text-gray-500 font-semibold">OCR Attempted</div>
          <div className="mt-2 text-2xl font-bold text-gray-800">{stats.ocr_attempted_count ?? "-"}</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm p-4">
          <div className="text-[11px] uppercase tracking-wide text-gray-500 font-semibold">OCR Text Available</div>
          <div className="mt-2 text-2xl font-bold text-gray-800">{stats.ocr_text_available_count ?? "-"}</div>
        </div>
      </div>

      <div className="mt-4 bg-white rounded-lg shadow-sm p-4">
        <div className="mb-3 flex items-center justify-between">
          <h3 className="text-sm font-semibold text-gray-800">
            {activeTab === "search" ? "Search Documents" : "All Documents"}
          </h3>
          <span className="text-xs text-gray-500">
            {activeTab === "search"
              ? "Search mode with filters and ranked cards"
              : "View mode with table listing"}
          </span>
        </div>
        <div className="flex flex-col sm:flex-row gap-2">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  runSearch();
                }
              }}
              placeholder="Search your indexed documents..."
              className="w-full border rounded-lg pl-9 pr-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#428B4D]/20"
            />
          </div>
          <button
            onClick={runSearch}
            className="inline-flex items-center justify-center gap-1.5 px-4 py-2 text-sm font-medium bg-[#428B4D] text-white rounded-md hover:bg-[#357a3f] transition-colors"
            disabled={searching}
          >
            <Search className="h-4 w-4" />
            {searching ? "Searching..." : "Search"}
          </button>
          {activeTab === "view" && (
            <button
              onClick={() => {
                setQuery("");
                loadList();
              }}
              className="inline-flex items-center justify-center gap-1.5 px-4 py-2 text-sm font-medium border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition-colors"
            >
              Clear
            </button>
          )}
        </div>

        {activeTab === "search" && (
          <div className="mt-3 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-6 gap-2">
            <input
              value={filters.doc_type}
              onChange={(e) => setFilters((s) => ({ ...s, doc_type: e.target.value }))}
              placeholder="Doc type"
              className="border rounded-md px-3 py-2 text-xs"
            />
            <input
              value={filters.issuer}
              onChange={(e) => setFilters((s) => ({ ...s, issuer: e.target.value }))}
              placeholder="Issuer"
              className="border rounded-md px-3 py-2 text-xs"
            />
            <input
              value={filters.name}
              onChange={(e) => setFilters((s) => ({ ...s, name: e.target.value }))}
              placeholder="Name"
              className="border rounded-md px-3 py-2 text-xs"
            />
            <input
              value={filters.isin}
              onChange={(e) => setFilters((s) => ({ ...s, isin: e.target.value }))}
              placeholder="ISIN / Underlying / Ticker"
              className="border rounded-md px-3 py-2 text-xs"
            />
            <input
              value={filters.product_type}
              onChange={(e) => setFilters((s) => ({ ...s, product_type: e.target.value }))}
              placeholder="Product type"
              className="border rounded-md px-3 py-2 text-xs"
            />
            <div className="flex items-center gap-2">
              <select
                value={filters.status}
                onChange={(e) => setFilters((s) => ({ ...s, status: e.target.value }))}
                className="border rounded-md px-2 py-2 text-xs w-full"
              >
                <option value="">Status</option>
                <option value="Active">Active</option>
                <option value="Expired">Expired</option>
              </select>
              <button
                onClick={clearFilters}
                className="px-2 py-2 text-xs border rounded-md text-gray-600 hover:bg-gray-50"
              >
                Clear
              </button>
            </div>
          </div>
        )}
      </div>

      <div className="mt-4 rounded-lg">
      <div className="bg-white rounded-lg shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center py-16 text-sm text-gray-400">
            Loading documents...
          </div>
        ) : rows.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 gap-3">
            <FileText className="h-10 w-10 text-gray-300" />
            <div className="text-sm text-gray-400">No indexed documents found.</div>
          </div>
        ) : activeTab === "search" ? (
          <div className="p-4">
            <div className="mb-3 text-xs text-gray-500">{rows.length} result(s) found</div>
            {rows.map((row) => (
              <div key={row.id} className="rounded-lg p-4 mb-3 last:mb-0 bg-white/90 hover:bg-gray-50/60 transition-colors shadow-sm">
                {(() => {
                  const excluded = new Set<string>([
                    "id",
                    "original_name",
                    "storage_key",
                    "mime_type",
                    "file_size",
                    "formatted_file_size",
                    "doc_type",
                    "uploaded_at",
                    "view_url",
                    "download_url",
                    "snippet",
                    "extracted_preview",
                    "tag_status",
                    "strike_tier",
                    "coupon_tier",
                    "extracted_data",
                    "deepdex_id",
                  ]);
                  const rowAsRecord = row as Record<string, unknown>;
                  const orderedFields = SEARCH_TAG_ORDER.map((key) => ({
                    key,
                    value: safeToText(rowAsRecord[key]),
                  })).filter((item) => item.value !== "");

                  const extraFields = Object.entries(rowAsRecord)
                    .filter(([key]) => !excluded.has(key) && !SEARCH_TAG_ORDER.includes(key as (typeof SEARCH_TAG_ORDER)[number]))
                    .map(([key, value]) => ({ key, value: safeToText(value) }))
                    .filter((item) => item.value !== "");

                  const detailFields = [...orderedFields, ...extraFields];
                  const extractedData =
                    rowAsRecord.extracted_data && typeof rowAsRecord.extracted_data === "object"
                      ? (rowAsRecord.extracted_data as Record<string, unknown>)
                      : null;
                  const extractedTextRaw =
                    safeToText(rowAsRecord.extracted_preview) ||
                    safeToText(extractedData?.extracted_text) ||
                    safeToText(extractedData?.ocr_text);
                  const extractedTextPreview =
                    extractedTextRaw.length > 450
                      ? `${extractedTextRaw.slice(0, 450)}...`
                      : extractedTextRaw;

                  return (
                    <>
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="text-sm font-semibold text-gray-800 truncate">
                      {renderHighlightedText(row.original_name, query)}
                    </div>
                    <div className="mt-1 flex flex-wrap gap-1 text-[11px] text-gray-600">
                      {row.doc_type && (
                        <span className="inline-flex items-center rounded-full border border-transparent px-2 py-0.5 bg-blue-50 text-blue-700">
                          {row.doc_type}
                        </span>
                      )}
                      {row.tag_status && (
                        <span className="inline-flex items-center rounded-full border border-transparent px-2 py-0.5 bg-lime-50 text-lime-700">
                          {row.tag_status}
                        </span>
                      )}
                      {row.strike_tier && (
                        <span className="inline-flex items-center rounded-full border border-transparent px-2 py-0.5 bg-red-50 text-red-700">
                          Strike {row.strike_tier}
                        </span>
                      )}
                      {row.coupon_tier && (
                        <span className="inline-flex items-center rounded-full border border-transparent px-2 py-0.5 bg-yellow-50 text-yellow-700">
                          Coupon {row.coupon_tier}
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <a href={resolveDeepdexViewUrl(row)} target="_blank" rel="noopener noreferrer" className="inline-flex items-center justify-center h-8 w-8 rounded-md bg-[#428B4D]/10 text-[#428B4D] hover:bg-[#428B4D] hover:text-white transition-colors">
                      <Eye className="h-4 w-4" />
                    </a>
                    <a href={`/api/deepdex/file?id=${row.id}&disposition=attachment`} className="inline-flex items-center justify-center h-8 w-8 rounded-md bg-gray-100 text-gray-700 hover:bg-gray-700 hover:text-white transition-colors">
                      <Download className="h-4 w-4" />
                    </a>
                  </div>
                </div>

                {extractedTextPreview && (
                  <div className="mt-2 text-xs text-gray-600">
                    <span className="font-medium text-gray-700">Extracted:</span>{" "}
                    {renderHighlightedText(extractedTextPreview, query)}
                  </div>
                )}

                {detailFields.length > 0 && (
                  <div className="mt-3">
                    <div className="text-xs text-gray-600 mb-2">Document details</div>
                    <div className="flex flex-wrap gap-1">
                    {detailFields.map((field) => (
                      <span
                        key={field.key}
                        className={`px-2 py-0.5 text-[11px] rounded ${tagColorClass(field.key)}`}
                      >
                        {formatLabel(field.key)}: {renderHighlightedText(field.value, query)}
                      </span>
                    ))}
                    </div>
                  </div>
                )}

                <div className="mt-3 flex flex-wrap gap-1">
                  <span className="px-2 py-0.5 text-[11px] rounded bg-gray-100 text-gray-700">
                    Coupon: {row.days_to_coupon != null ? `${row.days_to_coupon}d` : "—"} {row.next_coupon_date ? `(${row.next_coupon_date})` : ""}
                  </span>
                  <span className="px-2 py-0.5 text-[11px] rounded bg-gray-100 text-gray-700">
                    Observation: {row.days_to_observation != null ? `${row.days_to_observation}d` : "—"} {row.next_observation_date ? `(${row.next_observation_date})` : ""}
                  </span>
                  <span className="px-2 py-0.5 text-[11px] rounded bg-gray-100 text-gray-700">
                    Maturity: {row.days_to_maturity != null ? `${row.days_to_maturity}d` : "—"} {row.maturity_date ? `(${row.maturity_date})` : ""}
                  </span>
                </div>

                
                    </>
                  );
                })()}
              </div>
            ))}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-gray-50/70 border-b border-gray-100">
                  <th className="px-4 py-3 text-left text-[11px] font-semibold tracking-wide text-gray-500 uppercase">File name</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold tracking-wide text-gray-500 uppercase">Size</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold tracking-wide text-gray-500 uppercase">Doc type</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold tracking-wide text-gray-500 uppercase">Uploaded at</th>
                  <th className="px-4 py-3 text-left text-[11px] font-semibold tracking-wide text-gray-500 uppercase">Snippet</th>
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((row) => (
                  <tr key={row.id} className="border-b border-gray-100 hover:bg-gray-50/60 transition-colors">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2 max-w-[340px]">
                        <span className="h-7 w-7 rounded-md bg-[#428B4D]/10 text-[#428B4D] flex items-center justify-center flex-shrink-0">
                          <FileText className="h-4 w-4" />
                        </span>
                        <span className="text-xs text-gray-800 font-medium truncate">{row.original_name}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-700">
                      <span className="inline-flex items-center rounded-full border px-2 py-0.5 bg-gray-50">
                        {row.formatted_file_size || "-"}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-600">
                      <span className="inline-flex items-center rounded-full border border-[#428B4D]/20 text-[#428B4D] bg-[#428B4D]/10 px-2 py-0.5">
                        {row.doc_type || row.mime_type || "-"}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-600 whitespace-nowrap">{row.uploaded_at || "-"}</td>
                    <td className="px-4 py-3 text-xs text-gray-600 max-w-[320px] truncate">{row.snippet || "-"}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-2">
                        <a
                          href={resolveDeepdexViewUrl(row)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center justify-center h-8 w-8 rounded-md bg-[#428B4D]/10 text-[#428B4D] hover:bg-[#428B4D] hover:text-white transition-colors"
                          title="View"
                        >
                          <Eye className="h-4 w-4" />
                        </a>
                        <a
                          href={`/api/deepdex/file?id=${row.id}&disposition=attachment`}
                          className="inline-flex items-center justify-center h-8 w-8 rounded-md bg-gray-100 text-gray-700 hover:bg-gray-700 hover:text-white transition-colors"
                          title="Download"
                        >
                          <Download className="h-4 w-4" />
                        </a>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
      </div>
    </div>
  );
}

function DeepdexDocumentsFallback() {
  return (
    <div className="min-h-[40vh] flex items-center justify-center text-gray-500 text-sm">
      Loading…
    </div>
  );
}

export default function DeepdexDocumentsPage() {
  return (
    <Suspense fallback={<DeepdexDocumentsFallback />}>
      <DeepdexDocumentsContent />
    </Suspense>
  );
}
