/**
 * StripeKeysForm Component
 * Manages Stripe API key configuration with encryption
 */

"use client";

import { useState, useEffect } from "react";
import {
  CreditCard,
  Key,
  Eye,
  EyeOff,
  CheckCircle,
  AlertCircle,
  Trash2,
  Save,
  ExternalLink,
  Shield,
} from "lucide-react";

interface ExistingKeys {
  hasKeys: boolean;
  mode: "test" | "live" | null;
  configuredAt: string | null;
  maskedSecretKey: string | null;
  maskedWebhookSecret: string | null;
  publishableKey: string | null;
}

interface ValidationResult {
  valid: boolean;
  mode: "test" | "live" | null;
  message: string;
  accountName?: string;
  accountEmail?: string;
}

export default function StripeKeysForm() {
  // Input values
  const [secretKey, setSecretKey] = useState("");
  const [publishableKey, setPublishableKey] = useState("");
  const [webhookSecret, setWebhookSecret] = useState("");

  // Visibility toggles
  const [showSecretKey, setShowSecretKey] = useState(false);
  const [showWebhookSecret, setShowWebhookSecret] = useState(false);

  // State
  const [existingKeys, setExistingKeys] = useState<ExistingKeys | null>(null);
  const [validationResult, setValidationResult] =
    useState<ValidationResult | null>(null);
  const [loading, setLoading] = useState(true);
  const [validating, setValidating] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Track if keys are validated
  const [isValidated, setIsValidated] = useState(false);

  // Fetch existing keys on mount
  useEffect(() => {
    fetchExistingKeys();
  }, []);

  const fetchExistingKeys = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await fetch("/api/staff/settings/stripe-keys");

      if (response.ok) {
        const data = await response.json();
        setExistingKeys(data);

        // If keys exist, populate publishable key
        if (data.hasKeys && data.publishableKey) {
          setPublishableKey(data.publishableKey);
        }
      } else {
        const errorData = await response.json();
        setError(errorData.error || "Failed to fetch existing keys");
      }
    } catch (err) {
      console.error("Failed to fetch existing keys:", err);
      setError("Failed to fetch existing keys");
    } finally {
      setLoading(false);
    }
  };

  const handleValidate = async () => {
    // Reset previous validation
    setValidationResult(null);
    setError(null);
    setIsValidated(false);

    // Validation
    if (!secretKey.trim() || !publishableKey.trim()) {
      setError("Secret key and publishable key are required");
      return;
    }

    // Check key format
    if (!secretKey.startsWith("sk_")) {
      setError('Invalid secret key format. Must start with "sk_"');
      return;
    }

    if (!publishableKey.startsWith("pk_")) {
      setError('Invalid publishable key format. Must start with "pk_"');
      return;
    }

    try {
      setValidating(true);
      const response = await fetch("/api/staff/settings/stripe-keys/validate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          secretKey: secretKey.trim(),
          publishableKey: publishableKey.trim(),
          webhookSecret: webhookSecret.trim() || undefined,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        setValidationResult(data);
        setIsValidated(data.valid);
        if (!data.valid) {
          setError(data.message || "Keys validation failed");
        }
      } else {
        setError(data.error || "Validation request failed");
        setValidationResult({
          valid: false,
          mode: null,
          message: data.error || "Validation failed",
        });
      }
    } catch (err: any) {
      console.error("Validation error:", err);
      setError(err.message || "Failed to validate keys");
      setValidationResult({
        valid: false,
        mode: null,
        message: "Network error during validation",
      });
    } finally {
      setValidating(false);
    }
  };

  const handleSave = async () => {
    if (!isValidated) {
      setError("Please validate keys before saving");
      return;
    }

    if (!validationResult?.valid) {
      setError("Cannot save invalid keys");
      return;
    }

    try {
      setSaving(true);
      setError(null);

      const response = await fetch("/api/staff/settings/stripe-keys", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          secretKey: secretKey.trim(),
          publishableKey: publishableKey.trim(),
          webhookSecret: webhookSecret.trim() || undefined,
          mode: validationResult.mode,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        // Success - refresh existing keys
        alert("Stripe keys saved successfully!");
        setSecretKey("");
        setWebhookSecret("");
        setValidationResult(null);
        setIsValidated(false);
        await fetchExistingKeys();
      } else {
        setError(data.error || "Failed to save keys");
      }
    } catch (err: any) {
      console.error("Save error:", err);
      setError(err.message || "Failed to save keys");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (
      !confirm(
        "Are you sure you want to remove Stripe keys? This will disable payment processing.",
      )
    ) {
      return;
    }

    try {
      setSaving(true);
      setError(null);

      const response = await fetch("/api/staff/settings/stripe-keys", {
        method: "DELETE",
      });

      if (response.ok) {
        alert("Stripe keys removed successfully");
        setSecretKey("");
        setPublishableKey("");
        setWebhookSecret("");
        setValidationResult(null);
        setIsValidated(false);
        await fetchExistingKeys();
      } else {
        const data = await response.json();
        setError(data.error || "Failed to remove keys");
      }
    } catch (err: any) {
      console.error("Delete error:", err);
      setError(err.message || "Failed to remove keys");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="bg-white rounded-lg border border-gray-200 p-8">
        <div className="flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-green"></div>
          <span className="ml-3 text-gray-600">Loading...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Info Banner */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <div className="flex items-start gap-3">
          <Shield className="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" />
          <div>
            <h4 className="font-semibold text-blue-900 mb-1">
              Secure Encryption
            </h4>
            <p className="text-sm text-blue-800">
              All API keys are encrypted using AES-256-GCM encryption before
              storage. Only authorized administrators can configure Stripe
              settings.
            </p>
          </div>
        </div>
      </div>

      {/* Existing Keys Display */}
      {existingKeys?.hasKeys && (
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center gap-3 mb-4">
            <CreditCard className="w-6 h-6 text-brand-green" />
            <div>
              <h3 className="text-lg font-bold text-gray-900">
                Current Configuration
              </h3>
              <p className="text-sm text-gray-600">Active Stripe API keys</p>
            </div>
          </div>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Mode
                </label>
                <span
                  className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                    existingKeys.mode === "live"
                      ? "bg-green-100 text-green-800"
                      : "bg-yellow-100 text-yellow-800"
                  }`}
                >
                  {existingKeys.mode === "live"
                    ? "🔴 Live Mode"
                    : "🟡 Test Mode"}
                </span>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Configured
                </label>
                <p className="text-base text-gray-900">
                  {existingKeys.configuredAt
                    ? new Date(existingKeys.configuredAt).toLocaleDateString()
                    : "Unknown"}
                </p>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Secret Key
              </label>
              <code className="block text-sm bg-gray-100 px-3 py-2 rounded border border-gray-300">
                {existingKeys.maskedSecretKey || "••••••••"}
              </code>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Publishable Key
              </label>
              <code className="block text-sm bg-gray-100 px-3 py-2 rounded border border-gray-300">
                {existingKeys.publishableKey || "••••••••"}
              </code>
            </div>

            {existingKeys.maskedWebhookSecret && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Webhook Secret
                </label>
                <code className="block text-sm bg-gray-100 px-3 py-2 rounded border border-gray-300">
                  {existingKeys.maskedWebhookSecret}
                </code>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Configuration Form */}
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <div className="flex items-center gap-3 mb-6">
          <Key className="w-6 h-6 text-brand-green" />
          <div>
            <h3 className="text-lg font-bold text-gray-900">
              {existingKeys?.hasKeys ? "Update" : "Configure"} Stripe Keys
            </h3>
            <p className="text-sm text-gray-600">
              Enter your Stripe API credentials to enable payment processing
            </p>
          </div>
        </div>

        <div className="space-y-5">
          {/* Secret Key */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Secret Key <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type={showSecretKey ? "text" : "password"}
                value={secretKey}
                onChange={(e) => {
                  setSecretKey(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="sk_test_... or sk_live_..."
                className="w-full px-4 py-2 pr-12 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
              />
              <button
                type="button"
                onClick={() => setShowSecretKey(!showSecretKey)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
              >
                {showSecretKey ? (
                  <EyeOff className="w-5 h-5" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
              </button>
            </div>
            <p className="text-xs text-gray-500 mt-1">
              Starts with sk_test_ (test mode) or sk_live_ (live mode)
            </p>
          </div>

          {/* Publishable Key */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Publishable Key <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={publishableKey}
              onChange={(e) => {
                setPublishableKey(e.target.value);
                setValidationResult(null);
                setIsValidated(false);
              }}
              placeholder="pk_test_... or pk_live_..."
              className="w-full px-4 py-2 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
            />
            <p className="text-xs text-gray-500 mt-1">
              Starts with pk_test_ (test mode) or pk_live_ (live mode)
            </p>
          </div>

          {/* Webhook Secret */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Webhook Secret <span className="text-gray-500">(Optional)</span>
            </label>
            <div className="relative">
              <input
                type={showWebhookSecret ? "text" : "password"}
                value={webhookSecret}
                onChange={(e) => {
                  setWebhookSecret(e.target.value);
                  setValidationResult(null);
                  setIsValidated(false);
                }}
                placeholder="whsec_..."
                className="w-full px-4 py-2 pr-12 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-green focus:border-brand-green"
              />
              <button
                type="button"
                onClick={() => setShowWebhookSecret(!showWebhookSecret)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
              >
                {showWebhookSecret ? (
                  <EyeOff className="w-5 h-5" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
              </button>
            </div>
            <p className="text-xs text-gray-500 mt-1">
              Required for webhook verification. Starts with whsec_
            </p>
          </div>

          {/* Validation Result */}
          {validationResult && (
            <div
              className={`p-4 rounded-lg border-2 ${
                validationResult.valid
                  ? "bg-green-50 border-green-200"
                  : "bg-red-50 border-red-200"
              }`}
            >
              <div className="flex items-start gap-3">
                {validationResult.valid ? (
                  <CheckCircle className="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0" />
                ) : (
                  <AlertCircle className="w-5 h-5 text-red-600 mt-0.5 flex-shrink-0" />
                )}
                <div className="flex-1">
                  <p
                    className={`font-semibold ${
                      validationResult.valid ? "text-green-900" : "text-red-900"
                    }`}
                  >
                    {validationResult.valid
                      ? "Keys Valid"
                      : "Validation Failed"}
                  </p>
                  <p
                    className={`text-sm mt-1 ${
                      validationResult.valid ? "text-green-800" : "text-red-800"
                    }`}
                  >
                    {validationResult.message}
                  </p>
                  {validationResult.valid && validationResult.accountName && (
                    <div className="mt-2 text-sm text-green-800">
                      <p>
                        <strong>Account:</strong> {validationResult.accountName}
                      </p>
                      {validationResult.accountEmail && (
                        <p>
                          <strong>Email:</strong>{" "}
                          {validationResult.accountEmail}
                        </p>
                      )}
                      <p>
                        <strong>Mode:</strong>{" "}
                        <span
                          className={`font-semibold ${
                            validationResult.mode === "live"
                              ? "text-green-700"
                              : "text-yellow-700"
                          }`}
                        >
                          {validationResult.mode === "live" ? "Live" : "Test"}
                        </span>
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Error Display */}
          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">
              {error}
            </div>
          )}

          {/* Action Buttons */}
          <div className="flex items-center gap-3 pt-4">
            <button
              onClick={handleValidate}
              disabled={
                validating || !secretKey.trim() || !publishableKey.trim()
              }
              className="flex items-center gap-2 px-6 py-2.5 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Key className="w-4 h-4" />
              {validating ? "Validating..." : "Validate Keys"}
            </button>

            <button
              onClick={handleSave}
              disabled={saving || !isValidated || !validationResult?.valid}
              className="flex items-center gap-2 px-6 py-2.5 bg-brand-green text-white font-semibold rounded-lg hover:bg-green-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Save className="w-4 h-4" />
              {saving ? "Saving..." : "Save Keys"}
            </button>

            {existingKeys?.hasKeys && (
              <button
                onClick={handleDelete}
                disabled={saving}
                className="flex items-center gap-2 px-6 py-2.5 bg-red-600 text-white font-semibold rounded-lg hover:bg-red-700 transition-all disabled:opacity-50 disabled:cursor-not-allowed ml-auto"
              >
                <Trash2 className="w-4 h-4" />
                Remove Keys
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Help Section */}
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-6">
        <h4 className="font-semibold text-gray-900 mb-3">
          How to Get Your Stripe API Keys
        </h4>
        <ol className="list-decimal list-inside space-y-2 text-sm text-gray-700 mb-4">
          <li>Log in to your Stripe Dashboard</li>
          <li>Click on "Developers" in the top menu</li>
          <li>Select "API keys" from the sidebar</li>
          <li>Copy the "Secret key" and "Publishable key"</li>
          <li>For webhooks, go to "Webhooks" and copy the "Signing secret"</li>
        </ol>
        <a
          href="https://dashboard.stripe.com/apikeys"
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-2 text-brand-green hover:text-green-700 font-medium"
        >
          <ExternalLink className="w-4 h-4" />
          Open Stripe Dashboard
        </a>
      </div>
    </div>
  );
}
