"use client";

import React, { useEffect, useState } from "react";
import { FiX, FiActivity, FiClock } from "react-icons/fi";
import {
  getClientActivityLog,
  type PortalClientRow,
  type ClientActivityLog,
} from "../client-portal.api";

interface Props {
  isOpen: boolean;
  onClose: () => void;
  client: PortalClientRow;
}

const ACTION_ICONS: Record<string, string> = {
  LOGIN: "🔑",
  LOGOUT: "🚪",
  VIEW_AUDIT: "👁️",
  VIEW_CERTIFICATE: "📜",
  VIEW_REPORT: "📊",
  DOWNLOAD_REPORT: "⬇️",
  VIEW_NC: "⚠️",
  SUBMIT_NC_RESPONSE: "📤",
  UPLOAD_DOCUMENT: "📎",
  VIEW_CHECKLIST: "✅",
  OTP_VERIFIED: "🔐",
  INVITE_SENT: "📩",
  ACCESS_ENABLED: "🟢",
  ACCESS_DISABLED: "🔒",
};

function formatDateTime(d: string): string {
  try {
    const dt = new Date(d);
    return `${dt.toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    })} ${dt.toLocaleTimeString("en-GB", {
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    })}`;
  } catch {
    return d;
  }
}

export default function ClientActivityLogModal({
  isOpen,
  onClose,
  client,
}: Props) {
  const [logs, setLogs] = useState<ClientActivityLog[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  useEffect(() => {
    if (!isOpen) return;
    setLoading(true);
    getClientActivityLog(client.company_id, client.user_id, {
      page,
      limit: 20,
    })
      .then((res) => {
        setLogs(res.data);
        setTotalPages(res.lastPage);
      })
      .catch(() => setLogs([]))
      .finally(() => setLoading(false));
  }, [isOpen, client.company_id, client.user_id, page]);

  if (!isOpen) return null;

  return (
    <>
      <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          background: "rgba(0,0,0,0.5)",
          zIndex: 9998,
        }}
      />

      <div
        style={{
          position: "fixed",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          zIndex: 9999,
          background: "#fff",
          borderRadius: 16,
          boxShadow: "0 20px 60px rgba(0,0,0,0.2)",
          width: "min(640px, 95vw)",
          maxHeight: "85vh",
          display: "flex",
          flexDirection: "column",
        }}
      >
        {/* Header */}
        <div
          style={{
            padding: "20px 24px",
            borderBottom: "1px solid #e5e7eb",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            background: "linear-gradient(135deg, #0f766e, #14b8a6)",
            borderRadius: "16px 16px 0 0",
            flexShrink: 0,
          }}
        >
          <div>
            <h2
              style={{
                margin: 0,
                fontSize: 18,
                fontWeight: 800,
                color: "#fff",
                display: "flex",
                alignItems: "center",
                gap: 8,
              }}
            >
              <FiActivity size={18} /> Activity Log
            </h2>
            <p
              style={{
                margin: "4px 0 0",
                fontSize: 12,
                color: "rgba(255,255,255,0.8)",
              }}
            >
              {client.client_name} · {client.company_name}
            </p>
          </div>
          <button
            onClick={onClose}
            style={{
              background: "rgba(255,255,255,0.2)",
              border: "none",
              borderRadius: 8,
              padding: 8,
              cursor: "pointer",
              color: "#fff",
            }}
          >
            <FiX size={18} />
          </button>
        </div>

        {/* Client info summary */}
        <div
          style={{
            padding: "14px 24px",
            background: "#f0fdfa",
            borderBottom: "1px solid #99f6e4",
            display: "flex",
            gap: 20,
            flexWrap: "wrap",
            fontSize: 12,
            flexShrink: 0,
          }}
        >
          <div>
            <span style={{ color: "#6b7280" }}>Email: </span>
            <strong>{client.client_email}</strong>
          </div>
          <div>
            <span style={{ color: "#6b7280" }}>Status: </span>
            <strong
              style={{
                color:
                  client.status === "ACTIVE"
                    ? "#166534"
                    : client.status === "DISABLED"
                      ? "#991b1b"
                      : "#92400e",
              }}
            >
              {client.status}
            </strong>
          </div>
          <div>
            <span style={{ color: "#6b7280" }}>Last Login: </span>
            <strong>
              {client.last_login_at
                ? formatDateTime(client.last_login_at)
                : "Never"}
            </strong>
          </div>
        </div>

        {/* Log entries */}
        <div
          style={{ flex: 1, overflowY: "auto", padding: "16px 24px" }}
        >
          {loading ? (
            <div
              style={{
                textAlign: "center",
                padding: 40,
                color: "#9ca3af",
              }}
            >
              Loading activity log...
            </div>
          ) : logs.length === 0 ? (
            <div
              style={{
                textAlign: "center",
                padding: 40,
                color: "#9ca3af",
              }}
            >
              <div style={{ fontSize: 36, marginBottom: 8 }}>📋</div>
              <div style={{ fontSize: 14, fontWeight: 600 }}>
                No activity recorded yet
              </div>
              <div style={{ fontSize: 12, marginTop: 4 }}>
                Activity will appear here once the client uses the
                portal.
              </div>
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {logs.map((log) => (
                <div
                  key={log.id}
                  style={{
                    padding: "12px 14px",
                    borderRadius: 10,
                    border: "1px solid #e5e7eb",
                    background: "#fafafa",
                    display: "flex",
                    alignItems: "flex-start",
                    gap: 10,
                  }}
                >
                  <div
                    style={{
                      fontSize: 20,
                      flexShrink: 0,
                      lineHeight: 1,
                    }}
                  >
                    {ACTION_ICONS[log.action] || "📌"}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div
                      style={{
                        fontSize: 13,
                        fontWeight: 600,
                        color: "#0f172a",
                      }}
                    >
                      {log.action.replace(/_/g, " ")}
                    </div>
                    {log.details && (
                      <div
                        style={{
                          fontSize: 12,
                          color: "#64748b",
                          marginTop: 2,
                        }}
                      >
                        {log.details}
                      </div>
                    )}
                  </div>
                  <div
                    style={{
                      fontSize: 11,
                      color: "#9ca3af",
                      whiteSpace: "nowrap",
                      display: "flex",
                      alignItems: "center",
                      gap: 4,
                    }}
                  >
                    <FiClock size={10} />
                    {formatDateTime(log.created_at)}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div
            style={{
              padding: "12px 24px",
              borderTop: "1px solid #e5e7eb",
              display: "flex",
              justifyContent: "center",
              gap: 8,
              flexShrink: 0,
            }}
          >
            <button
              disabled={page === 1}
              onClick={() => setPage((p) => p - 1)}
              style={{
                padding: "6px 14px",
                borderRadius: 8,
                border: "1px solid #d1d5db",
                background: "#fff",
                cursor: page === 1 ? "not-allowed" : "pointer",
                fontSize: 13,
                opacity: page === 1 ? 0.4 : 1,
              }}
            >
              ← Prev
            </button>
            <span
              style={{
                display: "flex",
                alignItems: "center",
                fontSize: 13,
                color: "#6b7280",
                fontWeight: 600,
              }}
            >
              Page {page} of {totalPages}
            </span>
            <button
              disabled={page >= totalPages}
              onClick={() => setPage((p) => p + 1)}
              style={{
                padding: "6px 14px",
                borderRadius: 8,
                border: "1px solid #d1d5db",
                background: "#fff",
                cursor: page >= totalPages ? "not-allowed" : "pointer",
                fontSize: 13,
                opacity: page >= totalPages ? 0.4 : 1,
              }}
            >
              Next →
            </button>
          </div>
        )}
      </div>
    </>
  );
}
