"use client";

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

interface AuditLog {
  id: number;
  userId: string | null;
  userName: string | null;
  userEmail: string | null;
  action: string;
  entityType: string;
  entityId: string | null;
  details: string | null;
  ipAddress: string | null;
  createdAt: string;
}

interface PageResponse {
  content: AuditLog[];
  totalElements: number;
  totalPages: number;
  number: number;
  size: number;
}

const ACTION_LABELS: Record<string, { hi: string; en: string; color: string }> = {
  LOGIN: { hi: "लॉगिन", en: "Login", color: "bg-blue-100 text-blue-700" },
  // Security-relevant: a run of these from one IP is a brute-force attempt, so
  // it is coloured to stand out rather than blending into routine activity.
  LOGIN_FAILED: { hi: "लॉगिन विफल", en: "Login Failed", color: "bg-red-100 text-red-700" },
  REGISTER: { hi: "पंजीकरण", en: "Register", color: "bg-green-100 text-green-700" },
  OTP_SEND: { hi: "OTP भेजा", en: "OTP Sent", color: "bg-yellow-100 text-yellow-700" },
  OTP_VERIFY: { hi: "OTP सत्यापित", en: "OTP Verified", color: "bg-yellow-100 text-yellow-700" },
  CHANGE_PASSWORD: { hi: "पासवर्ड बदला", en: "Password Changed", color: "bg-orange-100 text-orange-700" },
  UPDATE_PROFILE: { hi: "प्रोफ़ाइल अपडेट", en: "Profile Updated", color: "bg-purple-100 text-purple-700" },
  PAPER_SUBMIT: { hi: "पेपर प्रस्तुत", en: "Paper Submitted", color: "bg-indigo-100 text-indigo-700" },
  PAPER_UPDATE: { hi: "पेपर अपडेट", en: "Paper Updated", color: "bg-indigo-100 text-indigo-700" },
  PAPER_REVISION_UPLOAD: { hi: "संशोधन अपलोड", en: "Revision Uploaded", color: "bg-indigo-100 text-indigo-700" },
  PAPER_ASSIGN_REVIEWER: { hi: "समीक्षक नियुक्त", en: "Reviewer Assigned", color: "bg-cyan-100 text-cyan-700" },
  PAPER_STATUS_CHANGE: { hi: "स्थिति बदली", en: "Status Changed", color: "bg-amber-100 text-amber-700" },
  PAPER_PUBLISH: { hi: "पेपर प्रकाशित", en: "Paper Published", color: "bg-green-100 text-green-700" },
  REVIEW_SUBMIT: { hi: "समीक्षा प्रस्तुत", en: "Review Submitted", color: "bg-teal-100 text-teal-700" },
  REVIEW_DECLINE: { hi: "समीक्षा अस्वीकृत", en: "Review Declined", color: "bg-red-100 text-red-700" },
  USER_CREATE: { hi: "उपयोगकर्ता बनाया", en: "User Created", color: "bg-green-100 text-green-700" },
  USER_UPDATE: { hi: "उपयोगकर्ता अपडेट", en: "User Updated", color: "bg-purple-100 text-purple-700" },
  USER_TOGGLE_STATUS: { hi: "स्थिति टॉगल", en: "Status Toggled", color: "bg-orange-100 text-orange-700" },
  USER_DELETE: { hi: "उपयोगकर्ता हटाया", en: "User Deleted", color: "bg-red-100 text-red-700" },
  CATEGORY_CREATE: { hi: "श्रेणी बनाई", en: "Category Created", color: "bg-green-100 text-green-700" },
  CATEGORY_UPDATE: { hi: "श्रेणी अपडेट", en: "Category Updated", color: "bg-purple-100 text-purple-700" },
  CATEGORY_TOGGLE: { hi: "श्रेणी टॉगल", en: "Category Toggled", color: "bg-orange-100 text-orange-700" },
  CATEGORY_DELETE: { hi: "श्रेणी हटाई", en: "Category Deleted", color: "bg-red-100 text-red-700" },
  CMS_UPDATE: { hi: "CMS अपडेट", en: "CMS Updated", color: "bg-purple-100 text-purple-700" },
  CMS_IMPORT: { hi: "CMS आयात", en: "CMS Imported", color: "bg-blue-100 text-blue-700" },
  MAGAZINE_CREATE: { hi: "पत्रिका बनाई", en: "Magazine Created", color: "bg-green-100 text-green-700" },
  MAGAZINE_GENERATE_PDF: { hi: "PDF बनाया", en: "PDF Generated", color: "bg-indigo-100 text-indigo-700" },
  MAGAZINE_PUBLISH: { hi: "पत्रिका प्रकाशित", en: "Magazine Published", color: "bg-green-100 text-green-700" },
  PAYMENT_CREATE_ORDER: { hi: "भुगतान ऑर्डर", en: "Payment Order", color: "bg-yellow-100 text-yellow-700" },
  PAYMENT_VERIFY: { hi: "भुगतान सत्यापित", en: "Payment Verified", color: "bg-green-100 text-green-700" },
  PAYMENT_VERIFY_FAILED: { hi: "भुगतान हस्ताक्षर अमान्य", en: "Payment Signature Invalid", color: "bg-red-100 text-red-700" },
  PAYMENT_VERIFY_REJECTED: { hi: "भुगतान अस्वीकृत (गेटवे कॉन्फ़िगर नहीं)", en: "Payment Rejected (gateway not configured)", color: "bg-red-100 text-red-700" },
};

