'use client'

import { useState, useEffect } from 'react'
import { useVersion, useVersionActions } from '@/application'

interface EditModalProps {
  versionId: string
  onClose: () => void
  onSuccess: () => void
}

export function EditModal({ versionId, onClose, onSuccess }: EditModalProps) {
  const { version, isLoading, error: loadError } = useVersion(versionId)
  const { updateVersion } = useVersionActions()

  const [isSubmitting, setIsSubmitting] = useState(false)
  const [formData, setFormData] = useState({
    changelog: '',
    isForceUpdate: false,
    isEnabled: true,
    minOsVersion: '',
  })
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (version) {
      setFormData({
        changelog: version.changelog || '',
        isForceUpdate: version.isForceUpdate,
        isEnabled: version.isEnabled,
        minOsVersion: version.minOsVersion || '',
      })
    }
  }, [version])

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

    try {
      await updateVersion(versionId, {
        changelog: formData.changelog || undefined,
        isForceUpdate: formData.isForceUpdate,
        isEnabled: formData.isEnabled,
        minOsVersion: formData.minOsVersion || undefined,
      })
      onSuccess()
    } catch (err) {
      setError(err instanceof Error ? err.message : '更新失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  if (isLoading) {
    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 p-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="text-gray-600 mt-4">加载中...</p>
        </div>
      </div>
    )
  }

  if (loadError || !version) {
    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 p-8">
          <p className="text-red-600">加载版本信息失败</p>
          <button onClick={onClose} className="btn btn-primary mt-4">
            关闭
          </button>
        </div>
      </div>
    )
  }

  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">
            <div>
              <h3 className="text-xl font-semibold text-gray-900">编辑版本</h3>
              <p className="text-gray-500 text-sm mt-1">
                {version.platform.toUpperCase()} v{version.versionName} (Build {version.buildNumber})
              </p>
            </div>
            <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>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Min OS Version */}
            <div>
              <label className="label">最低系统版本</label>
              <input
                type="text"
                value={formData.minOsVersion}
                onChange={(e) => setFormData((prev) => ({ ...prev, minOsVersion: e.target.value }))}
                placeholder={version.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>

            {/* Enabled */}
            <div>
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={formData.isEnabled}
                  onChange={(e) => setFormData((prev) => ({ ...prev, isEnabled: 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}
              >
                {isSubmitting ? '保存中...' : '保存'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}
