/**
 * Python环境管理页面
 * 用于管理Python环境和依赖包
 */

import React, { useState, useEffect } from 'react'
import { invoke } from '@tauri-apps/api/core'
import {
  Code,
  Package,
  Download,
  Trash2,
  RefreshCw,
  Plus,
  Settings,
  CheckCircle,
  XCircle,
  AlertCircle,
  Search,
  Loader
} from 'lucide-react'

interface PythonEnvInfo {
  python_type: string
  python_path?: string
  version?: string
  is_available: boolean
  error?: string
}

interface PythonPackage {
  name: string
  version: string
  location?: string
}

interface PythonEnvStatus {
  embedded: PythonEnvInfo
  system: PythonEnvInfo
  current_env: string
  packages: PythonPackage[]
}

const PythonEnvManagerPage: React.FC = () => {
  const [envStatus, setEnvStatus] = useState<PythonEnvStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [installing, setInstalling] = useState<string | null>(null)
  const [newPackageName, setNewPackageName] = useState('')
  const [searchTerm, setSearchTerm] = useState('')
  const [showInstallForm, setShowInstallForm] = useState(false)

  // 加载Python环境状态
  const loadEnvStatus = async () => {
    try {
      setLoading(true)
      const status: PythonEnvStatus = await invoke('get_python_env_status')
      setEnvStatus(status)
    } catch (error) {
      console.error('Failed to load Python environment status:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadEnvStatus()
  }, [])

  // 安装包
  const handleInstallPackage = async (packageName: string) => {
    if (!packageName.trim()) return

    try {
      setInstalling(packageName)
      await invoke('install_python_package', { packageName: packageName.trim() })
      await loadEnvStatus() // 重新加载状态
      setNewPackageName('')
      setShowInstallForm(false)
    } catch (error) {
      console.error('Failed to install package:', error)
      alert(`安装失败: ${error}`)
    } finally {
      setInstalling(null)
    }
  }

  // 卸载包
  const handleUninstallPackage = async (packageName: string) => {
    if (!confirm(`确定要卸载 ${packageName} 吗？`)) return

    try {
      setInstalling(packageName)
      await invoke('uninstall_python_package', { packageName })
      await loadEnvStatus() // 重新加载状态
    } catch (error) {
      console.error('Failed to uninstall package:', error)
      alert(`卸载失败: ${error}`)
    } finally {
      setInstalling(null)
    }
  }

  // 升级包
  const handleUpgradePackage = async (packageName: string) => {
    try {
      setInstalling(packageName)
      await invoke('upgrade_python_package', { packageName })
      await loadEnvStatus() // 重新加载状态
    } catch (error) {
      console.error('Failed to upgrade package:', error)
      alert(`升级失败: ${error}`)
    } finally {
      setInstalling(null)
    }
  }

  // 设置嵌入式Python
  const handleSetupEmbeddedPython = async () => {
    if (!confirm('这将下载并设置嵌入式Python环境，可能需要几分钟时间。继续吗？')) return

    try {
      setLoading(true)
      await invoke('setup_embedded_python')
      await loadEnvStatus() // 重新加载状态
      alert('嵌入式Python环境设置完成！')
    } catch (error) {
      console.error('Failed to setup embedded Python:', error)
      alert(`设置失败: ${error}`)
    } finally {
      setLoading(false)
    }
  }

  // 简化设置嵌入式Python（使用批处理脚本）
  const handleSetupEmbeddedPythonSimple = async () => {
    if (!confirm('这将使用批处理脚本设置嵌入式Python环境。继续吗？')) return

    try {
      setLoading(true)
      await invoke('setup_embedded_python_simple')
      await loadEnvStatus() // 重新加载状态
      alert('嵌入式Python环境设置完成！')
    } catch (error) {
      console.error('Failed to setup embedded Python (simple):', error)
      alert(`设置失败: ${error}`)
    } finally {
      setLoading(false)
    }
  }

  // 过滤包列表
  const filteredPackages = envStatus?.packages.filter(pkg =>
    pkg.name.toLowerCase().includes(searchTerm.toLowerCase())
  ) || []

  const getEnvStatusIcon = (env: PythonEnvInfo) => {
    if (env.is_available) {
      return <CheckCircle className="w-5 h-5 text-green-500" />
    } else {
      return <XCircle className="w-5 h-5 text-red-500" />
    }
  }

  const getEnvStatusColor = (env: PythonEnvInfo) => {
    if (env.is_available) {
      return 'border-green-200 bg-green-50'
    } else {
      return 'border-red-200 bg-red-50'
    }
  }

  if (loading && !envStatus) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <Loader className="w-8 h-8 animate-spin mx-auto mb-4 text-blue-500" />
          <p className="text-gray-600">正在加载Python环境信息...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-6xl mx-auto">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2 flex items-center gap-3">
            <Code className="w-8 h-8 text-blue-600" />
            Python环境管理
          </h1>
          <p className="text-gray-600">
            管理Python环境和依赖包，确保应用正常运行
          </p>
        </div>

        {/* Python环境状态 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
          {/* 嵌入式Python */}
          <div className={`bg-white rounded-lg shadow-sm border-2 p-6 ${getEnvStatusColor(envStatus?.embedded || {} as PythonEnvInfo)}`}>
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                {getEnvStatusIcon(envStatus?.embedded || {} as PythonEnvInfo)}
                <div>
                  <h3 className="font-semibold text-gray-900">嵌入式Python</h3>
                  <p className="text-sm text-gray-600">应用内置Python环境</p>
                </div>
              </div>
              {envStatus?.current_env === 'embedded' && (
                <span className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                  当前使用
                </span>
              )}
            </div>
            
            {envStatus?.embedded.is_available ? (
              <div className="space-y-2 text-sm">
                <div><strong>版本:</strong> {envStatus.embedded.version}</div>
                <div><strong>路径:</strong> {envStatus.embedded.python_path}</div>
              </div>
            ) : (
              <div className="space-y-2">
                <div className="text-sm text-red-600">
                  <strong>错误:</strong> {envStatus?.embedded.error}
                </div>
                <div className="space-y-2">
                  <button
                    onClick={handleSetupEmbeddedPython}
                    disabled={loading}
                    className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 w-full"
                  >
                    <Download size={16} />
                    设置嵌入式Python
                  </button>

                  <button
                    onClick={handleSetupEmbeddedPythonSimple}
                    disabled={loading}
                    className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 w-full"
                  >
                    <Settings size={16} />
                    简化设置（批处理）
                  </button>

                  <p className="text-xs text-gray-500 mt-2">
                    如果上面的设置失败，请参考手动设置指南
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* 系统Python */}
          <div className={`bg-white rounded-lg shadow-sm border-2 p-6 ${getEnvStatusColor(envStatus?.system || {} as PythonEnvInfo)}`}>
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                {getEnvStatusIcon(envStatus?.system || {} as PythonEnvInfo)}
                <div>
                  <h3 className="font-semibold text-gray-900">系统Python</h3>
                  <p className="text-sm text-gray-600">系统安装的Python</p>
                </div>
              </div>
              {envStatus?.current_env === 'system' && (
                <span className="px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                  当前使用
                </span>
              )}
            </div>
            
            {envStatus?.system.is_available ? (
              <div className="space-y-2 text-sm">
                <div><strong>版本:</strong> {envStatus.system.version}</div>
                <div><strong>路径:</strong> {envStatus.system.python_path}</div>
              </div>
            ) : (
              <div className="text-sm text-red-600">
                <strong>错误:</strong> {envStatus?.system.error}
              </div>
            )}
          </div>
        </div>

        {/* 包管理 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-3">
              <Package className="w-6 h-6 text-green-600" />
              <div>
                <h2 className="text-xl font-semibold text-gray-900">已安装的包</h2>
                <p className="text-sm text-gray-600">
                  当前环境: {envStatus?.current_env === 'embedded' ? '嵌入式Python' : 
                            envStatus?.current_env === 'system' ? '系统Python' : '无可用环境'}
                </p>
              </div>
            </div>
            
            <div className="flex items-center gap-3">
              <button
                onClick={loadEnvStatus}
                disabled={loading}
                className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:opacity-50"
              >
                <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
                刷新
              </button>
              
              <button
                onClick={() => setShowInstallForm(!showInstallForm)}
                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                <Plus size={16} />
                安装包
              </button>
            </div>
          </div>

          {/* 安装包表单 */}
          {showInstallForm && (
            <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <div className="flex items-center gap-3">
                <input
                  type="text"
                  value={newPackageName}
                  onChange={(e) => setNewPackageName(e.target.value)}
                  placeholder="输入包名，如: requests, numpy, pillow"
                  className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  onKeyDown={(e) => e.key === 'Enter' && handleInstallPackage(newPackageName)}
                />
                <button
                  onClick={() => handleInstallPackage(newPackageName)}
                  disabled={!newPackageName.trim() || installing !== null}
                  className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
                >
                  安装
                </button>
                <button
                  onClick={() => setShowInstallForm(false)}
                  className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700"
                >
                  取消
                </button>
              </div>
            </div>
          )}

          {/* 搜索框 */}
          <div className="mb-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <input
                type="text"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="搜索已安装的包..."
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              />
            </div>
          </div>

          {/* 包列表 */}
          <div className="space-y-2">
            {filteredPackages.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                {envStatus?.packages.length === 0 ? '没有找到已安装的包' : '没有匹配的包'}
              </div>
            ) : (
              filteredPackages.map((pkg) => (
                <div
                  key={pkg.name}
                  className="flex items-center justify-between p-4 border border-gray-200 rounded-lg hover:bg-gray-50"
                >
                  <div className="flex items-center gap-3">
                    <Package className="w-5 h-5 text-gray-400" />
                    <div>
                      <div className="font-medium text-gray-900">{pkg.name}</div>
                      <div className="text-sm text-gray-500">版本: {pkg.version}</div>
                    </div>
                  </div>
                  
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => handleUpgradePackage(pkg.name)}
                      disabled={installing === pkg.name}
                      className="flex items-center gap-1 px-3 py-1 text-sm bg-green-100 text-green-700 rounded hover:bg-green-200 disabled:opacity-50"
                    >
                      {installing === pkg.name ? (
                        <Loader size={14} className="animate-spin" />
                      ) : (
                        <RefreshCw size={14} />
                      )}
                      升级
                    </button>
                    
                    <button
                      onClick={() => handleUninstallPackage(pkg.name)}
                      disabled={installing === pkg.name}
                      className="flex items-center gap-1 px-3 py-1 text-sm bg-red-100 text-red-700 rounded hover:bg-red-200 disabled:opacity-50"
                    >
                      {installing === pkg.name ? (
                        <Loader size={14} className="animate-spin" />
                      ) : (
                        <Trash2 size={14} />
                      )}
                      卸载
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>

        {/* 环境信息 */}
        {envStatus?.current_env === 'none' && (
          <div className="mt-6 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div className="flex items-center gap-3">
              <AlertCircle className="w-5 h-5 text-yellow-600" />
              <div>
                <h3 className="font-medium text-yellow-800">没有可用的Python环境</h3>
                <p className="text-sm text-yellow-700 mt-1">
                  请设置嵌入式Python环境或确保系统已安装Python。
                </p>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export default PythonEnvManagerPage
