import React, { useState, useEffect } from 'react';
import { X, FolderInput, ArrowRight, Info } from 'lucide-react';
import { GROUP_ALLOWED_EXTENSIONS, isExtensionAllowed, getSupportedFormatsLabel } from '../constants/fileSupport';
import { useLanguage } from '../contexts/LanguageContext';
import { ModelConfig, ModelType, IndexingConfig } from '../types';
import { modelConfigService } from '../services/modelConfigService';
import { knowledgeGroupService } from '../services/knowledgeGroupService';
import { useToast } from '../contexts/ToastContext';
import IndexingModalWithMode from './IndexingModalWithMode';

interface ImportFolderDrawerProps {
    isOpen: boolean;
    onClose: () => void;
    authToken: string;
    initialGroupId?: string; // If provided, locks target to this group
    initialGroupName?: string;
    onImportSuccess?: () => void;
}

export const ImportFolderDrawer: React.FC<ImportFolderDrawerProps> = ({
    isOpen,
    onClose,
    authToken,
    initialGroupId,
    initialGroupName,
    onImportSuccess
}) => {
    const { t } = useLanguage();
    const { showError, showSuccess } = useToast();

    // Form State
    const [localFiles, setLocalFiles] = useState<File[]>([]);
    const [folderName, setFolderName] = useState('');
    const [targetName, setTargetName] = useState('');
    const fileInputRef = React.useRef<HTMLInputElement>(null);

    // Indexing Config State
    const [isIndexingConfigOpen, setIsIndexingConfigOpen] = useState(false);

    // Data State
    const [models, setModels] = useState<ModelConfig[]>([]);
    const [isLoading, setIsLoading] = useState(false);

    useEffect(() => {
        if (isOpen) {
            // Reset form
            setLocalFiles([]);
            setFolderName('');
            setTargetName(initialGroupName || '');
            setIsIndexingConfigOpen(false);

            // Fetch models
            modelConfigService.getAll(authToken).then(res => {
                setModels(res.filter(m => m.type === ModelType.EMBEDDING));
            });
        }
    }, [isOpen, authToken, initialGroupName]);

    const handleLocalFolderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            const allFiles = Array.from(e.target.files);
            // Filter files by allowed extensions
            const files = allFiles.filter(file => {
                const ext = file.name.split('.').pop() || '';
                return isExtensionAllowed(ext, 'group');
            });

            if (files.length === 0 && allFiles.length > 0) {
                showError(t('noFilesFound'));
                return;
            }

            setLocalFiles(files);

            // Get root folder name from webkitRelativePath
            const firstPath = allFiles[0].webkitRelativePath; // Use allFiles to get path even if filtered
            if (firstPath) {
                const parts = firstPath.split('/');
                if (parts.length > 0) {
                    const name = parts[0];
                    setFolderName(name);
                    if (!initialGroupId && !targetName) {
                        setTargetName(name);
                    }
                }
            }
        }
    };

    const handleNext = async () => {
        if (localFiles.length === 0) {
            showError(t('clickToSelectFolder'));
            return;
        }

        if (!initialGroupId && !targetName) {
            showError(t('fillTargetName'));
            return;
        }

        // Open indexing config modal
        setIsIndexingConfigOpen(true);
    };

    const handleConfirmConfig = async (config: IndexingConfig) => {
        setIsLoading(true);
        try {
            // 1. Ensure target group exists or create it
            let groupId = initialGroupId;
            if (!groupId) {
                const newGroup = await knowledgeGroupService.createGroup({
                    name: targetName,
                    description: t('importedFromLocalFolder').replace('$1', folderName)
                });
                groupId = newGroup.id;
            }

            // 2. Upload files in batches
            const { uploadService } = await import('../services/uploadService');
            const { readFile } = await import('../utils/fileUtils');

            // Limit concurrent uploads for large folders
            const BATCH_SIZE = 3;
            for (let i = 0; i < localFiles.length; i += BATCH_SIZE) {
                const batch = localFiles.slice(i, i + BATCH_SIZE);
                await Promise.all(batch.map(async (file) => {
                    try {
                        await readFile(file); // Optional: verify readability
                        const uploadedKb = await uploadService.uploadFileWithConfig(file, config, authToken);
                        if (groupId) {
                            await knowledgeGroupService.addFileToGroups(uploadedKb.id, [groupId]);
                        }
                    } catch (err) {
                        console.error(`Failed to upload ${file.name}:`, err);
                    }
                }));
            }
            showSuccess(t('importComplete'));

            onImportSuccess?.();
            onClose();
        } catch (error: any) {
            showError(t('submitFailed', error.message));
        } finally {
            setIsLoading(false);
            setIsIndexingConfigOpen(false);
        }
    };

    if (!isOpen) return null;

    return (
        <>
            <div className="fixed inset-0 z-50 flex justify-end">
                <div className="absolute inset-0 bg-black/20 backdrop-blur-sm transition-opacity" onClick={onClose} />

                <div className="relative w-full max-w-md bg-white shadow-2xl flex flex-col h-full animate-in slide-in-from-right duration-300">
                    {/* Header */}
                    <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between shrink-0 bg-white">
                        <h2 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                            <FolderInput className="w-5 h-5 text-blue-600" />
                            {t('importFolderTitle')}
                        </h2>
                        <button onClick={onClose} className="p-2 -mr-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-full transition-colors">
                            <X size={20} />
                        </button>
                    </div>

                    {/* Body */}
                    <div className="flex-1 overflow-y-auto p-6 space-y-6">
                        <div className="bg-blue-50 border border-blue-100 rounded-lg p-3 text-sm text-blue-800 flex items-start gap-2">
                            <Info className="w-4 h-4 mt-0.5 shrink-0" />
                            <div>
                                <p className="font-medium underline decoration-blue-200 underline-offset-2 mb-1">
                                    {t('supportedFormatsInfo')}
                                </p>
                                <p className="opacity-80 text-xs">
                                    {t('importFolderTip')}
                                </p>
                            </div>
                        </div>

                        {/* Local Folder Selection */}
                        <div className="space-y-4 animate-in fade-in slide-in-from-top-2">
                            <div
                                onClick={() => fileInputRef.current?.click()}
                                className="border-2 border-dashed border-slate-200 rounded-xl p-8 flex flex-col items-center justify-center gap-3 cursor-pointer hover:border-blue-400 hover:bg-blue-50 transition-all group"
                            >
                                <div className="w-12 h-12 bg-slate-50 text-slate-400 rounded-full flex items-center justify-center group-hover:bg-blue-100 group-hover:text-blue-600 transition-colors">
                                    <FolderInput size={24} />
                                </div>
                                <div className="text-center">
                                    <p className="text-sm font-medium text-slate-700">
                                        {localFiles.length > 0
                                            ? t('selectedFilesCount').replace('$1', localFiles.length.toString())
                                            : t('clickToSelectFolder')}
                                    </p>
                                    <p className="text-xs text-slate-400 mt-1">
                                        {localFiles.length > 0 ? folderName : t('selectFolderTip')}
                                    </p>
                                </div>
                                <input
                                    type="file"
                                    ref={fileInputRef}
                                    onChange={handleLocalFolderChange}
                                    className="hidden"
                                    multiple
                                    // @ts-ignore
                                    webkitdirectory=""
                                    directory=""
                                />
                            </div>
                        </div>

                        {/* Target Group */}
                        <div className="space-y-2">
                            <label className="text-sm font-medium text-slate-700">{t('lblTargetGroup')}</label>
                            <input
                                type="text"
                                value={targetName}
                                onChange={e => setTargetName(e.target.value)}
                                disabled={!!initialGroupId} // Readonly if locking to group
                                placeholder={t('placeholderNewGroup')}
                                className={`w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none ${initialGroupId ? 'bg-slate-50 text-slate-500' : ''}`}
                            />
                            {initialGroupId && <p className="text-xs text-slate-400">{t('importToCurrentGroup')}</p>}
                        </div>
                    </div>

                    {/* Footer */}
                    <div className="p-6 border-t border-slate-100 shrink-0 flex gap-3 bg-slate-50">
                        <button
                            onClick={onClose}
                            className="flex-1 px-4 py-2 text-sm font-medium text-slate-600 hover:bg-slate-200 rounded-lg transition-colors"
                        >
                            {t('cancel')}
                        </button>
                        <button
                            onClick={handleNext}
                            className="flex-1 px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg shadow-sm flex justify-center items-center gap-2 transition-all"
                            disabled={isLoading}
                        >
                            <span>{isLoading ? t('uploading') : t('nextStep')}</span>
                            <ArrowRight size={16} />
                        </button>
                    </div>
                </div>
            </div>

            {/* Indexing Config Modal */}
            <IndexingModalWithMode
                isOpen={isIndexingConfigOpen}
                onClose={() => setIsIndexingConfigOpen(false)}
                files={[]} // Empty array for folder import mode
                embeddingModels={models}
                defaultEmbeddingId={models.length > 0 ? models[0].id : ''}
                onConfirm={handleConfirmConfig}
                isReconfiguring={false}
            />
        </>
    );
};
