/**
 * Validation issue dialog for FileTextbox.
 *
 * Shows all clarification issues for a file using ClarificationSection
 * (same component as the Clarifications tab) with:
 * - Header with file name and issue count
 * - Grouped clarification cards (stacked issues for same document)
 * - Single "Submit All" button at the bottom
 * - Unsaved changes confirmation when closing with pending changes
 * - PDF viewer side panel when clicking "View" on a referenced document
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { optional_import } from '../../utils/optional_import.js';
import { Dialog, DialogContent, DialogTitle, DialogDescription, } from '../shared/dialog/index.js';
import { ClarificationSection } from '../clarification/clarification_section.js';
import { HazoUiDialog } from 'hazo_ui';
import { HiExclamationCircle, HiCheckCircle } from 'react-icons/hi';
import { IoClose } from 'react-icons/io5';
export function ValidationDialog({ file_id, blocks, validation_errors, file_manager, on_respond, on_response_change, on_close, responded_clarification_ids, sent_clarifications, }) {
    const raw_errors = validation_errors[file_id];
    if (!raw_errors)
        return null;
    // Enrich errors with responded status + response data from external responses
    const errors = useMemo(() => {
        if (!responded_clarification_ids?.size)
            return raw_errors;
        const sent_map = new Map((sent_clarifications ?? []).map(c => [c.id, c]));
        return raw_errors.map(item => {
            if (responded_clarification_ids.has(item.id) && item.status === 'pending') {
                const sent = sent_map.get(item.id);
                return {
                    ...item,
                    status: 'responded',
                    response_choice: sent?.response_choice ?? item.response_choice,
                    user_comment: sent?.user_comment ?? item.user_comment,
                    response_files: sent?.response_files ?? item.response_files,
                };
            }
            return item;
        });
    }, [raw_errors, responded_clarification_ids, sent_clarifications]);
    const file_block = blocks.find(b => b.type === 'file' && b.attachment.file_id === file_id);
    const file_name = file_block?.type === 'file' ? file_block.attachment.file_name : 'this file';
    // Pre-populate local_responses from items that already have response data
    const initial_responses = useMemo(() => {
        const map = new Map();
        for (const item of errors) {
            if (item.response_choice && (item.status === 'responded' || item.status === 'resolved')) {
                map.set(item.id, {
                    response_choice: item.response_choice,
                    user_comment: item.user_comment,
                    response_files: item.response_files?.length ? item.response_files : undefined,
                });
            }
        }
        return map;
    }, [errors]);
    // Track pending responses locally (seeded from already-responded items)
    const [local_responses, set_local_responses] = useState(initial_responses);
    const [confirm_close_open, set_confirm_close_open] = useState(false);
    // Re-seed if initial_responses changes (e.g., external data arrives after mount)
    const prev_initial_ref_dialog = useRef(initial_responses);
    if (initial_responses !== prev_initial_ref_dialog.current && initial_responses.size > 0 && local_responses.size === 0) {
        prev_initial_ref_dialog.current = initial_responses;
        set_local_responses(initial_responses);
    }
    // "has_changes" only tracks NEW responses beyond what was already responded
    const new_response_count = Array.from(local_responses.keys()).filter(id => !initial_responses.has(id)).length;
    const has_changes = new_response_count > 0;
    // Track response changes per card
    const handle_response_change = useCallback((id, response) => {
        set_local_responses(prev => {
            const next = new Map(prev);
            if (response.response_choice) {
                next.set(id, response);
            }
            return next;
        });
        // Also propagate to parent for external sync (e.g., file chip labels)
        on_response_change(id, response);
    }, [on_response_change]);
    // Submit only NEW responses (not pre-existing ones)
    const handle_submit_all = useCallback(() => {
        let submitted = false;
        for (const [id, response] of local_responses) {
            if (!initial_responses.has(id)) {
                on_respond(id, response);
                submitted = true;
            }
        }
        // If nothing new to submit (all were pre-existing), just close
        if (!submitted)
            on_close();
    }, [local_responses, initial_responses, on_respond, on_close]);
    // Handle dialog close — check for unsaved changes
    const handle_close_attempt = useCallback(() => {
        if (has_changes) {
            set_confirm_close_open(true);
        }
        else {
            on_close();
        }
    }, [has_changes, on_close]);
    const handle_confirm_discard = useCallback(() => {
        set_confirm_close_open(false);
        on_close();
    }, [on_close]);
    // Count how many issues have a response selected
    const responded_count = local_responses.size;
    const pending_count = errors.length - responded_count;
    // --- Enriched items for ClarificationSection ---
    const enriched_items = useMemo(() => {
        return errors.map((item) => {
            const local = local_responses.get(item.id);
            if (local?.response_choice) {
                return { ...item, status: 'responded', response_choice: local.response_choice, user_comment: local.user_comment };
            }
            return item;
        });
    }, [errors, local_responses]);
    const counts = useMemo(() => {
        const c = { pending: 0, responded: 0, resolved: 0, dismissed: 0, total: 0 };
        for (const item of enriched_items) {
            c[item.status]++;
            c.total++;
        }
        return c;
    }, [enriched_items]);
    // --- PDF viewer side panel ---
    const [preview_file, set_preview_file] = useState(null);
    const [PdfViewer, set_pdf_viewer] = useState(null);
    // Load PdfViewer from hazo_pdf (optional peer dependency)
    useEffect(() => {
        if (!file_manager?.get_download_url)
            return;
        let cancelled = false;
        optional_import('hazo_pdf').then((mod) => {
            if (!cancelled && mod.PdfViewer) {
                set_pdf_viewer(() => mod.PdfViewer);
            }
        }).catch(() => { });
        return () => { cancelled = true; };
    }, [file_manager?.get_download_url]);
    const can_view = !!(PdfViewer && file_manager?.get_download_url);
    const is_previewing = !!(preview_file && can_view);
    const handle_doc_view = useCallback((file_id, file_name) => {
        if (!file_manager?.get_download_url)
            return;
        set_preview_file({ file_id, file_name });
    }, [file_manager?.get_download_url]);
    const handle_doc_click = useCallback((file_id) => {
        // Find file_name from blocks or doc references
        const block = blocks.find(b => b.type === 'file' && b.attachment.file_id === file_id);
        const name = block?.type === 'file' ? block.attachment.file_name : file_id;
        handle_doc_view(file_id, name);
    }, [blocks, handle_doc_view]);
    const close_preview = useCallback(() => {
        set_preview_file(null);
    }, []);
    const dialog_class = is_previewing
        ? 'max-w-6xl max-h-[85vh] flex flex-col p-0'
        : 'max-w-3xl max-h-[80vh] flex flex-col p-0';
    // --- Shared section content ---
    const render_section = () => (_jsx(ClarificationSection, { items: enriched_items, counts: counts, callbacks: {}, hide_submit: true, hide_header: true, on_response_change: handle_response_change, on_doc_click: can_view ? handle_doc_click : undefined, on_doc_view: can_view ? handle_doc_view : undefined, file_manager: file_manager }));
    return (_jsxs(_Fragment, { children: [_jsx(Dialog, { open: true, onOpenChange: (open) => { if (!open)
                    handle_close_attempt(); }, children: _jsxs(DialogContent, { className: dialog_class, onInteractOutside: (e) => { if (has_changes) {
                        e.preventDefault();
                        handle_close_attempt();
                    } }, children: [_jsx(DialogTitle, { className: "sr-only", children: "Validation Issues" }), _jsx(DialogDescription, { className: "sr-only", children: "Validation issues" }), _jsxs("div", { className: "px-6 py-4 border-b flex items-center gap-3 flex-shrink-0", children: [pending_count > 0
                                    ? _jsx(HiExclamationCircle, { className: "h-5 w-5 text-destructive flex-shrink-0" })
                                    : _jsx(HiCheckCircle, { className: "h-5 w-5 text-green-500 flex-shrink-0" }), _jsx("h2", { className: "text-base font-semibold text-foreground", children: "Validation Issues" })] }), !is_previewing ? (
                        /* Standard layout */
                        _jsxs(_Fragment, { children: [_jsx("div", { className: "flex-1 overflow-y-auto px-6 py-4", children: render_section() }), _jsxs("div", { className: "px-6 py-3 border-t flex items-center justify-between flex-shrink-0 bg-muted/20", children: [_jsxs("span", { className: "text-xs text-muted-foreground", children: [responded_count, " of ", errors.length, " responded"] }), _jsxs("button", { type: "button", onClick: handle_submit_all, disabled: responded_count === 0, className: "px-4 py-2 text-sm font-medium rounded-md bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors", children: ["Submit Response", errors.length > 1 ? 's' : ''] })] })] })) : (
                        /* Side panel layout - section on left, PDF viewer on right */
                        _jsxs(_Fragment, { children: [_jsxs("div", { className: "flex gap-4 flex-1 min-h-0 px-4 py-4", children: [_jsx("div", { className: "w-1/2 overflow-y-auto pr-2", children: render_section() }), _jsxs("div", { className: "w-1/2 border rounded-lg overflow-hidden flex flex-col bg-muted/20", children: [_jsxs("div", { className: "flex items-center justify-between px-3 py-2 border-b bg-muted/30", children: [_jsx("span", { className: "text-sm font-medium truncate", title: preview_file.file_name, children: preview_file.file_name }), _jsx("button", { type: "button", onClick: close_preview, className: "rounded-sm p-1 hover:bg-muted transition-colors flex-shrink-0", title: "Close preview", children: _jsx(IoClose, { className: "h-4 w-4" }) })] }), _jsx("div", { className: "flex-1 min-h-0", children: _jsx(PdfViewer, { url: file_manager.get_download_url(preview_file.file_id), display_filename: preview_file.file_name, fit_to_width: true, toolbar_enabled: true, on_close: close_preview, className: "h-full w-full" }) })] })] }), _jsxs("div", { className: "px-6 py-3 border-t flex items-center justify-between flex-shrink-0 bg-muted/20", children: [_jsxs("span", { className: "text-xs text-muted-foreground", children: [responded_count, " of ", errors.length, " responded"] }), _jsxs("button", { type: "button", onClick: handle_submit_all, disabled: responded_count === 0, className: "px-4 py-2 text-sm font-medium rounded-md bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors", children: ["Submit Response", errors.length > 1 ? 's' : ''] })] })] }))] }) }), _jsx(HazoUiDialog, { open: confirm_close_open, onOpenChange: set_confirm_close_open, title: "Unsaved Changes", description: "You have unsaved responses. Are you sure you want to close? Your changes will be lost.", actionButtonText: "Discard Changes", onConfirm: handle_confirm_discard, cancelButtonText: "Continue Editing", actionButtonVariant: "destructive", sizeWidth: "24rem", children: null })] }));
}
//# sourceMappingURL=validation_dialog.js.map