"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  Loader2,
  BarChart3,
  ChevronLeft,
  ChevronRight,
  ArrowLeft,
  AlertTriangle,
} from "lucide-react";
import { adminApi } from "@/lib/api/client";

interface UsageSummary {
  userId: string;
  userEmail: string | null;
  userName: string | null;
  totalCalls: number;
  errorCalls: number;
  lastSeenAt: string | null;
}

interface EndpointUsage {
  method: string;
  path: string;
  calls: number;
  errorCalls: number;
  avgDurationMs: number | null;
}

interface RequestRow {
  id: number;
  method: string;
  path: string;
  status: number;
  durationMs: number;
  ipAddress: string | null;
  createdAt: string;
}

interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  number: number;
  size: number;
}

const WINDOWS = [
  { days: 1, hi: "24 घंटे", en: "24 hours" },
  { days: 7, hi: "7 दिन", en: "7 days" },
  { days: 30, hi: "30 दिन", en: "30 days" },
  { days: 90, hi: "90 दिन", en: "90 days" },
];

function formatWhen(iso: string | null) {
  if (!iso) return "—";
  return new Date(iso).toLocaleString("en-IN", {
    dateStyle: "medium",
    timeStyle: "short",
    timeZone: "Asia/Kolkata",
  });
}

/** Colour by class: 2xx quiet, 4xx amber (caller's fault), 5xx red (ours). */
function statusClass(status: number) {
  if (status >= 500) return "bg-red-100 text-red-700";
  if (status >= 400) return "bg-amber-100 text-amber-800";
  return "bg-green-100 text-green-700";
}

const METHOD_CLASS: Record<string, string> = {
  GET: "text-sky-700",
  POST: "text-green-700",
  PUT: "text-amber-700",
  PATCH: "text-amber-700",
  DELETE: "text-red-700",
};

