'use client';

import { useState, useRef } from 'react';
import { X, Upload } from 'lucide-react';
import { toast } from 'sonner';
import { AppPlatform, UploadAppVersionInput } from '@/domain/entities/app-version';
import { uploadVersion, parsePackage } from '@/infrastructure/repositories/api-app-version.repository';

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

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

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

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

    setFile(selected);
    setParseWarning(null);

    const detectedPlatform: AppPlatform = selected.name.endsWith('.ipa') ? 'ios' : 'android';
    setFormData((prev) => ({ ...prev, platform: detectedPlatform }));

    setIsParsing(true);
    try {
      const parsed = await parsePackage(selected, detectedPlatform);
      setFormData((prev) => ({
        ...prev,
        platform: detectedPlatform,
        versionName: parsed.versionName || prev.versionName,
        buildNumber: parsed.versionCode || prev.buildNumber,
        minOsVersion: parsed.minSdkVersion || prev.minOsVersion,
      }));
    } catch {
      setParseWarning('无法自动解析安装包信息，请手动填写版本号和构建号');
    } finally {
      setIsParsing(false);
    }
  };

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

    if (!file) {
      toast.error('请选择安装包文件');
      return;
    }
    if (!formData.versionName.trim()) {
      toast.error('请输入版本号');
      return;
    }
    if (!formData.buildNumber.trim()) {
      toast.error('请输入构建号');
      return;
    }

    setIsSubmitting(true);
    try {
      const input: UploadAppVersionInput = {
        file,
        platform: formData.platform,
        versionName: formData.versionName.trim(),
        buildNumber: formData.buildNumber.trim(),
        changelog: formData.changelog.trim() || undefined,
        isForceUpdate: formData.isForceUpdate,
        minOsVersion: formData.minOsVersion.trim() || undefined,
      };
      await uploadVersion(input);
      onSuccess();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '上传失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  const field = (label: string, required = false) => (
    <span className="text-sm font-medium text-foreground">
      {label}
      {required && <span className="text-red-400 ml-0.5">*</span>}
    </span>
  );

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
      <div className="bg-card rounded-xl border shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b shrink-0">
          <h3 className="text-base font-semibold text-foreground">上传新版本</h3>
          <button
            onClick={onClose}
            className="text-muted-foreground hover:text-foreground transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-5">
          {parseWarning && (
            <div className="mb-4 p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30 text-yellow-400 text-sm">
              {parseWarning}
            </div>
          )}

          <form id="upload-form" onSubmit={handleSubmit} className="space-y-4">
            {/* File upload */}
            <div className="space-y-1.5">
              {field('安装包文件', true)}
              <div
                onClick={() => fileInputRef.current?.click()}
                className="border-2 border-dashed border-border rounded-lg p-6 text-center cursor-pointer hover:border-primary/50 transition-colors"
              >
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".apk,.ipa"
                  onChange={handleFileChange}
                  className="hidden"
                />
                {file ? (
                  <div>
                    <p className="text-foreground font-medium text-sm">{file.name}</p>
                    <p className="text-muted-foreground text-xs mt-1">
                      {(file.size / (1024 * 1024)).toFixed(2)} MB
                    </p>
                    {isParsing && (
                      <p className="text-primary text-xs mt-1">正在解析包信息...</p>
                    )}
                  </div>
                ) : (
                  <div>
                    <Upload className="mx-auto h-10 w-10 text-muted-foreground mb-2" />
                    <p className="text-muted-foreground text-sm">点击选择 APK 或 IPA 文件</p>
                  </div>
                )}
              </div>
            </div>

            {/* Platform */}
            <div className="space-y-1.5">
              {field('平台', true)}
              <div className="flex gap-4">
                {(['android', 'ios'] as AppPlatform[]).map((p) => (
                  <label key={p} className="flex items-center gap-2 cursor-pointer">
                    <input
                      type="radio"
                      name="platform"
                      value={p}
                      checked={formData.platform === p}
                      onChange={() => setFormData((prev) => ({ ...prev, platform: p }))}
                      className="accent-primary"
                    />
                    <span className="text-sm text-foreground capitalize">{p}</span>
                  </label>
                ))}
              </div>
            </div>

            {/* Version name */}
            <div className="space-y-1.5">
              {field('版本号', true)}
              <input
                type="text"
                value={formData.versionName}
                onChange={(e) => setFormData((prev) => ({ ...prev, versionName: e.target.value }))}
                placeholder="例如：1.0.0"
                className="w-full rounded-md border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary"
              />
            </div>

            {/* Build number */}
            <div className="space-y-1.5">
              {field('构建号', true)}
              <input
                type="text"
                value={formData.buildNumber}
                onChange={(e) => setFormData((prev) => ({ ...prev, buildNumber: e.target.value }))}
                placeholder="例如：100"
                className="w-full rounded-md border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary"
              />
            </div>

            {/* Min OS version */}
            <div className="space-y-1.5">
              {field('最低系统版本')}
              <input
                type="text"
                value={formData.minOsVersion}
                onChange={(e) => setFormData((prev) => ({ ...prev, minOsVersion: e.target.value }))}
                placeholder={formData.platform === 'android' ? '例如：8.0' : '例如：14.0'}
                className="w-full rounded-md border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary"
              />
            </div>

            {/* Changelog */}
            <div className="space-y-1.5">
              {field('更新日志')}
              <textarea
                value={formData.changelog}
                onChange={(e) => setFormData((prev) => ({ ...prev, changelog: e.target.value }))}
                placeholder="请输入本版本的更新内容..."
                rows={4}
                className="w-full rounded-md border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary resize-none"
              />
            </div>

            {/* Force update */}
            <label className="flex items-start gap-2.5 cursor-pointer">
              <input
                type="checkbox"
                checked={formData.isForceUpdate}
                onChange={(e) => setFormData((prev) => ({ ...prev, isForceUpdate: e.target.checked }))}
                className="mt-0.5 accent-primary"
              />
              <div>
                <span className="text-sm font-medium text-foreground">强制更新</span>
                <p className="text-xs text-muted-foreground mt-0.5">
                  勾选后，用户必须更新到此版本才能继续使用应用
                </p>
              </div>
            </label>
          </form>
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-2.5 p-5 border-t shrink-0">
          <button
            type="button"
            onClick={onClose}
            disabled={isSubmitting}
            className="px-4 py-2 rounded-md text-sm font-medium bg-accent text-foreground hover:bg-accent/80 transition-colors disabled:opacity-50"
          >
            取消
          </button>
          <button
            type="submit"
            form="upload-form"
            disabled={isSubmitting || isParsing}
            className="px-4 py-2 rounded-md text-sm font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
          >
            {isParsing ? '解析中...' : isSubmitting ? '上传中...' : '上传'}
          </button>
        </div>
      </div>
    </div>
  );
}
