/**
 * Registry Configuration Form
 * For adding and editing registry configurations
 */
import React, { useState } from "react";
import { Save, X, TestTube } from "lucide-react";
import type { RegistryResponse } from "@/core/types";
import { checkRegistryHealth } from "@/api";
import { useToast } from "@/shared";
import { RegistryErrors, SuccessMessages, formatApiError } from "@/shared/utils";
import { ButtonText, LabelText } from "@/shared/constants";

interface RegistryFormProps {
  registry?: RegistryResponse;
  onSave: (data: Omit<RegistryResponse, "id">) => void;
  onCancel: () => void;
}

export const RegistryForm: React.FC<RegistryFormProps> = ({
  registry,
  onSave,
  onCancel,
}) => {
  const { success, error: toastError, info: toastInfo } = useToast();
  const [testing, setTesting] = useState(false);

  const [formData, setFormData] = useState<
    Omit<RegistryResponse, "id" | "createdAt" | "updatedAt">
  >({
    name: registry?.name || "",
    url: registry?.url || "",
    description: registry?.description || "",
    username: registry?.username || "",
    password: registry?.password || "",
    hasPassword: registry?.hasPassword || false,
    insecure: registry?.insecure || false,
  });

  // 新密码输入（编辑模式）
  const [newPassword, setNewPassword] = useState<string>("");

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value, type } = e.target;
    const checked = type === "checkbox" ? (e.target as HTMLInputElement).checked : undefined;

    setFormData((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // 准备提交数据
    const submitData = { ...formData };
    
    // 编辑模式：如果用户输入了新密码，使用新密码；否则不发送密码字段
    if (registry) {
      if (newPassword) {
        submitData.password = newPassword;
      } else {
        // 不发送密码字段，保持后端原有密码
        delete (submitData as any).password;
      }
    }
    
    onSave(submitData);
  };

  const handleTest = async () => {
    if (!registry?.id) {
      toastError("Please save the registry configuration before testing the connection.");
      return;
    }

    toastInfo("Testing registry connection...", {
      title: "Connection Test",
      durationMs: 1800,
      mergeKey: `registry-test-${registry.id}`,
    });

    setTesting(true);
    try {
      const result = await checkRegistryHealth({ registryId: registry.id }) as any;
      // ✅ FIX: Backend returns { healthy: boolean, message: string }
      if (result.healthy === true) {
        success(result.message || SuccessMessages.REGISTRY_CONNECTION_OK);
      } else {
        const errorMsg = result.message || RegistryErrors.CONNECTION_TEST_FAILED;
        toastError(errorMsg);
      }
    } catch (error) {
      toastError(formatApiError(error) || RegistryErrors.CONNECTION_TEST_FAILED);
      console.error(error);
    } finally {
      setTesting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {/* Name */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">
          {LabelText.NAME} <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          name="name"
          value={formData.name}
          onChange={handleChange}
          required
          placeholder="e.g., Harbor Production"
          className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-blue-500 focus:outline-none"
        />
      </div>

      {/* URL */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">
          Registry URL <span className="text-red-400">*</span>
        </label>
        <input
          type="url"
          name="url"
          value={formData.url}
          onChange={handleChange}
          required
          placeholder="https://registry.example.com"
          className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-blue-500 focus:outline-none"
        />
        <p className="mt-1 text-xs text-slate-500">
          OCI registry access URL (e.g., https://registry.hub.docker.com)
        </p>
      </div>

      {/* Username */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">
          {LabelText.USERNAME} <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          name="username"
          value={formData.username}
          onChange={handleChange}
          required
          placeholder="Registry username"
          className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-blue-500 focus:outline-none"
        />
      </div>

      {/* Password */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">
          {LabelText.PASSWORD} {!registry && <span className="text-red-400">*</span>}
        </label>
        {registry ? (
          // 编辑模式：显示状态和新密码输入
          <>
            <div className="mb-2 flex items-center gap-2 px-3 py-2 bg-slate-50 border border-slate-300 rounded-lg">
              <span className="text-slate-500 text-sm">当前密码:</span>
              <span className="text-slate-900 font-mono">{formData.password}</span>
              {formData.hasPassword && (
                <span className="ml-auto text-xs text-green-400 flex items-center gap-1">
                  <span className="w-2 h-2 bg-green-400 rounded-full"></span>
                  已设置（加密存储）
                </span>
              )}
            </div>
            <input
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              placeholder="输入新密码以覆盖（留空保持不变）"
              className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-blue-500 focus:outline-none"
            />
            <p className="mt-1 text-xs text-slate-500">
              💡 输入新密码以覆盖原密码，留空则保持原密码不变
            </p>
          </>
        ) : (
          // 创建模式：必填
          <input
            type="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            required
            placeholder="Registry password or access token"
            className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-blue-500 focus:outline-none"
          />
        )}
      </div>

      {/* Description */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1">
          {LabelText.DESCRIPTION}
        </label>
        <textarea
          name="description"
          value={formData.description}
          onChange={handleChange}
          rows={3}
          placeholder="Registry purpose or description"
          className="w-full px-3 py-2 bg-white border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-blue-500 focus:outline-none resize-none"
        />
      </div>

      {/* Insecure */}
      <div className="flex items-center">
        <input
          type="checkbox"
          id="insecure"
          name="insecure"
          checked={formData.insecure}
          onChange={handleChange}
          className="w-4 h-4 text-purple-600 bg-white border-slate-300 rounded focus:ring-blue-500 focus:ring-2"
        />
        <label htmlFor="insecure" className="ml-2 text-sm text-slate-700">
          Allow insecure connection (skip SSL certificate verification)
        </label>
      </div>

      {/* Action Buttons */}
      <div className="flex items-center gap-2 pt-4">
        <button
          type="submit"
          className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition flex items-center justify-center gap-2"
        >
          <Save className="w-4 h-4" />
          {ButtonText.SAVE}
        </button>
        {registry?.id && (
          <button
            type="button"
            onClick={handleTest}
            disabled={testing}
            className="px-4 py-2 bg-white hover:bg-slate-100 text-slate-900 rounded-lg transition flex items-center gap-2 disabled:opacity-50"
          >
            <TestTube className={`w-4 h-4 ${testing ? "animate-pulse" : ""}`} />
            {ButtonText.TEST_CONNECTION}
          </button>
        )}
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 bg-white hover:bg-slate-100 text-slate-900 rounded-lg transition flex items-center gap-2"
        >
          <X className="w-4 h-4" />
          {ButtonText.CANCEL}
        </button>
      </div>
    </form>
  );
};
