'use client';

import React from 'react';
import { FiEye, FiDownload, FiTrash2, FiEdit2, FiActivity, FiLock } from 'react-icons/fi';
import type { DocumentRow } from '@/lib/api/types/documents.types';
import {
  getCategoryMeta,
  STATUS_CONFIG,
  formatSecuritySummary,
  fileIconMeta,
  formatFileSize,
  formatDate,
  expiryHint,
} from '@/lib/api/mappers/documents.mappers';

interface Props {
  row: DocumentRow;
  onOpen: (row: DocumentRow) => void;         // triggers unlock modal
  onEdit: (row: DocumentRow) => void;
  onDelete: (row: DocumentRow) => void;
  onViewLog: (row: DocumentRow) => void;
  isBusy?: boolean;
  /** Permitted action keys for THIS user on the documents module */
  permittedActions: Set<string>;
  /** True when the caller is an admin (shows more columns) */
  isAdminView: boolean;
}

export default function DocumentRowComponent({
  row,
  onOpen,
  onEdit,
  onDelete,
  onViewLog,
  isBusy,
  permittedActions,
  isAdminView,
}: Props) {
  const category = getCategoryMeta(row.category);
  const status = STATUS_CONFIG[row.status];
  const icon = fileIconMeta(row.mime_type);
  const security = formatSecuritySummary(row);
  const expiry = expiryHint(row.expiry_date);

  // ✅ PERMISSION GATING — same shape as MyAuditRow
  const canView = permittedActions.has('view') || permittedActions.has('view_all');
  const canDownload = permittedActions.has('download') && row.allow_download === 1;
  const canEdit = permittedActions.has('edit');
  const canDelete = permittedActions.has('delete');
  const canViewLog = permittedActions.has('view_log');

  const isArchived = row.status === 'archived';

  return (
    <tr
      style={{
        borderTop: '1px solid #f1f5f9',
        opacity: isArchived ? 0.6 : 1,
        transition: 'background 0.15s',
      }}
    >
      {/* 1. Document (icon + title + category) */}
      <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
          <span
            style={{
              width: 38,
              height: 38,
              borderRadius: 9,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 10,
              fontWeight: 800,
              background: icon.bg,
              color: icon.text,
              flex: 'none',
            }}
          >
            {icon.label}
          </span>
          <div style={{ minWidth: 0 }}>
            <div
              style={{
                fontSize: 13.5,
                fontWeight: 600,
                color: '#111827',
                marginBottom: 3,
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                maxWidth: 260,
              }}
              title={row.title}
            >
              {row.title}
            </div>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
              <span
                style={{
                  fontSize: 10,
                  fontWeight: 700,
                  padding: '2px 8px',
                  borderRadius: 99,
                  background: category.bg,
                  color: category.text,
                }}
              >
                {category.icon} {category.label}
              </span>
              <span style={{ fontSize: 11, color: '#9ca3af' }}>
                {formatFileSize(row.file_size)}
              </span>
            </div>
          </div>
        </div>
      </td>

      {/* 2. Assigned to (role chips) */}
      <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {row.role_assignments && row.role_assignments.length > 0 ? (
            row.role_assignments.map((ra) => (
              <span
                key={ra.id}
                style={{
                  fontSize: 10,
                  fontWeight: 700,
                  padding: '2px 8px',
                  borderRadius: 99,
                  background: '#f3eefb',
                  color: '#7c3aed',
                }}
              >
                {ra.role_name || `Role ${ra.role_id}`}
              </span>
            ))
          ) : (
            <span style={{ color: '#9ca3af', fontSize: 12 }}>—</span>
          )}
        </div>
      </td>

      {/* 3. Security */}
      <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
        <span style={{ fontSize: 11.5, color: '#6b7280' }}>{security}</span>
      </td>

      {/* 4. Admin-only: opens (opens / failed counts) */}
      {isAdminView && (
        <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
          <div style={{ fontSize: 12.5, color: '#111827' }}>
            <b>{row.open_count ?? 0}</b>
            {typeof row.failed_count === 'number' && row.failed_count > 0 && (
              <span style={{ color: '#dc2626', marginLeft: 6 }}>
                / {row.failed_count} failed
              </span>
            )}
          </div>
        </td>
      )}

      {/* 5. Status + expiry hint */}
      <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          <span
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 6,
              padding: '3px 9px',
              borderRadius: 99,
              background: status.bg,
              color: status.text,
              fontSize: 11,
              fontWeight: 700,
              width: 'fit-content',
            }}
          >
            <span
              style={{
                width: 6,
                height: 6,
                borderRadius: '50%',
                background: status.dot,
              }}
            />
            {status.label}
          </span>
          {expiry && (
            <span style={{ fontSize: 10.5, color: expiry.color, fontWeight: 600 }}>
              {expiry.label}
            </span>
          )}
        </div>
      </td>

      {/* 6. Uploaded */}
      <td style={{ padding: '12px 10px', verticalAlign: 'top', fontSize: 12, color: '#6b7280' }}>
        {formatDate(row.created_at)}
      </td>

      {/* 7. Actions — gated by permittedActions */}
      <td style={{ padding: '12px 10px', verticalAlign: 'top' }}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {canView && !isArchived && (
            <button
              onClick={() => onOpen(row)}
              disabled={isBusy}
              title={row.require_otp ? 'Unlock with OTP' : 'Open document'}
              style={btnStyle('#eef2ff', '#4338ca', '#c7d2fe')}
            >
              {row.require_otp || row.password_hash ? (
                <>
                  <FiLock size={12} /> Open
                </>
              ) : (
                <>
                  <FiEye size={12} /> View
                </>
              )}
            </button>
          )}

          {canDownload && !isArchived && (
            <button
              onClick={() => onOpen(row)}
              title="Download"
              style={btnStyle('#f0fdf4', '#166534', '#86efac')}
            >
              <FiDownload size={12} />
            </button>
          )}

          {canViewLog && (
            <button
              onClick={() => onViewLog(row)}
              title="View access log"
              style={btnStyle('#fefce8', '#854d0e', '#fde68a')}
            >
              <FiActivity size={12} />
            </button>
          )}

          {canEdit && (
            <button
              onClick={() => onEdit(row)}
              title="Edit"
              style={btnStyle('#eff6ff', '#1d4ed8', '#bfdbfe')}
            >
              <FiEdit2 size={12} />
            </button>
          )}

          {canDelete && !isArchived && (
            <button
              onClick={() => onDelete(row)}
              title="Archive"
              style={btnStyle('#fef2f2', '#b91c1c', '#fecaca')}
            >
              <FiTrash2 size={12} />
            </button>
          )}
        </div>
      </td>
    </tr>
  );
}

// Small helper so every action button shares one visual style
function btnStyle(bg: string, color: string, border: string): React.CSSProperties {
  return {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 4,
    padding: '5px 10px',
    borderRadius: 6,
    border: `1px solid ${border}`,
    background: bg,
    color,
    fontSize: 11,
    fontWeight: 600,
    cursor: 'pointer',
    whiteSpace: 'nowrap',
  };
}
