'use client';

import React, { useState, useEffect } from 'react';
import Sidebar from '@/components/dashboard/Sidebar';
import Header from '@/components/dashboard/Header';
import {
  Webhook,
  Plus,
  Send,
  CheckCircle2,
  XCircle,
  ShieldCheck,
  Copy,
  Check,
  RefreshCw,
  X,
  Code,
} from 'lucide-react';

export default function WebhooksPage() {
  const [user, setUser] = useState<any>(null);
  const [wallet, setWallet] = useState<any>(null);
  const [webhooks, setWebhooks] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // New Webhook Modal
  const [modalOpen, setModalOpen] = useState(false);
  const [endpointUrl, setEndpointUrl] = useState('https://api.yourdomain.ng/webhooks/smartauth');
  const [saving, setSaving] = useState(false);

  // Test Ping State
  const [testingWebhookId, setTestingWebhookId] = useState<string | null>(null);
  const [testResult, setTestResult] = useState<any>(null);
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  const fetchWebhooks = async () => {
    try {
      const [accRes, whRes] = await Promise.all([
        fetch('/api/v1/account'),
        fetch('/api/v1/webhooks'),
      ]);
      const accData = await accRes.json();
      const whData = await whRes.json();

      if (accData.success) {
        setUser(accData.data.user);
        setWallet(accData.data.wallet);
      }
      if (whData.success) {
        setWebhooks(whData.data || []);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

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

  const handleRegisterWebhook = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const res = await fetch('/api/v1/webhooks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url: endpointUrl }),
      });
      const data = await res.json();
      if (data.success) {
        setModalOpen(false);
        fetchWebhooks();
      }
    } catch {}
    finally {
      setSaving(false);
    }
  };

  const handleTestPing = async (webhookId: string) => {
    setTestingWebhookId(webhookId);
    setTestResult(null);

    try {
      const res = await fetch('/api/v1/webhooks/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ webhookId, eventType: 'verification.success' }),
      });
      const data = await res.json();
      setTestResult(data);
      fetchWebhooks(); // Refresh delivery history
    } catch (err: any) {
      setTestResult({ success: false, error: { message: err.message } });
    } finally {
      setTestingWebhookId(null);
    }
  };

  const handleCopy = (secret: string, id: string) => {
    navigator.clipboard.writeText(secret);
    setCopiedKey(id);
    setTimeout(() => setCopiedKey(null), 2000);
  };

  return (
    <div className="flex min-h-screen bg-[#070b14] text-slate-100">
      <Sidebar userRole={user?.role} />

      <div className="flex-1 flex flex-col min-w-0">
        <Header user={user} walletBalance={wallet?.balance || 0} onRefreshWallet={fetchWebhooks} />

        <main className="flex-1 p-6 space-y-6 overflow-y-auto max-w-7xl">
          {/* Header */}
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div>
              <h1 className="text-xl font-bold text-white flex items-center gap-2">
                <Webhook className="w-5 h-5 text-emerald-400" />
                Webhooks & Real-Time Event Dispatcher
              </h1>
              <p className="text-xs text-slate-400 mt-0.5">
                Subscribe to verification lifecycle events with cryptographic HMAC-SHA256 signatures.
              </p>
            </div>

            <button
              onClick={() => setModalOpen(true)}
              className="px-4 py-2 bg-emerald-400 hover:bg-emerald-300 text-slate-900 font-bold text-xs rounded-xl shadow-md shadow-emerald-500/20 transition-all flex items-center gap-2"
            >
              <Plus className="w-4 h-4" />
              Add Webhook Endpoint
            </button>
          </div>

          {/* Security Guide */}
          <div className="p-4 rounded-2xl bg-slate-900/80 border border-slate-800 flex items-start gap-3 text-xs text-slate-300">
            <ShieldCheck className="w-5 h-5 text-emerald-400 shrink-0 mt-0.5" />
            <div className="space-y-1">
              <span className="font-bold text-white">HMAC Signature Verification</span>
              <p className="text-slate-400 leading-relaxed">
                All outgoing webhook HTTP requests include the <code className="text-emerald-400">X-SmartAuth-Signature</code> header. Compute an HMAC-SHA256 hash of the raw JSON body using your webhook secret to verify authenticity.
              </p>
            </div>
          </div>

          {/* Webhook List */}
          <div className="space-y-4">
            {webhooks.length > 0 ? (
              webhooks.map((wh) => (
                <div key={wh.id} className="glass-panel p-6 rounded-2xl border border-slate-800 space-y-4">
                  <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-800 pb-4">
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-sm font-bold text-white">{wh.url}</span>
                        <span className="px-2 py-0.5 rounded-full bg-emerald-500/20 text-emerald-300 text-[10px] font-bold">
                          {wh.status}
                        </span>
                      </div>
                      <div className="flex items-center gap-2 text-xs text-slate-400 font-mono">
                        <span>Signing Secret:</span>
                        <code className="text-emerald-400 bg-slate-900 px-2 py-0.5 rounded text-[11px]">
                          {wh.secretKey.slice(0, 10)}...{wh.secretKey.slice(-6)}
                        </code>
                        <button
                          onClick={() => handleCopy(wh.secretKey, wh.id)}
                          className="text-slate-400 hover:text-white p-1"
                        >
                          {copiedKey === wh.id ? <Check className="w-3 h-3 text-emerald-400" /> : <Copy className="w-3 h-3" />}
                        </button>
                      </div>
                    </div>

                    <button
                      onClick={() => handleTestPing(wh.id)}
                      disabled={testingWebhookId === wh.id}
                      className="px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-bold rounded-xl border border-slate-700 transition-all flex items-center gap-1.5"
                    >
                      {testingWebhookId === wh.id ? (
                        <RefreshCw className="w-3.5 h-3.5 animate-spin" />
                      ) : (
                        <Send className="w-3.5 h-3.5" />
                      )}
                      {testingWebhookId === wh.id ? 'Dispatching Ping...' : 'Send Test Ping'}
                    </button>
                  </div>

                  {/* Deliveries History */}
                  <div className="space-y-2">
                    <span className="text-[11px] font-bold text-slate-400 uppercase tracking-wider block">
                      Recent Delivery Attempts
                    </span>
                    {wh.deliveries && wh.deliveries.length > 0 ? (
                      <div className="overflow-x-auto">
                        <table className="w-full text-left text-xs font-mono">
                          <thead>
                            <tr className="border-b border-slate-800 text-slate-400 text-[10px]">
                              <th className="py-2 px-2">Event</th>
                              <th className="py-2 px-2">Status</th>
                              <th className="py-2 px-2">HTTP Code</th>
                              <th className="py-2 px-2">Timestamp</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-slate-800/60 text-slate-300">
                            {wh.deliveries.map((del: any) => (
                              <tr key={del.id}>
                                <td className="py-2 px-2 text-emerald-400">{del.eventType}</td>
                                <td className="py-2 px-2">
                                  <span
                                    className={`px-1.5 py-0.5 rounded text-[10px] font-bold ${
                                      del.status === 'DELIVERED'
                                        ? 'bg-emerald-500/20 text-emerald-300'
                                        : 'bg-rose-500/20 text-rose-300'
                                    }`}
                                  >
                                    {del.status}
                                  </span>
                                </td>
                                <td className="py-2 px-2">{del.responseStatus || 'N/A'}</td>
                                <td className="py-2 px-2 text-slate-400 font-sans">
                                  {new Date(del.createdAt).toLocaleTimeString()}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    ) : (
                      <p className="text-xs text-slate-500 font-sans">
                        No deliveries recorded yet. Click "Send Test Ping" to verify your endpoint.
                      </p>
                    )}
                  </div>
                </div>
              ))
            ) : (
              <div className="glass-panel p-10 rounded-2xl border border-slate-800 text-center space-y-3">
                <Webhook className="w-8 h-8 text-emerald-400/50 mx-auto" />
                <h3 className="text-base font-bold text-white">No Webhook Endpoints Configured</h3>
                <p className="text-xs text-slate-400 max-w-sm mx-auto">
                  Add an HTTPS webhook endpoint to receive asynchronous event payloads when identities are verified.
                </p>
                <button
                  onClick={() => setModalOpen(true)}
                  className="px-4 py-2 bg-emerald-400 text-slate-900 font-bold text-xs rounded-xl shadow-md shadow-emerald-500/20"
                >
                  Configure Webhook
                </button>
              </div>
            )}
          </div>

          {/* Test Ping Result Modal */}
          {testResult && (
            <div className="p-4 rounded-2xl bg-slate-900 border border-slate-700 space-y-2">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold text-white flex items-center gap-1.5">
                  <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                  Test Ping Dispatched
                </span>
                <button
                  onClick={() => setTestResult(null)}
                  className="text-slate-400 hover:text-white text-xs"
                >
                  Dismiss
                </button>
              </div>
              <p className="text-xs text-slate-300">{testResult.message}</p>
              <pre className="p-3 rounded-lg bg-black/50 text-[11px] font-mono text-emerald-300 overflow-x-auto max-h-40">
                {JSON.stringify(testResult.data?.payloadSent, null, 2)}
              </pre>
            </div>
          )}

          {/* Modal to Register Webhook */}
          {modalOpen && (
            <div className="fixed inset-0 bg-black/75 backdrop-blur-sm z-50 flex items-center justify-center p-4">
              <div className="glass-panel w-full max-w-md rounded-2xl p-6 border border-slate-700 space-y-4 shadow-2xl animate-in fade-in zoom-in-95 duration-200">
                <div className="flex items-center justify-between border-b border-slate-800 pb-3">
                  <div className="flex items-center gap-2">
                    <Webhook className="w-5 h-5 text-emerald-400" />
                    <h3 className="text-base font-bold text-white">Add Webhook Endpoint</h3>
                  </div>
                  <button
                    onClick={() => setModalOpen(false)}
                    className="text-slate-400 hover:text-white p-1"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>

                <form onSubmit={handleRegisterWebhook} className="space-y-4">
                  <div>
                    <label className="block text-xs font-semibold text-slate-300 mb-1.5">
                      Endpoint HTTPS URL
                    </label>
                    <input
                      type="url"
                      required
                      value={endpointUrl}
                      onChange={(e) => setEndpointUrl(e.target.value)}
                      placeholder="https://api.yourdomain.ng/webhooks/smartauth"
                      className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3.5 py-2.5 text-xs font-mono text-white focus:outline-none focus:border-emerald-500"
                    />
                  </div>

                  <div className="p-3 rounded-xl bg-slate-900/60 border border-slate-800 text-[11px] text-slate-400 space-y-1">
                    <span className="font-bold text-slate-300">Subscribed Events:</span>
                    <ul className="list-disc pl-4 space-y-0.5">
                      <li>verification.success (When an identity is verified)</li>
                      <li>verification.failed (When a mismatch occurs)</li>
                    </ul>
                  </div>

                  <div className="pt-2">
                    <button
                      type="submit"
                      disabled={saving}
                      className="w-full py-3 bg-emerald-400 hover:bg-emerald-300 text-slate-900 font-bold text-xs rounded-xl shadow-lg shadow-emerald-500/20 transition-all flex items-center justify-center gap-2 disabled:opacity-50"
                    >
                      {saving ? 'Registering...' : 'Save Webhook Endpoint'}
                    </button>
                  </div>
                </form>
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
