'use client'

import { useState, useRef } from 'react'
import { Platform } from '@/domain'
import { useVersionActions, useAppType } from '@/application'
import { getVersionRepository } from '@/infrastructure/repositories/version-repository-impl'

interface UploadModalProps {
  onClose: () => void
  onSuccess: () => void
}

export function UploadModal({ onClose, onSuccess }: UploadModalProps) {
  const { uploadVersion } = useVersionActions()
  const { appType } = useAppType()
  const fileInputRef = useRef<HTMLInputElement>(null)

  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isParsing, setIsParsing] = useState(false)
  const [formData, setFormData] = useState({
    platform: 'android' as Platform,
    versionName: '',
    buildNumber: '',
    changelog: '',
    isForceUpdate: false,
    minOsVersion: '',
  })
  const [file, setFile] = useState<File | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [parseWarning, setParseWarning] = useState<string | null>(null)

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0]
    if (!selectedFile) return

    setFile(selectedFile)
    setError(null)
    setParseWarning(null)

    // Auto-detect platform from file extension
    let detectedPlatform: Platform = 'android'
    if (selectedFile.name.endsWith('.apk')) {
      detectedPlatform = 'android'
    } else if (selectedFile.name.endsWith('.ipa')) {
      detectedPlatform = 'ios'
    }
    setFormData((prev) => ({ ...prev, platform: detectedPlatform }))

    // Auto-parse package info
    setIsParsing(true)
    try {
      const parsed = await getVersionRepository(appType).parsePackage(selectedFile, detectedPlatform)
      setFormData((prev) => ({
        ...prev,
        platform: detectedPlatform,
        versionName: parsed.versionName || prev.versionName,
        buildNumber: parsed.versionCode?.toString() || prev.buildNumber,
        minOsVersion: parsed.minSdkVersion || prev.minOsVersion,
      }))
    } catch (err) {
      console.error('Failed to parse package:', err)
      // Show warning but allow user to fill in manually
      setParseWarning('无法自动解析安装包信息，请手动填写版本号和构建号')
    } finally {
      setIsParsing(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)

    if (!file) {
      setError('请选择安装包文件')
      return
    }

    if (!formData.versionName) {
      setError('请输入版本号')
      return
    }

    if (!formData.buildNumber) {
      setError('请输入构建号')
      return
    }

    setIsSubmitting(true)

    try {
      await uploadVersion({
        platform: formData.platform,
        versionName: formData.versionName,
        buildNumber: formData.buildNumber,
        changelog: formData.changelog || undefined,
        isForceUpdate: formData.isForceUpdate,
        minOsVersion: formData.minOsVersion || undefined,
        file,
      })
      onSuccess()
    } catch (err) {
      setError(err instanceof Error ? err.message : '上传失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl max-w-lg w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-xl font-semibold text-gray-900">上传新版本</h3>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
              {error}
            </div>
          )}

          {parseWarning && (
            <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-yellow-700 text-sm">
              {parseWarning}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* File Upload */}
            <div>
              <label className="label">安装包文件 *</label>
              <div
                onClick={() => fileInputRef.current?.click()}
                className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-blue-400 transition-colors"
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".apk,.ipa"
                  onChange={handleFileChange}
                  className="hidden"
                />
                {file ? (
                  <div>
                    <p className="text-gray-900 font-medium">{file.name}</p>
                    <p className="text-gray-500 text-sm">
                      {(file.size / (1024 * 1024)).toFixed(2)} MB
                    </p>
                    {isParsing && (
                      <p className="text-blue-500 text-sm mt-1">正在解析包信息...</p>
                    )}
                  </div>
                ) : (
                  <div>
                    <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                    </svg>
                    <p className="mt-2 text-gray-600">点击选择 APK 或 IPA 文件</p>
                  </div>
                )}
              </div>
            </div>

            {/* Platform */}
            <div>
              <label className="label">平台 *</label>
              <div className="flex gap-4">
                <label className="flex items-center">
                  <input
                    type="radio"
                    name="platform"
                    value="android"
                    checked={formData.platform === 'android'}
                    onChange={(e) => setFormData((prev) => ({ ...prev, platform: e.target.value as Platform }))}
                    className="mr-2"
                  />
                  Android
                </label>
                <label className="flex items-center">
                  <input
                    type="radio"
                    name="platform"
                    value="ios"
                    checked={formData.platform === 'ios'}
                    onChange={(e) => setFormData((prev) => ({ ...prev, platform: e.target.value as Platform }))}
                    className="mr-2"
                  />
                  iOS
                </label>
              </div>
            </div>

            {/* Version Name */}
            <div>
              <label className="label">版本号 *</label>
              <input
                type="text"
                value={formData.versionName}
                onChange={(e) => setFormData((prev) => ({ ...prev, versionName: e.target.value }))}
                placeholder="例如：1.0.0"
                className="input"
              />
            </div>

            {/* Build Number */}
            <div>
              <label className="label">构建号 *</label>
              <input
                type="text"
                value={formData.buildNumber}
                onChange={(e) => setFormData((prev) => ({ ...prev, buildNumber: e.target.value }))}
                placeholder="例如：100"
                className="input"
              />
            </div>

            {/* Min OS Version */}
            <div>
              <label className="label">最低系统版本</label>
              <input
                type="text"
                value={formData.minOsVersion}
                onChange={(e) => setFormData((prev) => ({ ...prev, minOsVersion: e.target.value }))}
                placeholder={formData.platform === 'android' ? '例如：8.0' : '例如：14.0'}
                className="input"
              />
            </div>

            {/* Changelog */}
            <div>
              <label className="label">更新日志</label>
              <textarea
                value={formData.changelog}
                onChange={(e) => setFormData((prev) => ({ ...prev, changelog: e.target.value }))}
                placeholder="请输入本版本的更新内容..."
                rows={4}
                className="input"
              />
            </div>

            {/* Force Update */}
            <div>
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={formData.isForceUpdate}
                  onChange={(e) => setFormData((prev) => ({ ...prev, isForceUpdate: e.target.checked }))}
                  className="mr-2"
                />
                <span className="text-gray-700">强制更新</span>
              </label>
              <p className="text-gray-500 text-xs mt-1">
                勾选后，用户必须更新到此版本才能继续使用应用
              </p>
            </div>

            {/* Actions */}
            <div className="flex justify-end gap-3 pt-4">
              <button
                type="button"
                onClick={onClose}
                className="btn bg-gray-100 text-gray-700 hover:bg-gray-200"
                disabled={isSubmitting}
              >
                取消
              </button>
              <button
                type="submit"
                className="btn btn-primary"
                disabled={isSubmitting || isParsing}
              >
                {isParsing ? '解析中...' : isSubmitting ? '上传中...' : '上传'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}
