'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { FiX, FiDownload } from 'react-icons/fi';
import toast from 'react-hot-toast';
import {
  getDocumentAccessLog,
  exportDocumentAccessLogCsv,
} from '@/lib/api/documents.api';
import type {
  AccessLogEntry,
  DocumentRow,
} from '@/lib/api/types/documents.types';
import { ACTION_META, formatDateTime } from '@/lib/api/mappers/documents.mappers';

interface Props {
  isOpen: boolean;
  document: DocumentRow | null;
  onClose: () => void;
  /** Whether the current user has export_log permission */
  canExport: boolean;
}

export default function AuditLogModal({
  isOpen,
  document: doc,
  onClose,
  canExport,
}: Props) {
  const [entries, setEntries] = useState<AccessLogEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [meta, setMeta] = useState<{
    total: number;
    page: number;
    totalPages: number;
  } | null>(null);
  const [page, setPage] = useState(1);
  const [exporting, setExporting] = useState(false);

  const load = useCallback(
    (pageNum: number) => {
      if (!doc) return;
      setLoading(true);
      getDocumentAccessLog(doc.id, { page: pageNum, limit: 50 })
        .then((res) => {
          setEntries(res.data);
          setMeta({
            total: res.meta.total,
            page: res.meta.page,
            totalPages: res.meta.totalPages,
          });
        })
        .catch((err) => toast.error(err.message || 'Failed to load log'))
        .finally(() => setLoading(false));
    },
    [doc],
  );

  useEffect(() => {
    if (isOpen && doc) {
      setPage(1);
      load(1);
    }
  }, [isOpen, doc, load]);

  if (!isOpen || !doc) return null;

  const handleExport = async () => {
    setExporting(true);
    try {
      await exportDocumentAccessLogCsv(
        doc.id,
        `document-${doc.id}-access-log.csv`,
      );
      toast.success('CSV export ready');
    } catch (err: any) {
      toast.error(err.message || 'Export failed');
    } finally {
      setExporting(false);
    }
  };

  return (
    <div style={overlayStyle} onClick={onClose}>
      <div style={modalStyle} onClick={(e) => e.stopPropagation()}>
        {/* Header */}
        <div style={headerStyle}>
          <div>
            <h2 style={{ margin: 0, fontSize: 17, color: '#1a0440' }}>
              Access log — {doc.title}
            </h2>
            <p style={{ margin: '4px 0 0', fontSize: 12, color: '#8b8397' }}>
              Every open, download and failed attempt is recorded.
            </p>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            {canExport && (
              <button
                onClick={handleExport}
                disabled={exporting}
                style={exportBtnStyle}
              >
                <FiDownload size={12} /> {exporting ? 'Exporting…' : 'Export CSV'}
              </button>
            )}
            <button onClick={onClose} style={closeBtnStyle}>
              <FiX size={20} />
            </button>
          </div>
        </div>

        {/* Body — entries list */}
        <div style={bodyStyle}>
          {loading ? (
            <div style={{ textAlign: 'center', padding: 40, color: '#8b8397' }}>
              Loading…
            </div>
          ) : entries.length === 0 ? (
            <div style={{ textAlign: 'center', padding: 40, color: '#8b8397' }}>
              No access log entries yet.
            </div>
          ) : (
            entries.map((e) => {
              const meta = ACTION_META[e.action];
              return (
                <div key={e.id} style={logRowStyle}>
                  <span style={{ ...avatarStyle, background: meta.bg, color: meta.text }}>
                    {(e.user_name || '?').charAt(0).toUpperCase()}
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13 }}>
                      <b style={{ color: '#1a0440' }}>
                        {e.user_name || `User #${e.user_id}`}
                      </b>{' '}
                      {e.role_name && (
                        <span style={rolePillStyle}>{e.role_name}</span>
                      )}{' '}
                      <span style={{ color: '#6b7280' }}>—</span>{' '}
                      <span
                        style={{
                          fontSize: 11,
                          fontWeight: 700,
                          padding: '2px 8px',
                          borderRadius: 99,
                          background: meta.bg,
                          color: meta.text,
                        }}
                      >
                        {meta.icon} {meta.label}
                      </span>
                    </div>
                    {e.ip_address && (
                      <div style={{ fontSize: 11, color: '#9ca3af', marginTop: 2 }}>
                        IP {e.ip_address}
                        {e.user_agent ? ` · ${truncate(e.user_agent, 60)}` : ''}
                      </div>
                    )}
                  </div>
                  <span style={{ fontSize: 11, color: '#8b8397', whiteSpace: 'nowrap' }}>
                    {formatDateTime(e.created_at)}
                  </span>
                </div>
              );
            })
          )}
        </div>

        {/* Footer — pagination */}
        {meta && meta.totalPages > 1 && (
          <div style={footerStyle}>
            <span style={{ fontSize: 12, color: '#8b8397' }}>
              Page {meta.page} of {meta.totalPages} · {meta.total.toLocaleString()} entries
            </span>
            <div style={{ display: 'flex', gap: 6 }}>
              <button
                onClick={() => {
                  const p = Math.max(1, page - 1);
                  setPage(p);
                  load(p);
                }}
                disabled={page === 1}
                style={pageBtnStyle}
              >
                ← Prev
              </button>
              <button
                onClick={() => {
                  const p = Math.min(meta.totalPages, page + 1);
                  setPage(p);
                  load(p);
                }}
                disabled={page === meta.totalPages}
                style={pageBtnStyle}
              >
                Next →
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function truncate(s: string, n: number): string {
  return s.length > n ? s.slice(0, n) + '…' : s;
}

// ─── Styles ──────────────────────────────────────────────────────────────
const overlayStyle: React.CSSProperties = {
  position: 'fixed',
  inset: 0,
  background: 'rgba(15,23,42,0.55)',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  zIndex: 1000,
  padding: 16,
};
const modalStyle: React.CSSProperties = {
  background: '#fff',
  borderRadius: 16,
  width: '100%',
  maxWidth: 720,
  maxHeight: '92vh',
  overflow: 'hidden',
  boxShadow: '0 24px 48px -12px rgba(0,0,0,0.3)',
  display: 'flex',
  flexDirection: 'column',
};
const headerStyle: React.CSSProperties = {
  padding: '20px 24px',
  borderBottom: '1px solid #eae5f1',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'flex-start',
  gap: 12,
};
const closeBtnStyle: React.CSSProperties = {
  background: 'none',
  border: 'none',
  color: '#8b8397',
  cursor: 'pointer',
  padding: 4,
};
const bodyStyle: React.CSSProperties = {
  padding: '10px 24px',
  overflow: 'auto',
  flex: 1,
};
const logRowStyle: React.CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  gap: 12,
  padding: '10px 0',
  borderBottom: '1px solid #f1f5f9',
};
const avatarStyle: React.CSSProperties = {
  width: 32,
  height: 32,
  borderRadius: '50%',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  fontSize: 12,
  fontWeight: 800,
  flex: 'none',
};
const rolePillStyle: React.CSSProperties = {
  fontSize: 10,
  fontWeight: 700,
  padding: '2px 8px',
  borderRadius: 99,
  background: '#f3eefb',
  color: '#7c3aed',
};
const footerStyle: React.CSSProperties = {
  padding: '12px 24px',
  borderTop: '1px solid #eae5f1',
  background: '#faf9fd',
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
};
const pageBtnStyle: React.CSSProperties = {
  padding: '6px 12px',
  borderRadius: 8,
  border: '1px solid #eae5f1',
  background: '#fff',
  fontSize: 12,
  fontWeight: 600,
  cursor: 'pointer',
  color: '#374151',
};
const exportBtnStyle: React.CSSProperties = {
  padding: '7px 12px',
  borderRadius: 8,
  border: '1px solid #eae5f1',
  background: '#fff',
  fontSize: 12,
  fontWeight: 700,
  cursor: 'pointer',
  color: '#7c3aed',
  display: 'inline-flex',
  alignItems: 'center',
  gap: 4,
};
