import { useState, useCallback } from 'react';
import { Modal, message } from 'antd';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import type { MkDocsBuildResult } from '@/types/api';

/**
 * Hook for triggering MkDocs static site builds with a confirmation modal.
 * Returns { building, confirmAndBuild } for use in any admin page.
 */
export function useMkDocsBuild() {
  const [building, setBuilding] = useState(false);
  const { user } = useAuthStore();
  const isSuperAdmin = user?.role === 'SUPER_ADMIN';

  const confirmAndBuild = useCallback(() => {
    if (!isSuperAdmin) {
      message.warning('Only super admins can trigger builds');
      return;
    }

    Modal.confirm({
      title: 'Build Static Site',
      content: 'This will rebuild the MkDocs static site. The dev server is unaffected. Continue?',
      okText: 'Build',
      cancelText: 'Cancel',
      onOk: async () => {
        setBuilding(true);
        try {
          const res = await api.post<MkDocsBuildResult>('/docs/build');
          if (res.data.success) {
            message.success(`Build succeeded in ${(res.data.duration / 1000).toFixed(1)}s`);
          } else {
            message.error('Build failed — check Docs Settings > Build for details');
          }
        } catch {
          message.error('Build request failed');
        } finally {
          setBuilding(false);
        }
      },
    });
  }, [isSuperAdmin]);

  return { building, confirmAndBuild, isSuperAdmin };
}
