import React, { useState, useEffect } from 'react';
import { X, Calendar, Clock, FolderInput, ArrowRight } from 'lucide-react';
import { useLanguage } from '../contexts/LanguageContext';
import { ModelConfig, ModelType, IndexingConfig } from '../types';
import { modelConfigService } from '../services/modelConfigService';
import { importService } from '../services/importService';
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 [sourcePath, setSourcePath] = useState('');
    const [targetName, setTargetName] = useState('');
    const [executionType, setExecutionType] = useState<'immediate' | 'scheduled'>('immediate');
    const [scheduledTime, setScheduledTime] = useState('');

    // 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
            setSourcePath('');
            setTargetName(initialGroupName || '');
            setExecutionType('immediate');
            setScheduledTime('');
            setIsIndexingConfigOpen(false);

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

    // Auto-fill target name from path if not locked to a group
    const handlePathChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value;
        setSourcePath(val);
        if (!initialGroupId && val) {
            // Extract last folder name (Windows or Unix style)
            const parts = val.split(/[\\/]/).filter(p => p);
            if (parts.length > 0) {
                setTargetName(parts[parts.length - 1]);
            }
        }
    };

    const handleNext = async () => {
        if (!sourcePath) {
            showError(t('fillSourcePath'));
            return;
        }
        if (!initialGroupId && !targetName) {
            showError(t('fillTargetName'));
            return;
        }

        if (executionType === 'scheduled' && !scheduledTime) {
            showError(t('selectExecTime'));
            return;
        }

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

    const handleConfirmConfig = async (config: IndexingConfig) => {
        setIsLoading(true);
        try {
            await importService.create(authToken, {
                sourcePath,
                targetGroupId: initialGroupId || undefined,
                targetGroupName: initialGroupId ? undefined : targetName,
                embeddingModelId: config.embeddingModelId,
                scheduledAt: executionType === 'scheduled' ? new Date(scheduledTime).toISOString() : undefined,
                chunkSize: config.chunkSize,
                chunkOverlap: config.chunkOverlap,
                mode: config.mode
            });

            showSuccess(executionType === 'immediate' ? t('importTaskStarted') : t('importTaskScheduled'));
            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">
                            {t('importFolderTip')}
                        </div>

                        {/* Source Path */}
                        <div className="space-y-2">
                            <label className="text-sm font-medium text-slate-700">{t('lblSourcePath')}</label>
                            <input
                                type="text"
                                value={sourcePath}
                                onChange={handlePathChange}
                                placeholder="例如: D:/data/courses/gen-ai"
                                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
                            />
                        </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>

                        {/* Execution Type */}
                        <div className="space-y-3 pt-4 border-t border-slate-100">
                            <label className="text-sm font-medium text-slate-700">{t('lblExecType')}</label>
                            <div className="flex gap-4">
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input
                                        type="radio"
                                        name="executionType"
                                        value="immediate"
                                        checked={executionType === 'immediate'}
                                        onChange={() => setExecutionType('immediate')}
                                        className="text-blue-600 focus:ring-blue-500"
                                    />
                                    <span className="text-sm text-slate-700">{t('execImmediate')}</span>
                                </label>
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input
                                        type="radio"
                                        name="executionType"
                                        value="scheduled"
                                        checked={executionType === 'scheduled'}
                                        onChange={() => setExecutionType('scheduled')}
                                        className="text-blue-600 focus:ring-blue-500"
                                    />
                                    <span className="text-sm text-slate-700">{t('execScheduled')}</span>
                                </label>
                            </div>
                        </div>

                        {/* Schedule Time Picker */}
                        {executionType === 'scheduled' && (
                            <div className="space-y-2 animate-in fade-in slide-in-from-top-2">
                                <label className="text-sm font-medium text-slate-700 flex items-center gap-2">
                                    <Clock size={16} />
                                    {t('lblStartTime')}
                                </label>
                                <input
                                    type="datetime-local"
                                    value={scheduledTime}
                                    onChange={e => setScheduledTime(e.target.value)}
                                    min={new Date().toISOString().slice(0, 16)}
                                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none"
                                />
                            </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"
                        >
                            <span>{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}
            />
        </>
    );
};