export default function ApiUsagePage() {
  const [days, setDays] = useState(7);
  const [page, setPage] = useState(0);
  const [drillUser, setDrillUser] = useState<UsageSummary | null>(null);

  const { data: totals } = useQuery<{ totalCalls: number }>({
    queryKey: ["api-usage-totals", days],
    queryFn: async () => (await adminApi.apiUsageTotals({ days })).data,
  });

  const { data: summary, isLoading } = useQuery<PageResponse<UsageSummary>>({
    queryKey: ["api-usage-summary", days, page],
    queryFn: async () =>
      (await adminApi.apiUsageSummary({ days, page, size: 20 })).data,
    enabled: !drillUser,
  });

  const { data: endpoints } = useQuery<PageResponse<EndpointUsage>>({
    queryKey: ["api-usage-endpoints", days],
    queryFn: async () =>
      (await adminApi.apiUsageEndpoints({ days, page: 0, size: 10 })).data,
    enabled: !drillUser,
  });

  const { data: userRequests, isLoading: drillLoading } = useQuery<PageResponse<RequestRow>>({
    queryKey: ["api-usage-user", drillUser?.userId, page],
    queryFn: async () =>
      (await adminApi.apiUsageForUser(drillUser!.userId, { page, size: 25 })).data,
    enabled: !!drillUser,
  });

  function selectWindow(d: number) {
    setDays(d);
    setPage(0);
  }

  function openUser(u: UsageSummary) {
    setDrillUser(u);
    setPage(0);
  }

  function backToSummary() {
    setDrillUser(null);
    setPage(0);
  }

  /* ───── Drill-down: one user's recent requests ───── */
  if (drillUser) {
    return (
      <div className="space-y-5">
        <button
          onClick={backToSummary}
          className="inline-flex items-center gap-1.5 text-sm font-medium text-indigo-600 hover:text-indigo-800"
        >
          <ArrowLeft className="h-4 w-4" />
          सभी उपयोगकर्ता / All users
        </button>

        <div>
          <h2 className="text-xl font-semibold text-gray-900">
            {drillUser.userName ?? drillUser.userEmail}
          </h2>
          <p className="text-sm text-gray-500">{drillUser.userEmail}</p>
        </div>

        <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
          {drillLoading ? (
            <div className="flex justify-center p-10">
              <Loader2 className="h-6 w-6 animate-spin text-indigo-600" />
            </div>
          ) : !userRequests?.content.length ? (
            <p className="p-8 text-center text-sm text-gray-500">
              इस उपयोगकर्ता का कोई अनुरोध नहीं / No requests recorded for this user
            </p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 text-left text-xs uppercase tracking-wide text-gray-500">
                  <tr>
                    <th className="px-4 py-3">समय / Time</th>
                    <th className="px-4 py-3">विधि / Method</th>
                    <th className="px-4 py-3">एंडपॉइंट / Endpoint</th>
                    <th className="px-4 py-3">स्थिति / Status</th>
                    <th className="px-4 py-3">अवधि / Duration</th>
                    <th className="px-4 py-3">IP</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {userRequests.content.map((r) => (
                    <tr key={r.id} className="hover:bg-gray-50">
                      <td className="whitespace-nowrap px-4 py-2.5 text-gray-600">
                        {formatWhen(r.createdAt)}
                      </td>
                      <td className={`px-4 py-2.5 font-mono text-xs font-semibold ${METHOD_CLASS[r.method] ?? "text-gray-600"}`}>
                        {r.method}
                      </td>
                      <td className="px-4 py-2.5 font-mono text-xs text-gray-800">{r.path}</td>
                      <td className="px-4 py-2.5">
                        <span className={`rounded px-1.5 py-0.5 text-xs font-medium ${statusClass(r.status)}`}>
                          {r.status}
                        </span>
                      </td>
                      <td className="px-4 py-2.5 text-gray-600">{r.durationMs} ms</td>
                      <td className="px-4 py-2.5 font-mono text-xs text-gray-500">{r.ipAddress ?? "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
          {userRequests && userRequests.totalPages > 1 && (
            <Pager
              page={userRequests.number}
              totalPages={userRequests.totalPages}
              totalElements={userRequests.totalElements}
              onPage={setPage}
            />
          )}
        </div>
      </div>
    );
  }

  /* ───── Summary ───── */
  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <BarChart3 className="h-5 w-5 text-indigo-600" />
          <h2 className="text-xl font-semibold text-gray-900">
            API उपयोग / API Usage
          </h2>
        </div>
        <div className="flex gap-1 rounded-lg border border-gray-200 bg-white p-1">
          {WINDOWS.map((w) => (
            <button
              key={w.days}
              onClick={() => selectWindow(w.days)}
              className={`rounded px-3 py-1 text-xs font-medium transition ${
                days === w.days
                  ? "bg-indigo-600 text-white"
                  : "text-gray-600 hover:bg-gray-100"
              }`}
            >
              {w.en}
            </button>
          ))}
        </div>
      </div>

      <p className="text-sm text-gray-500">
        पिछले {days} दिनों में कुल {totals?.totalCalls ?? 0} अनुरोध — 90 दिनों तक रखा जाता है /{" "}
        {totals?.totalCalls ?? 0} requests in the last {days} days. History is kept for 90 days.
      </p>

      {/* Per-user table */}
      <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
        <div className="border-b border-gray-100 px-4 py-3">
          <h3 className="text-sm font-semibold text-gray-900">
            प्रति उपयोगकर्ता / Per user
          </h3>
        </div>
        {isLoading ? (
          <div className="flex justify-center p-10">
            <Loader2 className="h-6 w-6 animate-spin text-indigo-600" />
          </div>
        ) : !summary?.content.length ? (
          <p className="p-8 text-center text-sm text-gray-500">
            इस अवधि में कोई गतिविधि नहीं / No activity in this window
          </p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 text-left text-xs uppercase tracking-wide text-gray-500">
                <tr>
                  <th className="px-4 py-3">उपयोगकर्ता / User</th>
                  <th className="px-4 py-3">कुल कॉल / Calls</th>
                  <th className="px-4 py-3">त्रुटियाँ / Errors</th>
                  <th className="px-4 py-3">अंतिम बार / Last seen</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {summary.content.map((u) => (
                  <tr
                    key={u.userId}
                    onClick={() => openUser(u)}
                    className="cursor-pointer hover:bg-indigo-50/50"
                  >
                    <td className="px-4 py-2.5">
                      <div className="font-medium text-gray-900">{u.userName ?? "—"}</div>
                      <div className="text-xs text-gray-500">{u.userEmail}</div>
                    </td>
                    <td className="px-4 py-2.5 font-semibold text-gray-900">{u.totalCalls}</td>
                    <td className="px-4 py-2.5">
                      {u.errorCalls > 0 ? (
                        <span className="inline-flex items-center gap-1 rounded bg-amber-100 px-1.5 py-0.5 text-xs font-medium text-amber-800">
                          <AlertTriangle className="h-3 w-3" />
                          {u.errorCalls}
                        </span>
                      ) : (
                        <span className="text-gray-400">0</span>
                      )}
                    </td>
                    <td className="whitespace-nowrap px-4 py-2.5 text-gray-600">
                      {formatWhen(u.lastSeenAt)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {summary && summary.totalPages > 1 && (
          <Pager
            page={summary.number}
            totalPages={summary.totalPages}
            totalElements={summary.totalElements}
            onPage={setPage}
          />
        )}
      </div>

      {/* Busiest endpoints */}
      <div className="rounded-lg border border-gray-200 bg-white shadow-sm overflow-hidden">
        <div className="border-b border-gray-100 px-4 py-3">
          <h3 className="text-sm font-semibold text-gray-900">
            व्यस्ततम एंडपॉइंट / Busiest endpoints
          </h3>
          <p className="mt-0.5 text-xs text-gray-500">
            अनाम ट्रैफ़िक सहित / Includes unauthenticated traffic
          </p>
        </div>
        {!endpoints?.content.length ? (
          <p className="p-8 text-center text-sm text-gray-500">—</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 text-left text-xs uppercase tracking-wide text-gray-500">
                <tr>
                  <th className="px-4 py-3">विधि / Method</th>
                  <th className="px-4 py-3">एंडपॉइंट / Endpoint</th>
                  <th className="px-4 py-3">कॉल / Calls</th>
                  <th className="px-4 py-3">त्रुटियाँ / Errors</th>
                  <th className="px-4 py-3">औसत / Avg</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {endpoints.content.map((e) => (
                  <tr key={`${e.method}-${e.path}`} className="hover:bg-gray-50">
                    <td className={`px-4 py-2.5 font-mono text-xs font-semibold ${METHOD_CLASS[e.method] ?? "text-gray-600"}`}>
                      {e.method}
                    </td>
                    <td className="px-4 py-2.5 font-mono text-xs text-gray-800">{e.path}</td>
                    <td className="px-4 py-2.5 font-semibold text-gray-900">{e.calls}</td>
                    <td className="px-4 py-2.5 text-gray-600">{e.errorCalls}</td>
                    <td className="px-4 py-2.5 text-gray-600">
                      {e.avgDurationMs != null ? `${Math.round(e.avgDurationMs)} ms` : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

function Pager({
  page,
  totalPages,
  totalElements,
  onPage,
}: {
  page: number;
  totalPages: number;
  totalElements: number;
  onPage: (p: number) => void;
}) {
  return (
    <div className="flex items-center justify-between border-t border-gray-100 px-4 py-3">
      <span className="text-xs text-gray-500">
        {totalElements} कुल / total · पृष्ठ {page + 1} / {totalPages}
      </span>
      <div className="flex gap-1">
        <button
          onClick={() => onPage(page - 1)}
          disabled={page === 0}
          className="rounded border border-gray-200 p-1.5 text-gray-600 transition hover:bg-gray-50 disabled:opacity-40"
        >
          <ChevronLeft className="h-4 w-4" />
        </button>
        <button
          onClick={() => onPage(page + 1)}
          disabled={page + 1 >= totalPages}
          className="rounded border border-gray-200 p-1.5 text-gray-600 transition hover:bg-gray-50 disabled:opacity-40"
        >
          <ChevronRight className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}