const ENTITY_TYPES = ["USER", "PAPER", "REVIEW", "CATEGORY", "CMS", "MAGAZINE", "PAYMENT", "AUTH"];

export default function ActivityLogPage() {
  const [page, setPage] = useState(0);
  const [actionFilter, setActionFilter] = useState("");
  const [entityFilter, setEntityFilter] = useState("");
  const [showFilters, setShowFilters] = useState(false);
  const pageSize = 20;

  const { data, isLoading } = useQuery<PageResponse>({
    queryKey: ["audit-logs", page, actionFilter, entityFilter],
    queryFn: async () => {
      const params: Record<string, unknown> = {
        page,
        size: pageSize,
        sort: "createdAt,desc",
      };
      if (actionFilter) params.action = actionFilter;
      if (entityFilter) params.entityType = entityFilter;
      const res = await adminApi.auditLogs(params);
      return res.data;
    },
  });

  const formatDate = (dateStr: string) => {
    const d = new Date(dateStr);
    return d.toLocaleDateString("en-IN", {
      day: "2-digit",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const parseDetails = (details: string | null): Record<string, string> | null => {
    if (!details) return null;
    try {
      return JSON.parse(details);
    } catch {
      return null;
    }
  };

  if (isLoading && !data) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-3">
        <Loader2 className="h-8 w-8 animate-spin text-indigo-500" />
        <p className="text-sm text-gray-400">लोड हो रहा है... / Loading...</p>
      </div>
    );
  }

  const logs = data?.content ?? [];
  const totalPages = data?.totalPages ?? 0;
  const totalElements = data?.totalElements ?? 0;

  return (
    <div className="mx-auto max-w-6xl px-4 sm:px-6 py-8">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <Activity className="h-6 w-6 text-indigo-600" />
            गतिविधि लॉग / Activity Log
          </h1>
          <p className="text-sm text-gray-500 mt-1">
            {totalElements} रिकॉर्ड / {totalElements} records
          </p>
        </div>
        <button
          onClick={() => setShowFilters(!showFilters)}
          className="flex items-center gap-2 rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-600 hover:bg-gray-50 transition-colors"
        >
          <Filter className="h-4 w-4" />
          फ़िल्टर / Filters
        </button>
      </div>

      {/* Filters */}
      {showFilters && (
        <div className="rounded-xl border border-gray-100 bg-white p-4 shadow-sm mb-6 flex flex-wrap gap-4">
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">कार्रवाई / Action</label>
            <select
              value={actionFilter}
              onChange={(e) => { setActionFilter(e.target.value); setPage(0); }}
              className="rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
            >
              <option value="">सभी / All</option>
              {Object.keys(ACTION_LABELS).map((action) => (
                <option key={action} value={action}>
                  {ACTION_LABELS[action].en}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">इकाई / Entity Type</label>
            <select
              value={entityFilter}
              onChange={(e) => { setEntityFilter(e.target.value); setPage(0); }}
              className="rounded-lg border border-gray-200 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
            >
              <option value="">सभी / All</option>
              {ENTITY_TYPES.map((t) => (
                <option key={t} value={t}>{t}</option>
              ))}
            </select>
          </div>
          {(actionFilter || entityFilter) && (
            <div className="flex items-end">
              <button
                onClick={() => { setActionFilter(""); setEntityFilter(""); setPage(0); }}
                className="rounded-lg bg-gray-100 px-4 py-2 text-sm text-gray-600 hover:bg-gray-200 transition-colors"
              >
                रीसेट / Reset
              </button>
            </div>
          )}
        </div>
      )}

      {/* Table */}
      <div className="rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-100">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">समय / Time</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">उपयोगकर्ता / User</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">कार्रवाई / Action</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">इकाई / Entity</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase">विवरण / Details</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {logs.length === 0 ? (
                <tr>
                  <td colSpan={5} className="px-4 py-12 text-center text-sm text-gray-400">
                    कोई गतिविधि नहीं / No activity logs found
                  </td>
                </tr>
              ) : (
                logs.map((log) => {
                  const label = ACTION_LABELS[log.action] ?? { hi: log.action, en: log.action, color: "bg-gray-100 text-gray-700" };
                  const details = parseDetails(log.details);

                  return (
                    <tr key={log.id} className="hover:bg-gray-50/50 transition-colors">
                      <td className="px-4 py-3 text-xs text-gray-500 whitespace-nowrap">
                        {formatDate(log.createdAt)}
                      </td>
                      <td className="px-4 py-3">
                        {log.userName ? (
                          <div>
                            <p className="text-sm font-medium text-gray-900">{log.userName}</p>
                            <p className="text-xs text-gray-400">{log.userEmail}</p>
                          </div>
                        ) : (
                          <span className="text-xs text-gray-400">System</span>
                        )}
                      </td>
                      <td className="px-4 py-3">
                        <span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ${label.color}`}>
                          {label.en}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <span className="text-xs font-medium text-gray-600">{log.entityType}</span>
                        {log.entityId && (
                          <p className="text-[10px] text-gray-400 font-mono truncate max-w-[120px]" title={log.entityId}>
                            {log.entityId}
                          </p>
                        )}
                      </td>
                      <td className="px-4 py-3 text-xs text-gray-500 max-w-xs">
                        {details ? (
                          <div className="flex flex-wrap gap-1">
                            {Object.entries(details).map(([k, v]) => (
                              <span key={k} className="inline-flex items-center gap-0.5 bg-gray-50 rounded px-1.5 py-0.5 text-[10px]">
                                <span className="text-gray-400">{k}:</span>
                                <span className="text-gray-700 truncate max-w-[100px]" title={String(v)}>{String(v)}</span>
                              </span>
                            ))}
                          </div>
                        ) : (
                          <span className="text-gray-300">-</span>
                        )}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t border-gray-100 px-4 py-3">
            <p className="text-xs text-gray-500">
              पृष्ठ {page + 1} / {totalPages}
            </p>
            <div className="flex gap-2">
              <button
                onClick={() => setPage(Math.max(0, page - 1))}
                disabled={page === 0}
                className="flex items-center gap-1 rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronLeft className="h-3.5 w-3.5" />
                पिछला / Prev
              </button>
              <button
                onClick={() => setPage(Math.min(totalPages - 1, page + 1))}
                disabled={page >= totalPages - 1}
                className="flex items-center gap-1 rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-medium text-gray-600 hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
              >
                अगला / Next
                <ChevronRight className="h-3.5 w-3.5" />
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
