import React, { useEffect, useState } from 'react';
import { CreditCard, Save, Info, Eye, EyeOff, Lock, Key, Globe } from 'lucide-react';
import { toast } from 'react-toastify';
import systemSettingsService, {
  StripeSettingsResponse,
  UpdateStripeSettingsRequest,
} from '../../features/system/services/systemSettingsService';
import Loading from '../../shared/components/Loading';

const StripeSettingsPage: React.FC = () => {
  const [settings, setSettings] = useState<StripeSettingsResponse['data'] | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const [formData, setFormData] = useState<UpdateStripeSettingsRequest>({
    stripe_secret_key: '',
    stripe_publishable_key: '',
    stripe_webhook_secret: '',
  });

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

  useEffect(() => {
    loadStripeSettings();
  }, []);

  const loadStripeSettings = async () => {
    try {
      setLoading(true);
      const response = await systemSettingsService.getStripeSettings();
      setSettings(response.data);
      
      
      setFormData({
        stripe_secret_key: '',
        stripe_publishable_key: response.data.stripe_publishable_key || '',
        stripe_webhook_secret: '',
      });
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to load Stripe settings');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    try {
      setSaving(true);

      
      const updateData: UpdateStripeSettingsRequest = {};
      
      if (formData.stripe_secret_key && formData.stripe_secret_key.trim()) {
        updateData.stripe_secret_key = formData.stripe_secret_key.trim();
      }
      
      if (formData.stripe_publishable_key && formData.stripe_publishable_key.trim()) {
        updateData.stripe_publishable_key = formData.stripe_publishable_key.trim();
      }
      
      if (formData.stripe_webhook_secret && formData.stripe_webhook_secret.trim()) {
        updateData.stripe_webhook_secret = formData.stripe_webhook_secret.trim();
      }

      await systemSettingsService.updateStripeSettings(updateData);
      await loadStripeSettings();
      
      
      setFormData({
        ...formData,
        stripe_secret_key: '',
        stripe_webhook_secret: '',
      });
      
      toast.success('Stripe settings updated successfully');
    } catch (error: unknown) {
      toast.error(
        getUserFriendlyError(error) || 
        getUserFriendlyError(error) || 
        'Failed to update Stripe settings'
      );
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return <Loading fullScreen={false} text="Loading Stripe settings..." />;
  }

  return (
    <div className="space-y-10 pb-8 animate-fade-in">
      {}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6 pb-6 border-b border-gray-200/60">
        <div className="space-y-3">
          <div className="flex items-center gap-3">
            <div className="p-2.5 rounded-lg bg-gradient-to-br from-indigo-500/10 to-purple-500/5 border border-indigo-200/20 shadow-sm">
              <CreditCard className="w-6 h-6 text-indigo-600" />
            </div>
            <h1 className="enterprise-section-title">Stripe Payment Settings</h1>
          </div>
          <p className="enterprise-section-subtitle max-w-2xl text-gray-600">
            Configure your Stripe account credentials to enable card payments. 
            All payments will be processed through your Stripe account.
          </p>
        </div>

        <button
          type="button"
          onClick={handleSave}
          disabled={saving}
          className="btn-enterprise-primary inline-flex items-center gap-2 whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <Save className={`w-4 h-4 ${saving ? 'animate-pulse' : ''}`} />
          {saving ? 'Saving...' : 'Save Changes'}
        </button>
      </div>

      {}
      <div className="enterprise-card flex gap-5 p-6 bg-gradient-to-br from-blue-50/50 to-indigo-50/30 border-blue-100/60">
        <div className="mt-0.5 flex-shrink-0">
          <div className="p-2.5 rounded-lg bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-200/40">
            <Info className="w-5 h-5 text-blue-600" />
          </div>
        </div>
        <div className="space-y-2.5 flex-1">
          <p className="font-semibold text-gray-900 text-base">
            How Stripe payments work
          </p>
          <p className="text-sm text-gray-700 leading-relaxed">
            Stripe handles all card payments securely. You need to provide your Stripe API keys 
            from your Stripe Dashboard. The secret key is used to process payments on the backend, 
            while the publishable key is used in the frontend payment forms. The webhook secret 
            is required to verify webhook events from Stripe.
          </p>
          <div className="text-xs text-gray-600 pt-2 border-t border-gray-200/60 space-y-2">
            <p>
              <strong>Note:</strong> Leave fields empty to keep existing values. Only enter new values 
              when you want to update them.
            </p>
            <div className="bg-blue-50 border border-blue-200 rounded p-3 mt-2">
              <p className="font-semibold text-blue-900 mb-2">📝 How to Get Stripe Test Keys:</p>
              <ol className="list-decimal list-inside space-y-1 text-blue-800">
                <li>Go to <a href="https://dashboard.stripe.com/test/apikeys" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">Stripe Dashboard</a></li>
                <li>Make sure you're in <strong>Test mode</strong> (toggle in top right)</li>
                <li>Navigate to <a href="https://dashboard.stripe.com/test/apikeys" target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:underline">API Keys</a></li>
                <li>Copy your <strong>Publishable key</strong> (starts with <code className="bg-blue-100 px-1 rounded">pk_test_</code>)</li>
                <li>Click "Reveal test key" and copy your <strong>Secret key</strong> (starts with <code className="bg-blue-100 px-1 rounded">sk_test_</code>)</li>
                <li>Paste them in the fields below and click "Save Changes"</li>
              </ol>
              <p className="mt-2 text-blue-800">
                <strong>💳 Test Card Numbers:</strong> Use <code className="bg-blue-100 px-1 rounded">4242 4242 4242 4242</code> with any future expiry date, any CVC, and any ZIP code.
              </p>
            </div>
          </div>
          {settings?.updated_at && (
            <div className="pt-2 border-t border-gray-200/60">
              <p className="text-xs text-gray-500 font-medium">
                Last updated on{' '}
                <span className="text-gray-700">
                  {new Date(settings.updated_at).toLocaleString(undefined, {
                    dateStyle: 'medium',
                    timeStyle: 'short',
                  })}
                </span>
                {settings.updated_by && (
                  <>
                    {' '}by <span className="text-gray-700 font-semibold">{settings.updated_by}</span>
                  </>
                )}
              </p>
            </div>
          )}
        </div>
      </div>

      {}
      <div className="enterprise-card p-6 space-y-6">
        <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between pb-4 border-b border-gray-200/60">
          <div className="flex items-start gap-3">
            <div className="p-2 rounded-lg bg-gradient-to-br from-purple-500/10 to-pink-500/10 border border-purple-200/40 mt-0.5">
              <Key className="w-5 h-5 text-purple-600" />
            </div>
            <div className="space-y-1.5">
              <p className="font-bold text-gray-900 text-lg">
                Stripe API Keys
              </p>
              <p className="text-sm text-gray-600 leading-relaxed max-w-xl">
                Get these keys from your{' '}
                <a
                  href="https://dashboard.stripe.com/test/apikeys"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-indigo-600 hover:text-indigo-700 underline font-medium"
                >
                  Stripe Dashboard (Test Mode)
                </a>
                {' '}or{' '}
                <a
                  href="https://dashboard.stripe.com/test/apikeys"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-indigo-600 hover:text-indigo-700 underline font-medium"
                >
                  Live Mode
                </a>
              </p>
            </div>
          </div>
        </div>

        <div className="space-y-6">
          {}
          <div className="space-y-3">
            <label className="block text-sm font-semibold text-gray-900 tracking-wide">
              <Lock className="w-4 h-4 inline mr-1" />
              Stripe Secret Key
              <span className="text-red-500 ml-1">*</span>
            </label>
            <div className="relative">
              <input
                type={showSecretKey ? 'text' : 'password'}
                value={formData.stripe_secret_key}
                onChange={(e) =>
                  setFormData({ ...formData, stripe_secret_key: e.target.value })
                }
                placeholder={
                  settings?.has_secret_key
                    ? `Current: ${settings.stripe_secret_key_masked || '****'}`
                    : 'sk_test_... or sk_live_...'
                }
                className="enterprise-input text-sm pr-10"
              />
              <button
                type="button"
                onClick={() => setShowSecretKey(!showSecretKey)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
              >
                {showSecretKey ? (
                  <EyeOff className="w-4 h-4" />
                ) : (
                  <Eye className="w-4 h-4" />
                )}
              </button>
            </div>
            <p className="text-xs text-gray-500 leading-relaxed">
              Used to process payments on the backend. Must start with{' '}
              <code className="px-1.5 py-0.5 bg-gray-100 rounded text-gray-700">sk_</code>
              {settings?.has_secret_key && (
                <span className="text-green-600 font-medium ml-2">
                  ✓ Currently configured
                </span>
              )}
            </p>
          </div>

          {}
          <div className="space-y-3">
            <label className="block text-sm font-semibold text-gray-900 tracking-wide">
              <Globe className="w-4 h-4 inline mr-1" />
              Stripe Publishable Key
              <span className="text-red-500 ml-1">*</span>
            </label>
            <input
              type="text"
              value={formData.stripe_publishable_key}
              onChange={(e) =>
                setFormData({
                  ...formData,
                  stripe_publishable_key: e.target.value,
                })
              }
              placeholder="pk_test_... or pk_live_..."
              className="enterprise-input text-sm"
            />
            <p className="text-xs text-gray-500 leading-relaxed">
              Used in frontend payment forms. Must start with{' '}
              <code className="px-1.5 py-0.5 bg-gray-100 rounded text-gray-700">pk_</code>
              {settings?.has_publishable_key && (
                <span className="text-green-600 font-medium ml-2">
                  ✓ Currently configured
                </span>
              )}
            </p>
          </div>

          {}
          <div className="space-y-3">
            <label className="block text-sm font-semibold text-gray-900 tracking-wide">
              <Lock className="w-4 h-4 inline mr-1" />
              Stripe Webhook Secret
            </label>
            <div className="relative">
              <input
                type={showWebhookSecret ? 'text' : 'password'}
                value={formData.stripe_webhook_secret}
                onChange={(e) =>
                  setFormData({
                    ...formData,
                    stripe_webhook_secret: e.target.value,
                  })
                }
                placeholder={
                  settings?.has_webhook_secret
                    ? `Current: ${settings.stripe_webhook_secret_masked || '****'}`
                    : 'whsec_...'
                }
                className="enterprise-input text-sm pr-10"
              />
              <button
                type="button"
                onClick={() => setShowWebhookSecret(!showWebhookSecret)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
              >
                {showWebhookSecret ? (
                  <EyeOff className="w-4 h-4" />
                ) : (
                  <Eye className="w-4 h-4" />
                )}
              </button>
            </div>
            <p className="text-xs text-gray-500 leading-relaxed">
              Used to verify webhook events from Stripe. Must start with{' '}
              <code className="px-1.5 py-0.5 bg-gray-100 rounded text-gray-700">whsec_</code>
              {settings?.has_webhook_secret && (
                <span className="text-green-600 font-medium ml-2">
                  ✓ Currently configured
                </span>
              )}
            </p>
          </div>
        </div>

        {}
        <div className="mt-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
          <p className="text-sm font-semibold text-yellow-900 mb-2">
            Webhook Endpoint URL
          </p>
          <p className="text-sm text-yellow-800 mb-2">
            Configure this URL in your{' '}
            <a
              href="https://dashboard.stripe.com/webhooks"
              target="_blank"
              rel="noopener noreferrer"
              className="underline font-medium"
            >
              Stripe Webhooks Dashboard
            </a>
            :
          </p>
          <code className="block text-xs bg-yellow-100 px-3 py-2 rounded text-yellow-900 break-all">
            {window.location.origin}/api/payments/stripe/webhook
          </code>
          <p className="text-xs text-yellow-700 mt-2">
            Make sure to subscribe to <code className="px-1 bg-yellow-100 rounded">payment_intent.succeeded</code> and{' '}
            <code className="px-1 bg-yellow-100 rounded">payment_intent.payment_failed</code> events.
          </p>
        </div>
      </div>
    </div>
  );
};

export default StripeSettingsPage;

