'use client';

import { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import { toast } from 'sonner';
import { AppVersion, UpdateAppVersionInput } from '@/domain/entities/app-version';
import { getVersionById, updateVersion } from '@/infrastructure/repositories/api-app-version.repository';

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

export function EditModal({ versionId, onClose, onSuccess }: EditModalProps) {
  const [version, setVersion] = useState<AppVersion | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    changelog: '',
    isForceUpdate: false,
    isEnabled: true,
    minOsVersion: '',
  });

  useEffect(() => {
    setIsLoading(true);
    getVersionById(versionId)
      .then((v) => {
        setVersion(v);
        setFormData({
          changelog: v.changelog || '',
          isForceUpdate: v.isForceUpdate,
          isEnabled: v.isEnabled,
          minOsVersion: v.minOsVersion || '',
        });
      })
      .catch((err) => setLoadError(err instanceof Error ? err.message : '加载失败'))
      .finally(() => setIsLoading(false));
  }, [versionId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      const input: UpdateAppVersionInput = {
        changelog: formData.changelog.trim() || undefined,
        isForceUpdate: formData.isForceUpdate,
        isEnabled: formData.isEnabled,
        minOsVersion: formData.minOsVersion.trim() || null,
      };
      await updateVersion(versionId, input);
      onSuccess();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '更新失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  const field = (label: string) => (
    <span className="text-sm font-medium text-foreground">{label}</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">
          <div>
            <h3 className="text-base font-semibold text-foreground">编辑版本</h3>
            {version && (
              <p className="text-xs text-muted-foreground mt-0.5">
                {version.platform.toUpperCase()} v{version.versionName} (Build {version.buildNumber})
              </p>
            )}
          </div>
          <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">
          {isLoading ? (
            <div className="flex items-center justify-center py-10">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary" />
            </div>
          ) : loadError || !version ? (
            <div className="text-center py-10">
              <p className="text-red-400 text-sm">{loadError || '加载版本信息失败'}</p>
              <button
                onClick={onClose}
                className="mt-4 px-4 py-2 rounded-md text-sm bg-primary text-primary-foreground hover:bg-primary/90"
              >
                关闭
              </button>
            </div>
          ) : (
            <form id="edit-form" onSubmit={handleSubmit} className="space-y-4">
              {/* 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={version.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>

              {/* Enabled */}
              <label className="flex items-start gap-2.5 cursor-pointer">
                <input
                  type="checkbox"
                  checked={formData.isEnabled}
                  onChange={(e) => setFormData((prev) => ({ ...prev, isEnabled: 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 */}
        {!isLoading && !loadError && version && (
          <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="edit-form"
              disabled={isSubmitting}
              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"
            >
              {isSubmitting ? '保存中...' : '保存'}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
