import React, { useEffect, useState } from 'react';
import { X, History, Clock, Download, Edit3, Trash2, Plus, Shield } from 'lucide-react';
import api from '../services/api';

interface HistoryEntry {
  id: number;
  file_id: number;
  file_name: string;
  action: string;
  user_id: number;
  user_name: string;
  user_email: string;
  user_role: string;
  user_department: string;
  ip: string;
  version_before: number;
  version_after: number;
  size_before: number;
  size_after: number;
  summary: string;
  created_at: string;
}

interface DocumentHistoryProps {
  fileId: number;
  fileName: string;
  onClose: () => void;
}

function fmtSize(b: number) {
  if (b === 0) return '0 B';
  if (b < 1024) return `${b} B`;
  if (b < 1048576) return `${(b / 1024).toFixed(1)} KB`;
  return `${(b / 1048576).toFixed(1)} MB`;
}

function fmtDate(s: string) {
  try {
    const d = new Date(s + 'Z');
    return d.toLocaleString('pt-BR', {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit', second: '2-digit'
    });
  } catch { return s; }
}

type LucideIcon = React.ComponentType<{ size?: number; className?: string }>;
const ACTION_META: Record<string, { label: string; color: string; Icon: LucideIcon }> = {
  created:    { label: 'Criado',    color: 'text-emerald-400', Icon: Plus as LucideIcon },
  edited:     { label: 'Editado',   color: 'text-blue-400',    Icon: Edit3 as LucideIcon },
  downloaded: { label: 'Baixado',   color: 'text-gray-400',    Icon: Download as LucideIcon },
  deleted:    { label: 'Removido',  color: 'text-red-400',     Icon: Trash2 as LucideIcon },
};

export default function DocumentHistory({ fileId, fileName, onClose }: DocumentHistoryProps) {
  const [entries, setEntries] = useState<HistoryEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [forbidden, setForbidden] = useState(false);

  const displayName = fileName
    .replace('.hardrada-doc.json', '')
    .replace('.hardrada-sheet.json', '');

  useEffect(() => {
    api.get(`/files/${fileId}/history`)
      .then(r => setEntries(r.data))
      .catch(err => {
        if (err.response?.status === 403) setForbidden(true);
      })
      .finally(() => setLoading(false));
  }, [fileId]);

  return (
    <div className="fixed inset-0 z-50 flex justify-end">
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
      <div className="relative w-full max-w-md bg-surface-card border-l border-surface-border flex flex-col h-full shadow-2xl">

        {/* Header */}
        <div className="flex items-center gap-3 px-5 py-4 border-b border-surface-border shrink-0">
          <History size={18} className="text-purple-400 shrink-0" />
          <div className="flex-1 min-w-0">
            <p className="text-white font-semibold text-sm">Histórico de Alterações</p>
            <p className="text-gray-500 text-xs truncate">{displayName}</p>
          </div>
          <span className="flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-purple-900/30 text-purple-400 border border-purple-700/40 shrink-0">
            <Shield size={11} /> Somente TI
          </span>
          <button onClick={onClose} className="icon-btn hover:text-white shrink-0">
            <X size={16} />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto">
          {loading && (
            <div className="flex items-center justify-center py-16">
              <span className="w-5 h-5 border-2 border-purple-400/30 border-t-purple-400 rounded-full animate-spin" />
            </div>
          )}

          {!loading && forbidden && (
            <div className="flex flex-col items-center justify-center py-16 gap-3 px-6 text-center">
              <Shield size={32} className="text-gray-600" />
              <p className="text-gray-400 text-sm">Acesso restrito à equipe de TI</p>
            </div>
          )}

          {!loading && !forbidden && entries.length === 0 && (
            <div className="flex flex-col items-center justify-center py-16 gap-3 px-6 text-center">
              <Clock size={32} className="text-gray-600" />
              <p className="text-gray-400 text-sm">Nenhuma alteração registrada</p>
            </div>
          )}

          {!loading && !forbidden && entries.length > 0 && (
            <div className="divide-y divide-surface-border/40">
              {entries.map(entry => {
                const meta = ACTION_META[entry.action] || { label: entry.action, color: 'text-gray-400', Icon: Clock };
                const { label, color, Icon } = meta;
                return (
                  <div key={entry.id} className="px-5 py-4 hover:bg-surface-hover/20 transition-colors">
                    <div className="flex items-start justify-between gap-2 mb-1.5">
                      <div className="flex items-center gap-2">
                        <Icon size={13} className={color} />
                        <span className={`text-xs font-semibold uppercase tracking-wide ${color}`}>{label}</span>
                      </div>
                      {(entry.version_before > 0 || entry.version_after > 0) && (
                        <span className="text-xs text-gray-600 shrink-0">
                          v{entry.version_before} → v{entry.version_after}
                        </span>
                      )}
                    </div>

                    <p className="text-white text-sm font-medium leading-tight">{entry.user_name}</p>
                    <p className="text-gray-500 text-xs">{entry.user_email}</p>
                    <p className="text-gray-600 text-xs mt-0.5">
                      {entry.user_department || '—'} · {entry.user_role === 'admin' ? 'Administrador' : 'Colaborador'}
                    </p>

                    {entry.summary && (
                      <p className="text-gray-400 text-xs mt-1.5 italic">"{entry.summary}"</p>
                    )}

                    <div className="flex items-center gap-3 mt-2 text-xs text-gray-600">
                      <span className="flex items-center gap-1">
                        <Clock size={10} />
                        {fmtDate(entry.created_at)}
                      </span>
                    </div>

                    <div className="flex items-center gap-3 mt-1 text-xs text-gray-700">
                      {(entry.size_before > 0 || entry.size_after > 0) && (
                        <span>{fmtSize(entry.size_before)} → {fmtSize(entry.size_after)}</span>
                      )}
                      {entry.ip && <span>IP: {entry.ip}</span>}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
