import { useState, useRef, useEffect } from 'react';
import {
  useImages,
  usePendingImages,
  useUploadImageFile,
  useReprocessImage,
  useOCRProviders,
  useConvertImageToTodo,
} from '@/hooks/useImages';
import { useCreateDocument } from '@/hooks/useDocuments';
import { Button } from '@/components/Button';
import { Card } from '@/components/Card';
import { Upload, Camera, FileText, CheckSquare, X, RefreshCw, ChevronDown, Settings, Sparkles } from 'lucide-react';
import type { Image } from '@/types';
import { useDeleteImage } from '@/hooks/useImages';
import { useNavigate } from 'react-router';

const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';

// 获取完整的图片 URL
const getImageUrl = (path: string) => {
  if (path.startsWith('http://') || path.startsWith('https://')) {
    return path;
  }
  return `${API_BASE_URL}${path}`;
};

// OCR Provider 显示名称映射
const PROVIDER_NAMES: Record<string, string> = {
  tesseract: 'Tesseract.js',
  baidu: '百度 OCR',
  rapidocr: 'RapidOCR',
  auto: '自动选择',
};

// OCR Provider 描述
const PROVIDER_DESCRIPTIONS: Record<string, string> = {
  tesseract: '本地轻量，免费',
  baidu: '云端准确，有免费额度',
  rapidocr: '本地快速准确，推荐',
  auto: '自动选择可用的服务',
};

