import React, { useState, useEffect } from 'react';
import { X, Loader, Image as ImageIcon, Box } from 'lucide-react';
import { ocrService } from '../services/ocrService';
import { knowledgeGroupService } from '../services/knowledgeGroupService';
import { KnowledgeGroup } from '../types';
import { useLanguage } from '../contexts/LanguageContext';
import { useToast } from '../contexts/ToastContext';

interface CreateNoteFromPDFDialogProps {
    screenshot: Blob;
    extractedText: string;
    onSave: (title: string, content: string, groupId?: string) => Promise<void>;
    onCancel: () => void;
    authToken: string;
    initialGroupId?: string;
    initialPageNumber?: number;
}

export const CreateNoteFromPDFDialog: React.FC<CreateNoteFromPDFDialogProps> = ({
    screenshot,
    extractedText,
    onSave,
    onCancel,
    authToken,
    initialGroupId,
    initialPageNumber,
}) => {
    const { t } = useLanguage();
    const { showToast } = useToast();
    const defaultTitle = initialPageNumber
        ? `${t('createPDFNote')} - ${t('page')} ${initialPageNumber} - ${new Date().toLocaleString()}`
        : `${t('createPDFNote')} - ${new Date().toLocaleString()}`;
    const [title, setTitle] = useState(defaultTitle);
    const [content, setContent] = useState(extractedText);
    const [selectedGroupId, setSelectedGroupId] = useState<string | undefined>(initialGroupId);
    const [groups, setGroups] = useState<KnowledgeGroup[]>([]);
    const [saving, setSaving] = useState(false);
    const [ocrLoading, setOcrLoading] = useState(false);
    const [screenshotUrl, setScreenshotUrl] = useState<string>('');

    useEffect(() => {
        if (authToken) {
            knowledgeGroupService.getGroups().then(setGroups).catch(console.error);
        }
    }, [authToken]);

    useEffect(() => {
        const url = URL.createObjectURL(screenshot);
        setScreenshotUrl(url);

        // Trigger OCR if initial text is empty
        if (!extractedText && authToken) {
            setOcrLoading(true);
            ocrService.recognizeText(authToken, screenshot)
                .then(text => setContent(text))
                .catch(err => console.error('OCR failed:', err))
                .finally(() => setOcrLoading(false));
        }

        return () => URL.revokeObjectURL(url);
    }, [screenshot, extractedText, authToken]);

    const handleSave = async () => {
        // ナレッジグループが選択されているか確認
        if (!selectedGroupId) {
            showToast('warning', t('pleaseSelectKnowledgeGroupFirst')); // 使用 toast 提示用户先选择知识组
            return;
        }

        setSaving(true);
        try {
            await onSave(title, content, selectedGroupId);
        } catch (error) {
            console.error('Failed to save note:', error);
        } finally {
            setSaving(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-lg w-full max-w-3xl max-h-[90vh] flex flex-col">
                {/* Header */}
                <div className="flex items-center justify-between p-4 border-b">
                    <h2 className="text-lg font-semibold text-gray-900">{t('createPDFNote')}</h2>
                    <button
                        onClick={onCancel}
                        className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
                        disabled={saving}
                    >
                        <X size={20} />
                    </button>
                </div>

                {/* Content */}
                <div className="flex-1 overflow-y-auto p-4 space-y-4">
                    {/* Screenshot Preview */}
                    <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700">
                            <ImageIcon size={16} className="inline mr-1" />
                            {t('screenshotPreview')}
                        </label>
                        <div className="border rounded-lg p-2 bg-gray-50">
                            {screenshotUrl && (
                                <img
                                    src={screenshotUrl}
                                    alt="PDF Selection"
                                    className="max-w-full h-auto rounded"
                                />
                            )}
                        </div>
                    </div>

                    {/* Knowledge Group selector */}
                    <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700">
                            <Box size={16} className="inline mr-1" />
                            {t('associateKnowledgeGroup')}
                        </label>
                        <select
                            value={selectedGroupId || ''}
                            onChange={(e) => setSelectedGroupId(e.target.value || undefined)}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none"
                            disabled={saving}
                        >
                            <option value="">{t('globalNoSpecificGroup')}</option>
                            {groups.map(group => (
                                <option key={group.id} value={group.id}>
                                    {group.name}
                                </option>
                            ))}
                        </select>
                    </div>

                    {/* Title Input */}
                    <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700">
                            {t('title')}
                        </label>
                        <input
                            type="text"
                            value={title}
                            onChange={(e) => setTitle(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            placeholder={t('enterNoteTitle')}
                            disabled={saving}
                        />
                    </div>

                    {/* Content Textarea */}
                    <div className="space-y-2">
                        <label className="block text-sm font-medium text-gray-700">
                            {t('contentOCR')}
                        </label>
                        <textarea
                            value={content}
                            onChange={(e) => setContent(e.target.value)}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent font-mono text-sm"
                            rows={10}
                            placeholder={ocrLoading ? t('extractingText') : t('placeholderText')}
                            disabled={saving || ocrLoading}
                        />
                        {ocrLoading && (
                            <div className="flex items-center gap-2 mt-2 p-2 bg-blue-50/50 rounded-md border border-blue-100/50">
                                <Loader size={12} className="animate-spin" />
                                {t('analyzingImage')}
                            </div>
                        )}
                        {!ocrLoading && !content && (
                            <p className="text-sm text-gray-500">
                                {t('noTextExtracted')}
                            </p>
                        )}
                    </div>
                </div>

                {/* Footer */}
                <div className="flex items-center justify-end gap-2 p-4 border-t bg-gray-50">
                    <button
                        onClick={onCancel}
                        className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                        disabled={saving}
                    >
                        {t('cancel')}
                    </button>
                    <button
                        onClick={handleSave}
                        className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                        disabled={saving || !title.trim()}
                    >
                        {saving && <Loader size={16} className="animate-spin" />}
                        {saving ? t('saving') : t('saveNote')}
                    </button>
                </div>
            </div>
        </div>
    );
};
