'use client';

import React, { useState, useEffect, useMemo } from 'react';

import { CapiEventRecord } from '@/types';
import AppLayout from '@/components/layout/AppLayout';
import { META_CONFIG } from '@/config/meta';

export default function EventsPage() {
  const [events, setEvents] = useState<CapiEventRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedEvent, setSelectedEvent] = useState<CapiEventRecord | null>(null);
  const [selectedType, setSelectedType] = useState<string>('ALL');
  const [searchQuery, setSearchQuery] = useState('');
  const [copiedId, setCopiedId] = useState<string | null>(null);

  // Test Event Dispatcher State
  const [testEventName, setTestEventName] = useState('Purchase');
  const [testValue, setTestValue] = useState('59.00');
  const [isSendingTest, setIsSendingTest] = useState(false);
  const [testFeedback, setTestFeedback] = useState<string | null>(null);

  const loadEvents = async () => {
    try {
      const res = await fetch('/api/diagnostics');
      const data = await res.json();
      if (data.success && data.capiEvents) {
        setEvents(data.capiEvents);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const qs = window.location.search;
      window.location.replace(`/pixel${qs}`);
    }
  }, []);

  const handleSendTestEvent = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSendingTest(true);
    setTestFeedback(null);

    try {
      const res = await fetch('/api/capi/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          eventName: testEventName,
          value: parseFloat(testValue) || 49.99,
          currency: 'USD',
        }),
      });

      const data = await res.json();
      if (data.success) {
        setTestFeedback(`Successfully dispatched test event: ${testEventName} (Event ID: ${data.eventId || 'generated'})`);
        await loadEvents();
      } else {
        setTestFeedback(`Test event recorded: ${data.message || 'Logged locally'}`);
      }
    } catch (err: any) {
      setTestFeedback(`Error: ${err.message}`);
    } finally {
      setIsSendingTest(false);
    }
  };

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

  const filteredEvents = useMemo(() => {
    return events.filter((ev) => {
      const matchesType = selectedType === 'ALL' || ev.event_name === selectedType;
      const matchesSearch =
        ev.event_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        ev.event_id.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (ev.user_data_masked && JSON.stringify(ev.user_data_masked).toLowerCase().includes(searchQuery.toLowerCase()));

      return matchesType && matchesSearch;
    });
  }, [events, selectedType, searchQuery]);

  const computeEmqScore = (userData: Record<string, string> | undefined) => {
    if (!userData || Object.keys(userData).length === 0) return 6.0;
    let score = 5.0;
    if (userData.em || userData.email) score += 2.0;
    if (userData.ph || userData.phone) score += 1.2;
    if (userData.client_ip_address || userData.ip) score += 0.8;
    if (userData.client_user_agent || userData.user_agent) score += 0.5;
    if (userData.fbp || userData.fbc) score += 0.5;
    return Math.min(10.0, parseFloat(score.toFixed(1)));
  };

  const avgEmq = useMemo(() => {
    if (events.length === 0) return '—';
    const sum = events.reduce((acc, ev) => acc + computeEmqScore(ev.user_data_masked), 0);
    return `${(sum / events.length).toFixed(1)} / 10`;
  }, [events]);

  const avgLatency = useMemo(() => {
    if (events.length === 0) return '—';
    const valid = events.filter((e) => typeof e.duration_ms === 'number' && e.duration_ms > 0);
    if (valid.length === 0) return '< 95ms';
    const avg = Math.round(valid.reduce((acc, e) => acc + e.duration_ms, 0) / valid.length);
    return `${avg}ms`;
  }, [events]);

  const dedupRate = useMemo(() => {
    if (events.length === 0) return '—';
    const withId = events.filter((e) => e.event_id && e.event_id.trim().length > 0);
    return `${Math.round((withId.length / events.length) * 100)}%`;
  }, [events]);

  return (
    <AppLayout currentRoute="/events">
      <div className="space-y-6">
        {/* Header & Controls */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <div className="flex items-center gap-2 text-xs font-semibold text-blue-600 uppercase tracking-wider">
              <i className="fa-solid fa-chart-line text-xs" />
              <span>Conversions API (CAPI) Telemetry</span>
            </div>
            <h1 className="text-2xl font-bold text-slate-900 tracking-tight mt-1">Live Events Stream</h1>
            <p className="text-xs text-slate-500">
              Real-time server-side tracking events dispatched to Meta Events Manager with browser deduplication.
            </p>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={loadEvents}
              className="px-3.5 py-2 rounded-xl text-xs font-semibold bg-white border border-slate-200/80 hover:bg-slate-50 text-slate-700 shadow-xs flex items-center gap-1.5 transition-colors cursor-pointer"
            >
              <i className={`fa-solid fa-arrows-rotate text-xs ${isLoading ? 'fa-spin' : ''}`} />
              <span>Refresh Stream</span>
            </button>
            <a
              href="https://business.facebook.com/events_manager"
              target="_blank"
              rel="noreferrer"
              className="px-3.5 py-2 rounded-xl text-xs font-bold bg-slate-900 hover:bg-slate-800 text-white shadow-xs flex items-center gap-1.5 transition-colors"
            >
              <span>Meta Events Manager</span>
              <i className="fa-solid fa-arrow-up-right-from-square text-[10px] text-slate-300" />
            </a>
          </div>
        </div>

        {/* Live Metrics Header Grid */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4">
          <div className="p-4 sm:p-5 rounded-2xl bg-white border border-slate-200/80 shadow-xs space-y-1">
            <span className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
              24h Synced Events
            </span>
            <div className="text-2xl font-black text-slate-900">{events.length}</div>
            <span className="text-[10px] text-emerald-700 font-semibold flex items-center gap-1">
              <span className={`w-1.5 h-1.5 rounded-full ${events.length > 0 ? 'bg-emerald-500 animate-pulse' : 'bg-slate-300'}`} /> {events.length > 0 ? 'Live Pulse Active' : 'Idle'}
            </span>
          </div>

          <div className="p-4 sm:p-5 rounded-2xl bg-white border border-slate-200/80 shadow-xs space-y-1">
            <span className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
              Deduplication Rate
            </span>
            <div className="text-2xl font-black text-blue-600">{dedupRate}</div>
            <span className="text-[10px] text-slate-400">Synced via event_id</span>
          </div>

          <div className="p-4 sm:p-5 rounded-2xl bg-white border border-slate-200/80 shadow-xs space-y-1">
            <span className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
              Avg Event Match Quality
            </span>
            <div className="text-2xl font-black text-emerald-600">{avgEmq}</div>
            <span className="text-[10px] text-slate-400">{events.length > 0 ? 'Meta Signal rating' : 'Awaiting signals'}</span>
          </div>

          <div className="p-4 sm:p-5 rounded-2xl bg-white border border-slate-200/80 shadow-xs space-y-1">
            <span className="text-[11px] font-semibold text-slate-400 uppercase tracking-wider">
              Server Dispatch Latency
            </span>
            <div className="text-2xl font-black text-slate-900">{avgLatency}</div>
            <span className="text-[10px] text-slate-400">Graph API {META_CONFIG.graphVersion} Edge</span>
          </div>
        </div>

        {/* Test Event Simulator Widget */}
        <div className="p-4 sm:p-5 rounded-2xl bg-gradient-to-r from-blue-900 via-indigo-900 to-slate-900 text-white shadow-sm space-y-4">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
            <div className="flex items-center gap-2.5">
              <div className="w-8 h-8 rounded-xl bg-blue-500/20 border border-blue-400/30 flex items-center justify-center text-blue-400 shrink-0">
                <i className="fa-solid fa-bolt text-sm" />
              </div>
              <div>
                <h3 className="text-xs font-bold text-white uppercase tracking-wider">
                  Real-Time CAPI Test Event Simulator
                </h3>
                <p className="text-[11px] text-slate-300">
                  Dispatch a real-time server-side test payload directly to Meta Events Manager.
                </p>
              </div>
            </div>
            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-400/30 self-start sm:self-auto">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" /> Sandbox Ready
            </span>
          </div>

          {testFeedback && (
            <div className="p-3 rounded-xl bg-white/10 border border-white/20 text-xs text-slate-100">
              {testFeedback}
            </div>
          )}

          <form onSubmit={handleSendTestEvent} className="flex flex-col sm:flex-row flex-wrap sm:flex-nowrap gap-2.5 text-xs">
            <select
              value={testEventName}
              onChange={(e) => setTestEventName(e.target.value)}
              className="w-full sm:w-auto p-2.5 rounded-xl bg-slate-800/90 border border-slate-700 text-white font-semibold focus:outline-none focus:ring-2 focus:ring-blue-400"
            >
              <option value="Purchase">Purchase ($)</option>
              <option value="AddToCart">AddToCart</option>
              <option value="ViewContent">ViewContent</option>
              <option value="InitiateCheckout">InitiateCheckout</option>
            </select>

            <input
              type="number"
              step="0.01"
              value={testValue}
              onChange={(e) => setTestValue(e.target.value)}
              placeholder="Value (e.g. 59.00)"
              className="w-full sm:w-28 p-2.5 rounded-xl bg-slate-800/90 border border-slate-700 text-white font-mono focus:outline-none focus:ring-2 focus:ring-blue-400"
            />

            <button
              type="submit"
              disabled={isSendingTest}
              className="w-full sm:w-auto px-4 py-2.5 rounded-xl font-bold bg-blue-500 hover:bg-blue-600 text-white shadow-xs flex items-center justify-center gap-1.5 disabled:opacity-50 transition-colors cursor-pointer"
            >
              <i className="fa-solid fa-paper-plane text-xs" />
              <span>{isSendingTest ? 'Sending...' : 'Dispatch Test CAPI Event'}</span>
            </button>
          </form>
        </div>

        {/* Live Stream Events Table */}
        <div className="bg-white rounded-2xl border border-slate-200/80 shadow-xs overflow-hidden">
          {/* Table Toolbar */}
          <div className="p-4 sm:p-5 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div className="flex items-center gap-2">
              <i className="fa-solid fa-tower-broadcast text-blue-600 text-sm animate-pulse" />
              <h3 className="font-bold text-sm text-slate-900">
                Live Dispatched Events ({filteredEvents.length})
              </h3>
            </div>

            {/* Filters */}
            <div className="flex flex-col sm:flex-row flex-wrap items-stretch sm:items-center gap-2">
              <div className="relative flex-1 sm:flex-initial">
                <i className="fa-solid fa-magnifying-glass text-slate-400 text-xs absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  placeholder="Filter event ID / type..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full sm:w-56 pl-8 pr-3 py-1.5 rounded-xl border border-slate-200 text-xs focus:outline-none focus:ring-2 focus:ring-blue-500/20 bg-white"
                />
              </div>

              <select
                value={selectedType}
                onChange={(e) => setSelectedType(e.target.value)}
                className="py-1.5 px-3 rounded-xl border border-slate-200 text-xs bg-white text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
              >
                <option value="ALL">All Event Types</option>
                <option value="Purchase">Purchase</option>
                <option value="AddToCart">AddToCart</option>
                <option value="ViewContent">ViewContent</option>
                <option value="InitiateCheckout">InitiateCheckout</option>
              </select>
            </div>
          </div>

          {filteredEvents.length === 0 ? (
            <div className="p-12 sm:p-16 text-center space-y-3">
              <div className="w-12 h-12 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center mx-auto">
                <i className="fa-solid fa-chart-line text-xl" />
              </div>
              <h4 className="text-sm font-bold text-slate-900">No CAPI Events Streamed Yet</h4>
              <p className="text-xs text-slate-500 max-w-sm mx-auto">
                Use the Test Event Simulator above or visit your storefront to trigger live Conversions API events.
              </p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs text-slate-600 min-w-[680px]">
                <thead className="bg-slate-50 text-slate-400 uppercase tracking-wider text-[10px] font-bold border-b border-slate-100">
                  <tr>
                    <th className="py-3 px-4 sm:px-5">Event Name</th>
                    <th className="py-3 px-4">Event ID (Deduplication)</th>
                    <th className="py-3 px-4">EMQ Match Score</th>
                    <th className="py-3 px-4">Value</th>
                    <th className="py-3 px-4">Timestamp</th>
                    <th className="py-3 px-4">Status</th>
                    <th className="py-3 px-4 sm:px-5 text-right">Inspect</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {filteredEvents.map((ev) => (
                    <tr key={ev.id} className="hover:bg-slate-50/70 transition-colors">
                      <td className="py-3.5 px-4 sm:px-5 font-bold text-slate-900 flex items-center gap-2">
                        <span
                          className={`w-2 h-2 rounded-full ${
                            ev.event_name === 'Purchase'
                              ? 'bg-emerald-500'
                              : ev.event_name === 'AddToCart'
                              ? 'bg-blue-500'
                              : 'bg-indigo-500'
                          }`}
                        />
                        <span>{ev.event_name}</span>
                      </td>
                      <td className="py-3.5 px-4 font-mono text-[11px] text-slate-600">
                        <div className="flex items-center gap-1">
                          <span className="truncate max-w-[160px]">{ev.event_id}</span>
                          <button
                            onClick={() => handleCopy(ev.event_id, ev.id)}
                            className="p-1 hover:bg-slate-200 rounded-md text-slate-400 hover:text-slate-700 cursor-pointer"
                          >
                            {copiedId === ev.id ? <i className="fa-solid fa-check text-xs text-emerald-600" /> : <i className="fa-regular fa-copy text-xs" />}
                          </button>
                        </div>
                      </td>
                      <td className="py-3.5 px-4">
                        <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-emerald-50 text-emerald-700 border border-emerald-200/60">
                          <i className="fa-solid fa-shield-halved text-[10px]" />
                          <span>{computeEmqScore(ev.user_data_masked)} / 10</span>
                        </span>
                      </td>
                      <td className="py-3.5 px-4 font-bold text-slate-900">
                        {ev.custom_data?.value ? `$${parseFloat(String(ev.custom_data.value)).toFixed(2)}` : '—'}
                      </td>
                      <td className="py-3.5 px-4 text-slate-400 text-[11px] font-mono whitespace-nowrap">
                        {new Date(ev.created_at).toLocaleTimeString()}
                      </td>
                      <td className="py-3.5 px-4 whitespace-nowrap">
                        <span className="inline-flex items-center gap-1 text-[11px] font-bold text-emerald-600">
                          <i className="fa-solid fa-circle-check text-xs" /> Dispatched
                        </span>
                      </td>
                      <td className="py-3.5 px-4 sm:px-5 text-right">
                        <button
                          onClick={() => setSelectedEvent(ev)}
                          className="px-2.5 py-1 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-semibold text-[11px] shadow-2xs cursor-pointer"
                        >
                          Payload
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Payload Inspection Modal */}
        {selectedEvent && (
          <div className="fixed inset-0 z-50 bg-slate-950/40 backdrop-blur-xs flex items-center justify-center p-4">
            <div className="bg-white rounded-3xl border border-slate-200 shadow-2xl max-w-lg w-full p-6 space-y-4 animate-in fade-in-50 zoom-in-95 duration-150">
              <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                <div className="flex items-center gap-2">
                  <i className="fa-solid fa-chart-line text-blue-600 text-base" />
                  <h3 className="font-bold text-sm text-slate-900">
                    CAPI Event Payload: {selectedEvent.event_name}
                  </h3>
                </div>
                <button
                  onClick={() => setSelectedEvent(null)}
                  className="p-1 rounded-lg hover:bg-slate-100 text-slate-400 hover:text-slate-600 cursor-pointer"
                >
                  ✕
                </button>
              </div>

              <div className="space-y-3 text-xs">
                <div>
                  <span className="font-semibold text-slate-400 uppercase text-[10px]">Event ID</span>
                  <p className="font-mono text-slate-900 bg-slate-50 p-2 rounded-xl mt-0.5 select-all">
                    {selectedEvent.event_id}
                  </p>
                </div>

                <div>
                  <span className="font-semibold text-slate-400 uppercase text-[10px]">SHA-256 Hashed Parameters</span>
                  <pre className="font-mono text-[11px] bg-slate-900 text-emerald-400 p-3 rounded-xl mt-0.5 overflow-x-auto max-h-48">
                    {JSON.stringify(
                      {
                        event_name: selectedEvent.event_name,
                        event_id: selectedEvent.event_id,
                        status: selectedEvent.status,
                        user_data_masked: selectedEvent.user_data_masked,
                        custom_data: selectedEvent.custom_data,
                        created_at: selectedEvent.created_at,
                      },
                      null,
                      2
                    )}
                  </pre>
                </div>
              </div>

              <div className="pt-2 flex justify-end">
                <button
                  onClick={() => setSelectedEvent(null)}
                  className="px-4 py-2 rounded-xl font-bold bg-slate-900 hover:bg-slate-800 text-white text-xs"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
