import { useEffect, useState } from 'react';
import api from '../lib/api.js';
import { useQuery } from '@tanstack/react-query';
import ConfirmDialog from './ConfirmDialog.jsx';
import { useNotify } from './NotifyProvider.jsx';
import { IconHistory, IconRefresh, IconDeviceFloppy } from '@tabler/icons-react';

export default function HistoryModal({ resource, show, onClose, onRolledBack }) {
  const [loading, setLoading] = useState(false);
  const [items, setItems] = useState([]);
  const notify = useNotify();

  const { refetch } = useQuery({
    queryKey: ['history', resource],
    enabled: false,
    queryFn: async () => {
      const res = await api.get(`/history/${resource}`)
      const data = Array.isArray(res.data?.items) ? res.data.items : []
      setItems(data)
      return data
    },
  })

  useEffect(() => { if (show) refetch().catch(() => notify.error('Не удалось загрузить историю версий')); }, [show, resource]);

  const [confirmState, setConfirmState] = useState({ open: false, onConfirm: null });
  const rollback = async (versionId) => {
    if (!versionId) return;
    await new Promise((resolve) => {
      setConfirmState({
        open: true,
        onConfirm: async () => {
          setConfirmState({ open: false, onConfirm: null });
          setLoading(true);
          try {
            const res = await api.post(`/history/${resource}/rollback`, { versionId });
            notify.success('Откат выполнен');
            onRolledBack && onRolledBack(res.data || {});
            onClose && onClose();
          } catch (e) {
            notify.error('Не удалось выполнить откат');
          } finally {
            setLoading(false);
          }
          resolve();
        }
      });
    });
  };

  if (!show) return null;

  return (
    <div className="modal show d-block" role="dialog" aria-modal="true" aria-labelledby="history-title" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }} onKeyDown={(e) => { if (e.key === 'Escape') onClose?.() }}>
      <div className="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div className="modal-content" tabIndex={-1} onKeyDown={(e) => {
          if (e.key === 'Tab') {
            const c = e.currentTarget
            const focusable = c.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
            if (!focusable || focusable.length === 0) return
            const first = focusable[0]
            const last = focusable[focusable.length - 1]
            if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
            else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
          }
        }}>
          <div className="modal-header">
            <h5 id="history-title" className="modal-title d-flex align-items-center">
              <IconHistory className="me-2" /> История версий
            </h5>
            <button type="button" className="btn-close" onClick={onClose}></button>
          </div>
          <div className="modal-body">
            <div className="d-flex justify-content-between align-items-center mb-2">
              <div className="text-muted small">Ресурс: <code>{resource}</code></div>
              <button className="btn btn-outline-secondary btn-sm" onClick={() => refetch()} disabled={loading}>
                <IconRefresh className={loading ? 'spin' : ''} />
                <span className="ms-1">Обновить</span>
              </button>
            </div>
            <div className="table-responsive">
              <table className="table card-table table-vcenter table-nowrap mb-0">
                <thead>
                  <tr>
                    <th>Версия</th>
                    <th>Дата</th>
                    <th>Размер</th>
                    <th>ETag</th>
                    <th className="text-end">Действия</th>
                  </tr>
                </thead>
                <tbody>
                  {items.length === 0 ? (
                    <tr><td colSpan="5" className="text-muted text-center py-4">Нет данных (возможно, версионирование бакета отключено)</td></tr>
                  ) : items.map((v) => (
                    <tr key={v.versionId} className={v.isLatest ? 'table-info' : ''}>
                      <td><code>{v.versionId}</code></td>
                      <td>{v.lastModified ? new Date(v.lastModified).toLocaleString() : '—'}</td>
                      <td>{typeof v.size === 'number' ? `${v.size} байт` : '—'}</td>
                      <td><code>{v.etag || '—'}</code></td>
                      <td className="text-end">
                        {!v.isLatest && (
                          <button className="btn btn-outline-primary btn-sm" onClick={() => rollback(v.versionId)} disabled={loading}>
                            <IconDeviceFloppy className="me-1" /> Откатить к этой версии
                          </button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
          <div className="modal-footer">
            <button className="btn" onClick={onClose}>Закрыть</button>
          </div>
        </div>
      </div>
      <ConfirmDialog
        open={confirmState.open}
        title="Подтверждение"
        message="Откатить к выбранной версии? Текущее содержимое будет перезаписано."
        confirmText="Откатить"
        onCancel={() => setConfirmState({ open: false, onConfirm: null })}
        onConfirm={confirmState.onConfirm}
      />
    </div>
  );
}


