'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useCallback, useRef } from 'react';
import { Download, Upload, FileUp, Check, AlertCircle } from 'lucide-react';
import { cn } from '../../../lib/utils.js';
import { Button } from '../../ui/button.js';
import { Badge } from '../../ui/badge.js';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from '../../ui/dialog.js';
import { Label } from '../../ui/label.js';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '../../ui/select.js';
import { exportWorkItemsCsv, importWorkItemsCsv } from '../../../app/actions/manage-import-export.js';
const EXPORT_COLUMNS = [
    { value: 'identifier', label: 'Identifier' },
    { value: 'title', label: 'Title' },
    { value: 'description', label: 'Description' },
    { value: 'state', label: 'State' },
    { value: 'priority', label: 'Priority' },
    { value: 'labels', label: 'Labels' },
    { value: 'dueDate', label: 'Due Date' },
    { value: 'startDate', label: 'Start Date' },
    { value: 'estimate', label: 'Estimate' },
];
const IMPORT_FIELDS = [
    { value: 'title', label: 'Title' },
    { value: 'description', label: 'Description' },
    { value: 'priority', label: 'Priority' },
    { value: 'state', label: 'State' },
    { value: 'estimateValue', label: 'Estimate' },
    { value: 'dueDate', label: 'Due Date' },
    { value: 'startDate', label: 'Start Date' },
];
export function CsvImportExportPanel({ projectId, className }) {
    const [showExportDialog, setShowExportDialog] = useState(false);
    const [showImportDialog, setShowImportDialog] = useState(false);
    const [selectedColumns, setSelectedColumns] = useState([
        'identifier',
        'title',
        'state',
        'priority',
    ]);
    const [loading, setLoading] = useState(false);
    const [importFile, setImportFile] = useState(null);
    const [importPreview, setImportPreview] = useState([]);
    const [fieldMapping, setFieldMapping] = useState({});
    const [importResult, setImportResult] = useState(null);
    const fileInputRef = useRef(null);
    const handleExport = useCallback(async () => {
        setLoading(true);
        const result = await exportWorkItemsCsv({
            projectId,
            columns: selectedColumns,
        });
        setLoading(false);
        if (result.csv) {
            const blob = new Blob([result.csv], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `work-items-export.csv`;
            a.click();
            URL.revokeObjectURL(url);
            setShowExportDialog(false);
        }
    }, [projectId, selectedColumns]);
    const handleFileSelect = useCallback((e) => {
        const file = e.target.files?.[0];
        if (!file)
            return;
        setImportFile(file);
        setImportResult(null);
        const reader = new FileReader();
        reader.onload = (evt) => {
            const text = evt.target?.result;
            const lines = text.trim().split(/\r?\n/).slice(0, 6);
            const preview = lines.map((line) => line.split(',').map((v) => v.trim()));
            setImportPreview(preview);
            // Auto-map fields based on header names
            if (preview.length > 0) {
                const mapping = {};
                preview[0].forEach((header, idx) => {
                    const normalized = header.toLowerCase().replace(/[^a-z]/g, '');
                    const match = IMPORT_FIELDS.find((f) => f.value.toLowerCase() === normalized ||
                        f.label.toLowerCase().replace(/[^a-z]/g, '') === normalized);
                    if (match)
                        mapping[idx] = match.value;
                });
                setFieldMapping(mapping);
            }
        };
        reader.readAsText(file);
    }, []);
    const handleImport = useCallback(async () => {
        if (!importFile)
            return;
        setLoading(true);
        const text = await importFile.text();
        const result = await importWorkItemsCsv({
            projectId,
            csvContent: text,
            fieldMapping,
            skipHeaderRow: true,
        });
        setLoading(false);
        if (result.error) {
            setImportResult({ errors: [{ rowNumber: 0, error: result.error }] });
        }
        else {
            setImportResult({ createdCount: result.createdCount, errors: result.errors });
        }
    }, [projectId, importFile, fieldMapping]);
    const toggleColumn = useCallback((col) => {
        setSelectedColumns((prev) => prev.includes(col) ? prev.filter((c) => c !== col) : [...prev, col]);
    }, []);
    return (_jsxs("div", { className: cn('flex items-center gap-2', className), children: [_jsxs(Button, { size: "sm", variant: "outline", onClick: () => setShowExportDialog(true), children: [_jsx(Download, { className: "mr-1 h-4 w-4" }), "Export CSV"] }), _jsxs(Button, { size: "sm", variant: "outline", onClick: () => setShowImportDialog(true), children: [_jsx(Upload, { className: "mr-1 h-4 w-4" }), "Import CSV"] }), _jsx(Dialog, { open: showExportDialog, onOpenChange: setShowExportDialog, children: _jsxs(DialogContent, { children: [_jsx(DialogHeader, { children: _jsx(DialogTitle, { children: "Export Work Items to CSV" }) }), _jsx("div", { className: "space-y-4 py-4", children: _jsxs("div", { className: "space-y-2", children: [_jsx(Label, { children: "Columns to include" }), _jsx("div", { className: "flex flex-wrap gap-2", children: EXPORT_COLUMNS.map((col) => (_jsxs(Badge, { variant: selectedColumns.includes(col.value) ? 'default' : 'outline', className: "cursor-pointer", onClick: () => toggleColumn(col.value), children: [selectedColumns.includes(col.value) && _jsx(Check, { className: "mr-1 h-3 w-3" }), col.label] }, col.value))) })] }) }), _jsxs(DialogFooter, { children: [_jsx(Button, { variant: "outline", onClick: () => setShowExportDialog(false), children: "Cancel" }), _jsx(Button, { onClick: handleExport, disabled: loading || selectedColumns.length === 0, children: loading ? 'Exporting...' : 'Export' })] })] }) }), _jsx(Dialog, { open: showImportDialog, onOpenChange: (open) => {
                    setShowImportDialog(open);
                    if (!open) {
                        setImportFile(null);
                        setImportPreview([]);
                        setFieldMapping({});
                        setImportResult(null);
                    }
                }, children: _jsxs(DialogContent, { className: "max-w-lg", children: [_jsx(DialogHeader, { children: _jsx(DialogTitle, { children: "Import Work Items from CSV" }) }), _jsxs("div", { className: "space-y-4 py-4", children: [_jsxs("div", { className: "space-y-2", children: [_jsx(Label, { children: "CSV File" }), _jsx("input", { ref: fileInputRef, type: "file", accept: ".csv", className: "hidden", onChange: handleFileSelect }), _jsxs(Button, { variant: "outline", className: "w-full", onClick: () => fileInputRef.current?.click(), children: [_jsx(FileUp, { className: "mr-2 h-4 w-4" }), importFile ? importFile.name : 'Choose file...'] })] }), importPreview.length > 0 && (_jsxs("div", { className: "space-y-2", children: [_jsx(Label, { children: "Field Mapping" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Map CSV columns to work item fields" }), _jsx("div", { className: "space-y-2", children: importPreview[0].map((header, colIndex) => {
                                                const colKey = `col-${header || 'empty'}-${String(colIndex)}`;
                                                return (_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "w-28 truncate text-sm", children: header }), _jsxs(Select, { value: fieldMapping[colIndex] ?? 'skip', onValueChange: (val) => setFieldMapping((prev) => {
                                                                const next = { ...prev };
                                                                if (val === 'skip')
                                                                    delete next[colIndex];
                                                                else
                                                                    next[colIndex] = val;
                                                                return next;
                                                            }), children: [_jsx(SelectTrigger, { className: "h-8 w-36", children: _jsx(SelectValue, {}) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: "skip", children: "Skip" }), IMPORT_FIELDS.map((f) => (_jsx(SelectItem, { value: f.value, children: f.label }, f.value)))] })] })] }, colKey));
                                            }) })] })), importResult ? (_jsxs("div", { className: "space-y-2", children: [importResult.createdCount != null && importResult.createdCount > 0 && (_jsxs("div", { className: "flex items-center gap-2 text-sm text-green-600", children: [_jsx(Check, { className: "h-4 w-4" }), importResult.createdCount, " items imported successfully"] })), importResult.errors && importResult.errors.length > 0 ? (_jsx("div", { className: "space-y-1", children: importResult.errors.map((err) => (_jsxs("div", { className: "flex items-start gap-2 text-sm text-red-600", children: [_jsx(AlertCircle, { className: "mt-0.5 h-4 w-4 shrink-0" }), _jsxs("span", { children: [err.rowNumber > 0 ? `Row ${err.rowNumber}: ` : '', err.error] })] }, `err-${err.rowNumber}-${err.error}`))) })) : null] })) : null] }), _jsxs(DialogFooter, { children: [_jsx(Button, { variant: "outline", onClick: () => setShowImportDialog(false), children: "Cancel" }), _jsx(Button, { onClick: handleImport, disabled: loading || !importFile || !Object.keys(fieldMapping).length, children: loading ? 'Importing...' : 'Import' })] })] }) })] }));
}
