'use client'
import React, {useState} from 'react';
import {Download} from 'lucide-react';
import {useTranslations} from '@/lib/i18n';
import SelectBox from '@/components/form/SelectBox';
import InputField from '@/components/form/InputField';

interface SeriesImportItem {
    id: string;
    name: string;
}

interface SeriesImportSelectorProps {
    availableItems: SeriesImportItem[];
    onImport: (seriesElementId: string) => Promise<void>;
    placeholder: string;
    label?: string;
}

export default function SeriesImportSelector({
                                                 availableItems,
                                                 onImport,
                                                 placeholder,
                                                 label
                                             }: SeriesImportSelectorProps) {
    const t = useTranslations();
    
    const [selectedId, setSelectedId] = useState<string>('');
    const [isImporting, setIsImporting] = useState<boolean>(false);
    
    async function handleImport(): Promise<void> {
        if (!selectedId || isImporting) return;
        
        setIsImporting(true);
        try {
            await onImport(selectedId);
            setSelectedId('');
        } finally {
            setIsImporting(false);
        }
    }
    
    if (availableItems.length === 0) {
        return null;
    }
    
    const selectData = availableItems.map((item) => ({
        label: item.name,
        value: item.id
    }));
    
    return (
        <div className="bg-primary/10 border border-primary/30 rounded-xl p-4 mb-4">
            {label && (
                <h4 className="text-sm font-medium text-primary mb-3 flex items-center gap-2">
                    <Download className="w-4 h-4" strokeWidth={1.75}/>
                    {label}
                </h4>
            )}
            <InputField
                input={
                    <SelectBox
                        onChangeCallBack={(e) => setSelectedId(e.target.value)}
                        data={selectData}
                        defaultValue={selectedId}
                        placeholder={placeholder}
                    />
                }
                addButtonCallBack={handleImport}
                isAddButtonDisabled={!selectedId || isImporting}
            />
        </div>
    );
}
