/**
 * FileDetails - right column file details panel for DMS.
 * Shows file metadata, action buttons, and permissions.
 */

import React from 'react';
import clsx from 'clsx';
import { useTranslation } from 'react-i18next';
import type { DmsFile } from '@/api/dms';
import { getFileIcon, formatFileSize } from './FileExplorer';
import { Download, Eye, FileText, Share2, Trash2, X } from 'lucide-react';
import { formatDateTime } from '@/utils/date';

function formatDate(dateStr: string | null | undefined): string {
  if (!dateStr) return '-';
  return formatDateTime(dateStr) || '-';
}

function getFileSize(file: DmsFile): number {
  return file.size_bytes ?? file.size ?? 0;
}

export interface FileDetailsProps {
  file: DmsFile | null;
  onPreview: (file: DmsFile) => void;
  onShare: (file: DmsFile) => void;
  onDelete: (file: DmsFile) => void;
  onClose: () => void;
}

export function FileDetails({ file, onPreview, onShare, onDelete, onClose }: FileDetailsProps) {
  const { t } = useTranslation();

  if (!file) {
    return (
      <div className="flex flex-col items-center justify-center h-full p-6 text-center" data-testid="file-details-empty">
        <FileText className="w-12 h-12 text-secondary-300 mb-3" aria-hidden="true" strokeWidth={1.5} />
        <p className="text-sm font-medium text-secondary-600">{t('dms.noFileSelected')}</p>
        <p className="mt-1 text-xs text-secondary-400">{t('dms.noFileSelectedHint')}</p>
      </div>
    );
  }

  const icon = getFileIcon(file.mime_type);
  const uploader = file.uploaded_by || file.created_by || '-';
  const hasPermissions = file.permissions && file.permissions.length > 0;

  return (
    <div className="flex flex-col h-full" data-testid="file-details">
      {/* Header with close button */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-secondary-200">
        <h3 className="text-sm font-semibold text-secondary-900 truncate" title={file.name}>{file.name}</h3>
        <button
          onClick={onClose}
          className="p-1 rounded text-secondary-400 hover:text-secondary-600 hover:bg-secondary-100 min-h-touch min-w-touch"
          aria-label={t('common.close')}
        >
          <X className="w-4 h-4" aria-hidden="true" strokeWidth={2} />
        </button>
      </div>

      {/* Scrollable content */}
      <div className="flex-1 overflow-y-auto p-4">
        {/* File icon (large) */}
        <div className="flex justify-center mb-4">
          {file.mime_type.startsWith('image/') ? (
            <div className="w-24 h-24 bg-secondary-100 rounded-lg flex items-center justify-center overflow-hidden">
              <img
                src={`/api/v1/dms/files/${file.id}/preview`}
                alt={file.name}
                className="w-full h-full object-cover"
                onError={(e) => {
                  (e.target as HTMLImageElement).style.display = 'none';
                }}
              />
            </div>
          ) : (
            <icon.icon className={clsx('w-24 h-24', icon.color)} aria-hidden="true" strokeWidth={1} />
          )}
        </div>

        {/* File name */}
        <p className="text-center text-sm font-medium text-secondary-900 mb-4 break-words" title={file.name}>{file.name}</p>

        {/* Action buttons */}
        <div className="grid grid-cols-2 gap-2 mb-6">
          <button
            onClick={() => onPreview(file)}
            className="inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium bg-primary-50 text-primary-700 hover:bg-primary-100 min-h-touch"
          >
            <Eye className="w-4 h-4" aria-hidden="true" strokeWidth={2} />
            {t('dms.preview')}
          </button>
          <button
            onClick={() => onShare(file)}
            className="inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium bg-secondary-50 text-secondary-700 hover:bg-secondary-100 min-h-touch"
          >
            <Share2 className="w-4 h-4" aria-hidden="true" strokeWidth={2} />
            {t('dms.share')}
          </button>
          <a
            href={`/api/v1/dms/files/${file.id}/preview`}
            download={file.name}
            className="inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium bg-secondary-50 text-secondary-700 hover:bg-secondary-100 min-h-touch"
          >
            <Download className="w-4 h-4" aria-hidden="true" strokeWidth={2} />
            {t('dms.download')}
          </a>
          <button
            onClick={() => onDelete(file)}
            className="inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-md text-xs font-medium bg-danger-50 text-danger-700 hover:bg-danger-100 min-h-touch"
          >
            <Trash2 className="w-4 h-4" aria-hidden="true" strokeWidth={2} />
            {t('dms.delete')}
          </button>
        </div>

        {/* Metadata section */}
        <div className="space-y-3">
          <h4 className="text-xs font-semibold text-secondary-500 uppercase tracking-wide">{t('dms.details')}</h4>
          <dl className="space-y-2">
            <div className="flex justify-between text-sm">
              <dt className="text-secondary-500">{t('dms.fileSize')}</dt>
              <dd className="text-secondary-900 font-medium">{formatFileSize(getFileSize(file))}</dd>
            </div>
            <div className="flex justify-between text-sm">
              <dt className="text-secondary-500">{t('dms.fileType')}</dt>
              <dd className="text-secondary-900 font-medium">{file.mime_type || t('dms.icon.other')}</dd>
            </div>
            <div className="flex justify-between text-sm">
              <dt className="text-secondary-500">{t('dms.fileCreated')}</dt>
              <dd className="text-secondary-900">{formatDate(file.created_at)}</dd>
            </div>
            <div className="flex justify-between text-sm">
              <dt className="text-secondary-500">{t('dms.fileModified')}</dt>
              <dd className="text-secondary-900">{formatDate(file.updated_at)}</dd>
            </div>
            <div className="flex justify-between text-sm">
              <dt className="text-secondary-500">{t('dms.uploadedBy')}</dt>
              <dd className="text-secondary-900 font-mono text-xs">{uploader}</dd>
            </div>
            {file.access_level ? (
              <div className="flex justify-between text-sm">
                <dt className="text-secondary-500">{t('dms.permissionLevel')}</dt>
                <dd className="text-secondary-900 font-medium">{file.access_level}</dd>
              </div>
            ) : null}
          </dl>
        </div>

        {/* Permissions section */}
        {hasPermissions ? (
          <div className="mt-6 space-y-2">
            <h4 className="text-xs font-semibold text-secondary-500 uppercase tracking-wide">{t('dms.shareWith')}</h4>
            <ul className="space-y-1">
              {file.permissions!.map((perm) => (
                <li key={perm.id} className="flex items-center justify-between text-sm">
                  <span className="text-secondary-700 font-mono text-xs">
                    {perm.user_id || perm.group_id || '-'}
                  </span>
                  <span className="text-xs text-secondary-500">{perm.permission}</span>
                </li>
              ))}
            </ul>
          </div>
        ) : null}
      </div>
    </div>
  );
}