export default function ImagesPage() {
  const navigate = useNavigate();
  const { data: images, refetch } = useImages();
  const { data: pendingImages } = usePendingImages();
  const { data: providers } = useOCRProviders();
  const uploadMutation = useUploadImageFile();
  const deleteMutation = useDeleteImage();
  const reprocessMutation = useReprocessImage();
  const convertMutation = useConvertImageToTodo();
  const createDocumentMutation = useCreateDocument();
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Provider 选择状态
  const [showProviderMenu, setShowProviderMenu] = useState<string | null>(null);

  // OCR 处理状态轮询
  useEffect(() => {
    // 检查是否有处理中的图片
    const hasPendingImages = images?.some(
      (img) => img.processing_status === 'pending' || img.processing_status === 'processing'
    );

    if (hasPendingImages) {
      const interval = setInterval(() => {
        refetch();
      }, 3000); // 每3秒轮询一次

      return () => clearInterval(interval);
    }
  }, [images, refetch]);

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = () => setShowProviderMenu(null);
    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    // 验证并上传所有文件
    const validFiles = Array.from(files).filter((file) => {
      if (!file.type.startsWith('image/')) {
        alert(`文件 "${file.name}" 不是图片文件`);
        return false;
      }
      if (file.size > 10 * 1024 * 1024) {
        alert(`文件 "${file.name}" 超过 10MB 限制`);
        return false;
      }
      return true;
    });

    if (validFiles.length === 0) return;

    // 依次上传所有文件
    for (const file of validFiles) {
      try {
        await uploadMutation.mutateAsync({ file });
      } catch (err: any) {
        console.error(`上传 ${file.name} 失败:`, err);
      }
    }

    // 清空 input 允许再次选择同一文件
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleCapture = async () => {
    try {
      // 调用系统截图功能
      const stream = await navigator.mediaDevices.getDisplayMedia({
        video: { mediaSource: 'screen' as any },
      });

      // 创建视频元素捕获帧
      const video = document.createElement('video');
      video.srcObject = stream;
      await video.play();

      // 创建 canvas 截取当前帧
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx?.drawImage(video, 0, 0);

      // 停止视频流
      stream.getTracks().forEach((track) => track.stop());

      // 转换为 blob 并上传
      canvas.toBlob(async (blob) => {
        if (blob) {
          const file = new File([blob], `screenshot-${Date.now()}.png`, { type: 'image/png' });
          try {
            await uploadMutation.mutateAsync({ file });
          } catch (err: any) {
            alert(err.message || '上传截图失败');
          }
        }
      }, 'image/png');
    } catch (err: any) {
      if (err.name !== 'NotAllowedError') {
        alert('截图失败');
      }
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这张图片吗？')) return;

    try {
      await deleteMutation.mutateAsync(id);
    } catch (err: any) {
      alert(err.message || '删除失败');
    }
  };

  const handleReprocess = async (id: string, provider?: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    try {
      await reprocessMutation.mutateAsync({ id, provider });
      setShowProviderMenu(null);
    } catch (err: any) {
      alert(err.message || '重新处理失败');
    }
  };

  const handleCreateDocument = async (image: Image, e?: React.MouseEvent) => {
    e?.stopPropagation();
    if (!image.ocr_result) {
      alert('OCR 识别尚未完成，无法创建文档');
      return;
    }
    try {
      const doc = await createDocumentMutation.mutateAsync({
        title: `从图片提取: ${image.file_path.split('/').pop()}`,
        content: image.ocr_result,
      });
      // 将图片关联到文档（需要调用后端 API）
      await fetch(`${API_BASE_URL}/images/${image.id}/link`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${localStorage.getItem('auth_token')}`,
        },
        body: JSON.stringify({ document_id: doc.id }),
      });
      refetch();
      alert('已创建文档！');
    } catch (err: any) {
      alert(err.message || '创建文档失败');
    }
  };

  const handleConvertToTodo = async (imageId: string, e?: React.MouseEvent) => {
    e?.stopPropagation();
    try {
      const todo = await convertMutation.mutateAsync({ id: imageId });
      alert('已成功转换为待办事项！');
      // 可选：跳转到待办页面
      // navigate('/todos');
    } catch (err: any) {
      alert(err.message || '转换为待办失败');
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case 'completed':
        return '已完成';
      case 'pending':
        return '等待处理';
      case 'processing':
        return 'OCR 处理中';
      case 'failed':
        return '处理失败';
      default:
        return status;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-green-100 text-green-800';
      case 'pending':
        return 'bg-yellow-100 text-yellow-800';
      case 'processing':
        return 'bg-blue-100 text-blue-800';
      case 'failed':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  // 获取可用的 provider 列表
  const availableProviders = providers?.filter((p) => p.available) || [];
  const hasProviders = availableProviders.length > 0;

  const hasProcessingImages = images?.some(
    (img) => img.processing_status === 'pending' || img.processing_status === 'processing'
  );

  // OCR 重新处理按钮组件
  const ReprocessButton = ({ image }: { image: Image }) => {
    const isProcessing = image.processing_status === 'processing';
    const canReprocess = image.processing_status === 'completed' || image.processing_status === 'failed';

    if (!canReprocess) return null;

    return (
      <div className="relative">
        <button
          onClick={(e) => {
            e.stopPropagation();
            if (showProviderMenu === image.id) {
              setShowProviderMenu(null);
            } else {
              setShowProviderMenu(image.id);
            }
          }}
          disabled={reprocessMutation.isPending}
          className="flex items-center gap-1 rounded border border-orange-300 px-2 py-1 text-xs text-orange-600 hover:bg-orange-50 disabled:opacity-50"
        >
          <RefreshCw className="h-3 w-3" />
          重新识别
          {hasProviders && <ChevronDown className="h-3 w-3" />}
        </button>

        {/* Provider 选择菜单 */}
        {hasProviders && showProviderMenu === image.id && (
          <div
            className="absolute bottom-full left-0 mb-1 z-20 min-w-[200px] rounded-lg border border-gray-200 bg-white shadow-lg"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="p-2 border-b border-gray-100">
              <p className="text-xs font-medium text-gray-700">选择 OCR 引擎</p>
            </div>
            <div className="p-1">
              {/* 自动选择 */}
              <button
                onClick={(e) => handleReprocess(image.id, 'auto', e)}
                className="w-full text-left px-3 py-2 text-sm hover:bg-gray-50 rounded flex items-center justify-between group"
              >
                <div>
                  <div className="font-medium text-gray-800">自动选择</div>
                  <div className="text-xs text-gray-500">系统自动选择可用的服务</div>
                </div>
                {reprocessMutation.isPending && (
                  <RefreshCw className="h-4 w-4 animate-spin text-gray-400" />
                )}
              </button>
              {/* 可用的 providers */}
              {availableProviders.map((provider) => (
                <button
                  key={provider.type}
                  onClick={(e) => handleReprocess(image.id, provider.type, e)}
                  className="w-full text-left px-3 py-2 text-sm hover:bg-gray-50 rounded flex items-center justify-between group"
                >
                  <div>
                    <div className="font-medium text-gray-800">{provider.name}</div>
                    <div className="text-xs text-gray-500">{provider.typeDesc}</div>
                  </div>
                  {reprocessMutation.isPending && (
                    <RefreshCw className="h-4 w-4 animate-spin text-gray-400" />
                  )}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">图片管理</h1>
          <p className="mt-1 text-sm text-gray-600">上传和管理您的图片</p>
        </div>
        <div className="flex items-center gap-4">
          {hasProviders && (
            <div className="flex items-center gap-2 text-xs text-gray-500">
              <Settings className="h-4 w-4" />
              <span>
                可用 OCR: {availableProviders.map((p) => p.name).join(', ')}
              </span>
            </div>
          )}
          {hasProcessingImages && (
            <div className="flex items-center gap-2 text-sm text-blue-600">
              <RefreshCw className="h-4 w-4 animate-spin" />
              <span>OCR 处理中...</span>
            </div>
          )}
        </div>
      </div>

      {/* Upload Actions */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card variant="bordered">
          <div className="text-center">
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              multiple
              className="hidden"
              onChange={handleFileSelect}
            />
            <div className="mb-4 flex justify-center">
              <div className="rounded-full bg-blue-50 p-4">
                <Upload className="h-8 w-8 text-blue-600" />
              </div>
            </div>
            <h3 className="mb-2 text-lg font-semibold">上传图片</h3>
            <p className="mb-4 text-sm text-gray-600">支持选择多张图片</p>
            <Button
              onClick={() => fileInputRef.current?.click()}
              loading={uploadMutation.isPending}
            >
              选择文件
            </Button>
          </div>
        </Card>

        <Card variant="bordered">
          <div className="text-center">
            <div className="mb-4 flex justify-center">
              <div className="rounded-full bg-green-50 p-4">
                <Camera className="h-8 w-8 text-green-600" />
              </div>
            </div>
            <h3 className="mb-2 text-lg font-semibold">屏幕截图</h3>
            <p className="mb-4 text-sm text-gray-600">使用系统截图功能</p>
            <Button
              onClick={handleCapture}
              variant="secondary"
              loading={uploadMutation.isPending}
            >
              开始截图
            </Button>
          </div>
        </Card>
      </div>

      {/* Pending OCR */}
      {pendingImages && pendingImages.length > 0 && (
        <Card title="等待 OCR 处理" variant="bordered">
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {pendingImages.map((image) => (
              <div
                key={image.id}
                className="rounded-lg border border-yellow-200 bg-yellow-50 p-4"
              >
                <div className="mb-2 flex items-center justify-between">
                  <span className="text-xs font-medium text-yellow-800">等待处理</span>
                  <span className="text-xs text-yellow-600">
                    {new Date(image.created_at).toLocaleString()}
                  </span>
                </div>
                <p className="text-sm text-yellow-700 truncate">{image.file_path}</p>
              </div>
            ))}
          </div>
        </Card>
      )}

      {/* Images Grid */}
      <Card
        title={`所有图片 (${images?.length || 0})`}
        variant="bordered"
        extra={
          hasProcessingImages && (
            <button
              onClick={() => refetch()}
              className="flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700"
            >
              <RefreshCw className="h-4 w-4" />
              刷新
            </button>
          )
        }
      >
        {images && images.length > 0 ? (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {images.map((image) => (
              <div
                key={image.id}
                className="group relative overflow-hidden rounded-lg border border-gray-200 bg-white"
              >
                <button
                  onClick={() => handleDelete(image.id)}
                  className="absolute right-2 top-2 z-10 rounded-full bg-red-500 p-1 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-600"
                >
                  <X className="h-4 w-4" />
                </button>

                {/* 图片预览 */}
                <img
                  src={getImageUrl(image.file_path)}
                  alt="Upload"
                  className="h-48 w-full object-cover"
                  loading="lazy"
                />

                <div className="p-3">
                  {/* 状态标签 */}
                  <div className="mb-2 flex items-center justify-between">
                    <span
                      className={`rounded px-2 py-1 text-xs font-medium ${getStatusColor(
                        image.processing_status
                      )}`}
                    >
                      {image.processing_status === 'processing' && (
                        <RefreshCw className="mr-1 h-3 w-3 animate-spin inline" />
                      )}
                      {getStatusLabel(image.processing_status)}
                    </span>
                    {image.ocr_confidence !== null &&
                      image.ocr_confidence !== undefined && (
                        <span className="text-xs text-gray-600">
                          置信度: {Math.round(image.ocr_confidence * 100)}%
                        </span>
                      )}
                  </div>

                  {/* OCR 结果 */}
                  {image.ocr_result && (
                    <p className="mb-2 line-clamp-2 text-sm text-gray-600">
                      {image.ocr_result}
                    </p>
                  )}

                  {/* 错误信息 */}
                  {image.error_message && (
                    <p className="mb-2 text-xs text-red-600">{image.error_message}</p>
                  )}

                  {/* 操作按钮 */}
                  <div className="flex flex-wrap gap-2">
                    <ReprocessButton image={image} />

                    {image.processing_status === 'completed' && image.ocr_result ? (
                      <>
                        {image.document_id ? (
                          <>
                            <button
                              onClick={() => navigate(`/documents/${image.document_id}`)}
                              className="flex items-center rounded bg-blue-50 px-2 py-1 text-xs text-blue-600 hover:bg-blue-100"
                            >
                              <FileText className="mr-1 h-3 w-3" />
                              查看文档
                            </button>
                            <button
                              onClick={(e) => handleConvertToTodo(image.id, e)}
                              disabled={convertMutation.isPending}
                              className="flex items-center rounded border border-gray-300 px-2 py-1 text-xs text-gray-600 hover:bg-gray-50 disabled:opacity-50"
                            >
                              <CheckSquare className="mr-1 h-3 w-3" />
                              {convertMutation.isPending ? '转换中...' : '转为待办'}
                            </button>
                          </>
                        ) : (
                          <button
                            onClick={(e) => handleCreateDocument(image, e)}
                            disabled={createDocumentMutation.isPending}
                            className="flex items-center rounded bg-green-50 px-2 py-1 text-xs text-green-600 hover:bg-green-100 disabled:opacity-50"
                          >
                            <FileText className="mr-1 h-3 w-3" />
                            {createDocumentMutation.isPending ? '创建中...' : '创建文档'}
                          </button>
                        )}
                      </>
                    ) : null}
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="py-8 text-center text-gray-500">暂无图片，请上传图片开始使用</p>
        )}
      </Card>
    </div>
  );
}
