/**
 * Cluster Configuration Form Component
 * For adding and editing cluster configurations
 */
import React, { useState, useEffect } from "react";
import { Server, Key, FileText } from "lucide-react";
import type { ClusterConfig } from "@/core/types";
import { ValidationErrors } from "@/shared/utils";
import { ButtonText, LabelText } from "@/shared/constants";

interface ClusterFormProps {
  cluster?: ClusterConfig;
  onSave: (data: Omit<ClusterConfig, "id" | "createdAt" | "updatedAt">) => void;
  onCancel: () => void;
}

export const ClusterForm: React.FC<ClusterFormProps> = ({
  cluster,
  onSave,
  onCancel,
}) => {
  const [formData, setFormData] = useState({
    name: cluster?.name ?? "",
    host: cluster?.host ?? "",
    caData: cluster?.caData ?? "",
    certData: cluster?.certData ?? "",
    keyData: cluster?.keyData ?? "",
    token: cluster?.token ?? "",
    description: cluster?.description ?? "",
  });

  // 新证书输入（编辑模式）
  const [newCaData, setNewCaData] = useState<string>("");
  const [newCertData, setNewCertData] = useState<string>("");
  const [newKeyData, setNewKeyData] = useState<string>("");

  const [errors, setErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    if (cluster) {
      setFormData({
        name: cluster.name ?? "",
        host: cluster.host ?? "",
        caData: cluster.caData ?? "",
        certData: cluster.certData ?? "",
        keyData: cluster.keyData ?? "",
        token: cluster.token ?? "",
        description: cluster.description ?? "",
      });
    }
  }, [cluster]);

  const handleChange = (
    field: keyof typeof formData,
    value: string
  ) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    // Clear field error
    if (errors[field]) {
      setErrors((prev) => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  const validate = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = ValidationErrors.REQUIRED_FIELD("Cluster name");
    }

    if (!formData.host.trim()) {
      newErrors.host = ValidationErrors.REQUIRED_FIELD("API Server URL");
    } else if (!/^https?:\/\/.+/.test(formData.host.trim())) {
      newErrors.host = ValidationErrors.INVALID_URL;
    }

    // 创建模式：需要 token 或完整证书三件套
    if (!cluster) {
      const hasToken = Boolean(formData.token.trim());
      const hasCertAuth = Boolean(
        formData.caData.trim() &&
        formData.certData.trim() &&
        formData.keyData.trim()
      );
      if (!hasToken && !hasCertAuth && !formData.caData.trim()) {
        newErrors.caData = ValidationErrors.REQUIRED_FIELD("CA Certificate");
      }
      if (!hasToken && !hasCertAuth && !formData.certData.trim()) {
        newErrors.certData = ValidationErrors.REQUIRED_FIELD("Client Certificate");
      }
      if (!hasToken && !hasCertAuth && !formData.keyData.trim()) {
        newErrors.keyData = ValidationErrors.REQUIRED_FIELD("Client Key");
      }
    }
    // 编辑模式：证书可选（留空保持不变）

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (validate()) {
      // 准备提交数据 - 使用 OpenAPI 生成的 camelCase 字段名
      const submitData: Record<string, string> = {
        name: formData.name.trim(),
        host: formData.host.trim(),
      };

      // 只添加非空的 description
      if (formData.description.trim()) {
        submitData.description = formData.description.trim();
      }

      if (cluster) {
        // 编辑模式：只发送用户输入的新值（使用 camelCase）
        if (newCaData.trim()) submitData.caData = newCaData.trim();
        if (newCertData.trim()) submitData.certData = newCertData.trim();
        if (newKeyData.trim()) submitData.keyData = newKeyData.trim();
        if (formData.token.trim() && formData.token.trim() !== (cluster.token ?? "")) {
          submitData.token = formData.token.trim();
        }
      } else {
        // 创建模式：发送所有必填字段（使用 camelCase）
        submitData.caData = formData.caData.trim();
        submitData.certData = formData.certData.trim();
        submitData.keyData = formData.keyData.trim();
        if (formData.token?.trim()) submitData.token = formData.token.trim();
      }

      onSave(submitData);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4 sm:space-y-5">
      {/* Cluster Name */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1.5 flex items-center gap-2">
          <Server className="w-4 h-4 text-blue-400" />
          {LabelText.NAME} <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          value={formData.name}
          onChange={(e) => handleChange("name", e.target.value)}
          className={`w-full bg-white border ${
            errors.name ? "border-red-500" : "border-slate-300"
          } rounded-lg p-2.5 sm:p-3 text-sm sm:text-base text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none`}
          placeholder="e.g., Production Cluster"
        />
        {errors.name && (
          <p className="mt-1 text-sm text-red-400">{errors.name}</p>
        )}
      </div>

      {/* API Server URL */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1.5 flex items-center gap-2">
          <Server className="w-4 h-4 text-blue-400" />
          API Server URL <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          value={formData.host}
          onChange={(e) => handleChange("host", e.target.value)}
          className={`w-full bg-white border ${
            errors.host ? "border-red-500" : "border-slate-300"
          } rounded-lg p-2.5 sm:p-3 text-sm sm:text-base text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none`}
          placeholder="e.g., https://kubernetes.example.com:6443"
        />
        {errors.host && (
          <p className="mt-1 text-sm text-red-400">{errors.host}</p>
        )}
        <p className="mt-1 text-xs text-slate-500">
          Kubernetes API Server address (usually HTTPS protocol)
        </p>
      </div>

      {/* CA Certificate */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1.5 flex items-center gap-2">
          <Key className="w-4 h-4 text-green-400" />
          CA Certificate (Base64) {!cluster && <span className="text-red-400">*</span>}
        </label>
        {cluster ? (
          // 编辑模式：显示状态和新输入
          <>
            <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 text-xs">{formData.caData}</span>
              {cluster.hasCaData && (
                <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>
            <textarea
              value={newCaData}
              onChange={(e) => setNewCaData(e.target.value)}
              rows={3}
              className="w-full bg-white border border-slate-300 rounded-lg p-2.5 sm:p-3 text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono text-xs sm:text-sm resize-none"
              placeholder="粘贴新的 CA 证书以覆盖（留空保持不变）"
            />
            <p className="mt-1 text-xs text-slate-500">
              💡 输入新证书以覆盖，留空则保持原证书不变
            </p>
          </>
        ) : (
          // 创建模式：必填
          <>
            <textarea
              value={formData.caData}
              onChange={(e) => handleChange("caData", e.target.value)}
              rows={4}
              className={`w-full bg-white border ${
                errors.caData ? "border-red-500" : "border-slate-300"
              } rounded-lg p-2.5 sm:p-3 text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono text-xs sm:text-sm resize-none`}
              placeholder="LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0t..."
            />
            {errors.caData && (
              <p className="mt-1 text-sm text-red-400">{errors.caData}</p>
            )}
            <p className="mt-1 text-xs text-slate-500">
              Cluster CA certificate in base64 format (certificate-authority-data)
            </p>
          </>
        )}
      </div>

      {/* Client Certificate */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1.5 flex items-center gap-2">
          <Key className="w-4 h-4 text-yellow-400" />
          Client Certificate (Base64) {!cluster && <span className="text-red-400">*</span>}
        </label>
        {cluster ? (
          // 编辑模式
          <>
            <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 text-xs">{formData.certData}</span>
              {cluster.hasCertData && (
                <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>
            <textarea
              value={newCertData}
              onChange={(e) => setNewCertData(e.target.value)}
              rows={3}
              className="w-full bg-white border border-slate-300 rounded-lg p-2.5 sm:p-3 text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono text-xs sm:text-sm resize-none"
              placeholder="粘贴新的客户端证书以覆盖（留空保持不变）"
            />
            <p className="mt-1 text-xs text-slate-500">
              💡 输入新证书以覆盖，留空则保持原证书不变
            </p>
          </>
        ) : (
          <>
            <textarea
              value={formData.certData}
              onChange={(e) => handleChange("certData", e.target.value)}
              rows={4}
              className={`w-full bg-white border ${
                errors.certData ? "border-red-500" : "border-slate-300"
              } rounded-lg p-2.5 sm:p-3 text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono text-xs sm:text-sm resize-none`}
              placeholder="LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0t..."
            />
            {errors.certData && (
              <p className="mt-1 text-sm text-red-400">{errors.certData}</p>
            )}
            <p className="mt-1 text-xs text-slate-500">
              Client certificate in base64 format (client-certificate-data)
            </p>
          </>
        )}
      </div>

      {/* Client Key */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1.5 flex items-center gap-2">
          <Key className="w-4 h-4 text-red-400" />
          Client Key (Base64) {!cluster && <span className="text-red-400">*</span>}
        </label>
        {cluster ? (
          // 编辑模式
          <>
            <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 text-xs">{formData.keyData}</span>
              {cluster.hasKeyData && (
                <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>
            <textarea
              value={newKeyData}
              onChange={(e) => setNewKeyData(e.target.value)}
              rows={3}
              className="w-full bg-white border border-slate-300 rounded-lg p-2.5 sm:p-3 text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono text-xs sm:text-sm resize-none"
              placeholder="粘贴新的客户端密钥以覆盖（留空保持不变）"
            />
            <p className="mt-1 text-xs text-slate-500">
              💡 输入新密钥以覆盖，留空则保持原密钥不变
            </p>
          </>
        ) : (
          <>
            <textarea
              value={formData.keyData}
              onChange={(e) => handleChange("keyData", e.target.value)}
              rows={4}
              className={`w-full bg-white border ${
                errors.keyData ? "border-red-500" : "border-slate-300"
              } rounded-lg p-2.5 sm:p-3 text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono text-xs sm:text-sm resize-none`}
              placeholder="LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBL..."
            />
            {errors.keyData && (
              <p className="mt-1 text-sm text-red-400">{errors.keyData}</p>
            )}
            <p className="mt-1 text-xs text-slate-500">
              Client private key in base64 format (client-key-data)
            </p>
          </>
        )}
      </div>

      {/* Bearer Token */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1.5 flex items-center gap-2">
          <Key className="w-4 h-4 text-blue-600" />
          Bearer Token {!cluster && <span className="text-slate-400 text-xs">(optional alternative to client certs)</span>}
        </label>
        <textarea
          value={formData.token}
          onChange={(e) => handleChange("token", e.target.value)}
          rows={3}
          className="w-full bg-white border border-slate-300 rounded-lg p-2.5 sm:p-3 text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none font-mono text-xs sm:text-sm resize-none"
          placeholder="Paste service-account bearer token"
        />
      </div>

      {/* Description */}
      <div>
        <label className="block text-sm font-medium text-slate-700 mb-1.5 flex items-center gap-2">
          <FileText className="w-4 h-4 text-slate-500" />
          {LabelText.DESCRIPTION} (Optional)
        </label>
        <textarea
          value={formData.description}
          onChange={(e) => handleChange("description", e.target.value)}
          rows={2}
          className="w-full bg-white border border-slate-300 rounded-lg p-2.5 sm:p-3 text-sm sm:text-base text-slate-900 placeholder-gray-500 focus:ring-2 focus:ring-blue-500 focus:outline-none resize-none"
          placeholder="Cluster description (e.g., purpose, environment)"
        />
      </div>

      {/* Action Buttons */}
      <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 pt-3 sm:pt-4 border-t border-slate-200">
        <button
          type="button"
          onClick={onCancel}
          className="flex-1 px-4 py-2.5 bg-white hover:bg-slate-100 text-slate-900 rounded-lg transition text-sm sm:text-base"
        >
          {ButtonText.CANCEL}
        </button>
        <button
          type="submit"
          className="flex-1 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition text-sm sm:text-base"
        >
          {cluster ? ButtonText.SAVE : `${ButtonText.ADD} ${LabelText.CLUSTER}`}
        </button>
      </div>
    </form>
  );
};
