import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Input } from '../../components/ui/input';
import { Label } from '../../components/ui/label';
import { AlertCircle, CheckCircle, Settings as SettingsIcon, RefreshCw, Zap, Edit, Save, X, Copy, Eye, EyeOff, ExternalLink } from 'lucide-react';
import api from '../../utils/api';
import { toast } from 'sonner';

export default function AdminSettings() {
  const [stripeStatus, setStripeStatus] = useState(null);
  const [loadingStatus, setLoadingStatus] = useState(true);
  const [testing, setTesting] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [saving, setSaving] = useState(false);

  // Form state
  const [formData, setFormData] = useState({
    publishable_key: '',
    secret_key: '',
    webhook_secret: ''
  });

  // Show/hide sensitive values
  const [showPublishableKey, setShowPublishableKey] = useState(false);
  const [showSecretKey, setShowSecretKey] = useState(false);
  const [showWebhookSecret, setShowWebhookSecret] = useState(false);

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

  const fetchStripeStatus = async () => {
    setLoadingStatus(true);
    try {
      const response = await api.get('/admin/settings/stripe/status');
      setStripeStatus(response.data);
    } catch (error) {
      console.error('Failed to fetch Stripe status:', error);
      toast.error('Failed to load Stripe status');
    } finally {
      setLoadingStatus(false);
    }
  };

  const handleTestConnection = async () => {
    setTesting(true);
    try {
      const response = await api.post('/admin/settings/stripe/test-connection');
      toast.success(response.data.message);
    } catch (error) {
      const message = error.response?.data?.detail || 'Connection test failed';
      toast.error(message);
    } finally {
      setTesting(false);
    }
  };

  const handleEditClick = () => {
    setIsEditing(true);
    setFormData({
      publishable_key: '',
      secret_key: '',
      webhook_secret: ''
    });
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setFormData({
      publishable_key: '',
      secret_key: '',
      webhook_secret: ''
    });
    setShowPublishableKey(false);
    setShowSecretKey(false);
    setShowWebhookSecret(false);
  };

  const handleSave = async () => {
    // Validate inputs
    if (!formData.publishable_key || !formData.secret_key || !formData.webhook_secret) {
      toast.error('All three keys are required: Publishable Key, Secret Key, and Webhook Secret');
      return;
    }

    if (!formData.publishable_key.startsWith('pk_test_') && !formData.publishable_key.startsWith('pk_live_')) {
      toast.error('Invalid Publishable Key format. Must start with pk_test_ or pk_live_');
      return;
    }

    if (!formData.secret_key.startsWith('sk_test_') && !formData.secret_key.startsWith('sk_live_')) {
      toast.error('Invalid Secret Key format. Must start with sk_test_ or sk_live_');
      return;
    }

    if (!formData.webhook_secret.startsWith('whsec_')) {
      toast.error('Invalid Webhook Secret format. Must start with whsec_');
      return;
    }

    // Check environment consistency
    const pkIsLive = formData.publishable_key.startsWith('pk_live_');
    const skIsLive = formData.secret_key.startsWith('sk_live_');
    if (pkIsLive !== skIsLive) {
      toast.error('Publishable Key and Secret Key must be from the same environment (both test or both live)');
      return;
    }

    setSaving(true);
    try {
      await api.put('/admin/settings/stripe', formData);
      toast.success('Stripe settings updated successfully');
      setIsEditing(false);
      setFormData({
        publishable_key: '',
        secret_key: '',
        webhook_secret: ''
      });
      setShowPublishableKey(false);
      setShowSecretKey(false);
      setShowWebhookSecret(false);
      // Refresh status
      await fetchStripeStatus();
    } catch (error) {
      const message = error.response?.data?.detail || 'Failed to update Stripe settings';
      toast.error(message);
    } finally {
      setSaving(false);
    }
  };

  const copyToClipboard = (text, label) => {
    navigator.clipboard.writeText(text);
    toast.success(`${label} copied to clipboard`);
  };

  if (loadingStatus) {
    return (
      <div className="container mx-auto p-6">
        <div className="flex items-center justify-center py-12">
          <RefreshCw className="h-8 w-8 animate-spin text-brand-purple" />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stripe Integration Card */}
      <Card className="border-2 border-[var(--lavender-200)] shadow-sm">
        <CardHeader className="bg-gradient-to-r from-[var(--lavender-100)] to-white border-b-2 border-[var(--lavender-200)]">
          <div className="flex justify-between items-start">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Zap className="h-5 w-5 text-brand-purple" />
                Stripe Integration
              </CardTitle>
              <CardDescription>
                Payment processing and subscription management
              </CardDescription>
            </div>
            {!isEditing && (
              <Button
                onClick={handleEditClick}
                variant="outline"
                className="border-2 border-brand-purple text-brand-purple hover:bg-[#f1eef9] rounded-full"
              >
                <Edit className="h-4 w-4 mr-2" />
                Edit Settings
              </Button>
            )}
          </div>
        </CardHeader>

        <CardContent className="pt-6 space-y-6">
          {isEditing ? (
            /* Edit Mode */
            <div className="space-y-6">
              {/* Publishable Key Input */}
              <div className="space-y-2">
                <Label htmlFor="publishable_key">Stripe Publishable Key</Label>
                <div className="relative">
                  <Input
                    id="publishable_key"
                    type={showPublishableKey ? 'text' : 'password'}
                    value={formData.publishable_key}
                    onChange={(e) => setFormData({ ...formData, publishable_key: e.target.value })}
                    placeholder="pk_test_... or pk_live_..."
                    className="pr-10"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPublishableKey(!showPublishableKey)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                  >
                    {showPublishableKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                <p className="text-xs text-gray-500">
                  Get this from your Stripe Dashboard → Developers → API keys (Publishable key)
                </p>
              </div>

              {/* Secret Key Input */}
              <div className="space-y-2">
                <Label htmlFor="secret_key">Stripe Secret Key</Label>
                <div className="relative">
                  <Input
                    id="secret_key"
                    type={showSecretKey ? 'text' : 'password'}
                    value={formData.secret_key}
                    onChange={(e) => setFormData({ ...formData, secret_key: e.target.value })}
                    placeholder="sk_test_... or sk_live_..."
                    className="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="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                <p className="text-xs text-gray-500">
                  Get this from your Stripe Dashboard → Developers → API keys (Secret key)
                </p>
              </div>

              {/* Webhook Secret Input */}
              <div className="space-y-2">
                <Label htmlFor="webhook_secret">Stripe Webhook Secret</Label>
                <div className="relative">
                  <Input
                    id="webhook_secret"
                    type={showWebhookSecret ? 'text' : 'password'}
                    value={formData.webhook_secret}
                    onChange={(e) => setFormData({ ...formData, webhook_secret: e.target.value })}
                    placeholder="whsec_..."
                    className="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="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                <p className="text-xs text-gray-500">
                  Get this from your Stripe Dashboard → Developers → Webhooks → Add endpoint
                </p>
              </div>

              {/* Action Buttons */}
              <div className="flex justify-end gap-3 pt-4 border-t-2 border-gray-100">
                <Button
                  onClick={handleCancelEdit}
                  variant="outline"
                  className="border-2 border-gray-300 rounded-full"
                  disabled={saving}
                >
                  <X className="h-4 w-4 mr-2" />
                  Cancel
                </Button>
                <Button
                  onClick={handleSave}
                  disabled={saving}
                  className="bg-brand-purple hover:bg-[var(--purple-dark)] text-white rounded-full"
                >
                  {saving ? (
                    <>
                      <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4 mr-2" />
                      Save Settings
                    </>
                  )}
                </Button>
              </div>
            </div>
          ) : (
            /* View Mode */
            <>
              {/* Status Display */}
              <div className="space-y-4">
                <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <p className="font-semibold text-gray-900">Configuration Status</p>
                    <p className="text-sm text-gray-600">Credentials stored in database (encrypted)</p>
                  </div>
                  <div className="flex items-center gap-2">
                    {stripeStatus?.configured ? (
                      <>
                        <CheckCircle className="h-5 w-5 text-green-600" />
                        <span className="text-green-600 font-semibold">Configured</span>
                      </>
                    ) : (
                      <>
                        <AlertCircle className="h-5 w-5 text-amber-600" />
                        <span className="text-amber-600 font-semibold">Not Configured</span>
                      </>
                    )}
                  </div>
                </div>

                {stripeStatus?.configured && (
                  <>
                    <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                      <div>
                        <p className="font-semibold text-gray-900">Environment</p>
                        <p className="text-sm text-gray-600">Detected from key prefixes</p>
                      </div>
                      <span className={`px-3 py-1 rounded-full text-sm font-semibold ${
                        stripeStatus.environment === 'live'
                          ? 'bg-green-100 text-green-800 border-2 border-green-300'
                          : 'bg-blue-100 text-blue-800 border-2 border-blue-300'
                      }`}>
                        {stripeStatus.environment === 'live' ? 'Live' : 'Test'}
                      </span>
                    </div>

                    <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                      <div>
                        <p className="font-semibold text-gray-900">Publishable Key</p>
                        <p className="text-sm text-gray-600 font-mono">
                          {stripeStatus.publishable_key_prefix}...
                        </p>
                      </div>
                      {stripeStatus.publishable_key_set ? (
                        <CheckCircle className="h-5 w-5 text-green-600" />
                      ) : (
                        <AlertCircle className="h-5 w-5 text-amber-600" />
                      )}
                    </div>

                    <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                      <div>
                        <p className="font-semibold text-gray-900">Secret Key</p>
                        <p className="text-sm text-gray-600 font-mono">
                          {stripeStatus.secret_key_prefix}...
                        </p>
                      </div>
                      <CheckCircle className="h-5 w-5 text-green-600" />
                    </div>

                    <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                      <div>
                        <p className="font-semibold text-gray-900">Webhook Secret</p>
                        <p className="text-sm text-gray-600">Webhook endpoint configuration</p>
                      </div>
                      {stripeStatus.webhook_secret_set ? (
                        <div className="flex items-center gap-2">
                          <CheckCircle className="h-5 w-5 text-green-600" />
                          <span className="text-green-600 font-semibold text-sm">Set</span>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2">
                          <AlertCircle className="h-5 w-5 text-amber-600" />
                          <span className="text-amber-600 font-semibold text-sm">Not Set</span>
                        </div>
                      )}
                    </div>

                    {/* Webhook URL */}
                    <div className="p-4 bg-blue-50 border-2 border-blue-200 rounded-lg">
                      <div className="flex items-start justify-between gap-2">
                        <div className="flex-1">
                          <p className="font-semibold text-blue-900 mb-2 flex items-center gap-2">
                            <ExternalLink className="h-4 w-4" />
                            Webhook URL
                          </p>
                          <p className="text-sm text-blue-700 mb-2">
                            Configure this webhook endpoint in your Stripe Dashboard:
                          </p>
                          <div className="bg-white p-2 rounded border border-blue-300 font-mono text-sm break-all">
                            {stripeStatus.webhook_url}
                          </div>
                        </div>
                        <Button
                          onClick={() => copyToClipboard(stripeStatus.webhook_url, 'Webhook URL')}
                          variant="outline"
                          size="sm"
                          className="border-blue-300 text-blue-700 hover:bg-blue-100"
                        >
                          <Copy className="h-4 w-4" />
                        </Button>
                      </div>
                      <div className="mt-3 text-xs text-blue-600">
                        <p className="font-semibold mb-1">Webhook Events to Configure:</p>
                        <div className="space-y-2">
                          <div>
                            <p className="font-medium text-blue-700">✅ Required (Configure in Stripe):</p>
                            <ul className="list-disc list-inside ml-2">
                              <li>checkout.session.completed - Handles subscriptions & donations</li>
                            </ul>
                          </div>
                          <div className="opacity-80">
                            <p className="font-medium text-blue-700">🔔 Automatically Triggered:</p>
                            <ul className="list-disc list-inside ml-2 text-xs">
                              <li>payment_intent.created</li>
                              <li>payment_intent.succeeded</li>
                              <li>charge.succeeded</li>
                              <li>charge.updated</li>
                            </ul>
                            <p className="text-xs italic mt-1">These fire automatically with checkout.session.completed</p>
                          </div>
                          <div className="opacity-70">
                            <p className="font-medium text-blue-700">🔄 Coming Soon (Recurring Subscriptions):</p>
                            <ul className="list-disc list-inside ml-2">
                              <li>invoice.payment_succeeded</li>
                              <li>invoice.payment_failed</li>
                              <li>customer.subscription.updated</li>
                              <li>customer.subscription.deleted</li>
                            </ul>
                          </div>
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </div>

              {/* Configuration Instructions (Not Configured) */}
              {!stripeStatus?.configured && (
                <>
                  <div className="p-4 bg-amber-50 border-2 border-amber-200 rounded-lg">
                    <div className="flex items-start gap-2">
                      <AlertCircle className="h-5 w-5 text-amber-600 flex-shrink-0 mt-0.5" />
                      <div className="text-sm">
                        <p className="font-semibold text-amber-900 mb-2">Configuration Required</p>
                        <p className="text-amber-700 mb-2">
                          Click "Edit Settings" above to configure your Stripe credentials.
                        </p>
                        <p className="text-amber-700">
                          Get your API keys from{' '}
                          <a
                            href="https://dashboard.stripe.com/apikeys"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="font-semibold underline"
                          >
                            Stripe Dashboard
                          </a>
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Webhook URL Info (Always visible) */}
                  <div className="p-4 bg-blue-50 border-2 border-blue-200 rounded-lg">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1">
                        <p className="font-semibold text-blue-900 mb-2 flex items-center gap-2">
                          <ExternalLink className="h-4 w-4" />
                          Webhook URL Configuration
                        </p>
                        <p className="text-sm text-blue-700 mb-2">
                          After configuring your API keys, set up this webhook endpoint in your Stripe Dashboard:
                        </p>
                        <div className="bg-white p-2 rounded border border-blue-300 font-mono text-sm break-all">
                          {stripeStatus?.webhook_url || 'http://localhost:8000/api/webhooks/stripe'}
                        </div>
                      </div>
                      <Button
                        onClick={() => copyToClipboard(stripeStatus?.webhook_url || 'http://localhost:8000/api/webhooks/stripe', 'Webhook URL')}
                        variant="outline"
                        size="sm"
                        className="border-blue-300 text-blue-700 hover:bg-blue-100"
                      >
                        <Copy className="h-4 w-4" />
                      </Button>
                    </div>
                    <div className="mt-3 text-xs text-blue-600">
                      <p className="font-semibold mb-1">Webhook Events to Configure:</p>
                      <div className="space-y-2">
                        <div>
                          <p className="font-medium text-blue-700">✅ Required (Configure in Stripe):</p>
                          <ul className="list-disc list-inside ml-2">
                            <li>checkout.session.completed - Handles subscriptions & donations</li>
                          </ul>
                        </div>
                        <div className="opacity-80">
                          <p className="font-medium text-blue-700">🔔 Automatically Triggered:</p>
                          <ul className="list-disc list-inside ml-2 text-xs">
                            <li>payment_intent.created</li>
                            <li>payment_intent.succeeded</li>
                            <li>charge.succeeded</li>
                            <li>charge.updated</li>
                          </ul>
                          <p className="text-xs italic mt-1">These fire automatically with checkout.session.completed</p>
                        </div>
                        <div className="opacity-70">
                          <p className="font-medium text-blue-700">🔄 Coming Soon (Recurring Subscriptions):</p>
                          <ul className="list-disc list-inside ml-2">
                            <li>invoice.payment_succeeded</li>
                            <li>invoice.payment_failed</li>
                            <li>customer.subscription.updated</li>
                            <li>customer.subscription.deleted</li>
                          </ul>
                        </div>
                      </div>
                    </div>
                  </div>
                </>
              )}

              {/* Test Connection Button */}
              {stripeStatus?.configured && (
                <div className="flex justify-end gap-3 pt-4 border-t-2 border-gray-100">
                  <Button
                    onClick={fetchStripeStatus}
                    variant="outline"
                    className="border-2 border-gray-300 rounded-full"
                    disabled={loadingStatus}
                  >
                    <RefreshCw className={`h-4 w-4 mr-2 ${loadingStatus ? 'animate-spin' : ''}`} />
                    Refresh Status
                  </Button>
                  <Button
                    onClick={handleTestConnection}
                    disabled={testing}
                    className="bg-brand-purple hover:bg-[var(--purple-dark)] text-white rounded-full"
                  >
                    {testing ? (
                      <>
                        <RefreshCw className="h-4 w-4 mr-2 animate-spin" />
                        Testing...
                      </>
                    ) : (
                      <>
                        <Zap className="h-4 w-4 mr-2" />
                        Test Connection
                      </>
                    )}
                  </Button>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* Future Settings Sections Placeholder */}
      <div className="mt-6 p-6 border-2 border-dashed border-gray-300 rounded-lg text-center text-gray-500">
        <p className="text-sm">Additional settings sections will be added here</p>
        <p className="text-xs mt-1">(Email, Storage, Notifications, etc.)</p>
      </div>
    </div>
  );
}
