'use client';

import React, { useState, useEffect } from 'react';
import AppLayout from '@/components/layout/AppLayout';
import { AuditLogRecord } from '@/types';
import { META_CONFIG } from '@/config/meta';

export default function DiagnosticsPage() {
  const [logs, setLogs] = useState<AuditLogRecord[]>([]);
  const [health, setHealth] = useState<{
    shopifyAuth?: string;
    metaAuth?: string;
    capiStatus?: string;
    queueStatus?: string;
  }>({});
  const [isLoading, setIsLoading] = useState(true);

  const loadDiagnostics = async () => {
    try {
      const res = await fetch('/api/diagnostics');
      const data = await res.json();
      if (data.success) {
        setLogs(data.auditLogs || []);
        setHealth(data.health || {});
      }
    } catch (err) {
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

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

  return (
    <AppLayout currentRoute="/diagnostics">
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-200/80 pb-4">
          <div>
            <div className="flex items-center gap-2 text-xs font-semibold text-blue-600 uppercase tracking-wider">
              <i className="fa-solid fa-shield-halved text-xs" />
              <span>System Telemetry &amp; Security</span>
            </div>
            <h1 className="text-2xl font-bold text-slate-900 tracking-tight mt-1">Diagnostics &amp; Audit Logs</h1>
            <p className="text-xs text-slate-500">
              System health checks, queue execution metrics, and security audit logs with PII masking.
            </p>
          </div>
          <button
            onClick={loadDiagnostics}
            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 transition-colors flex items-center gap-1.5 shadow-2xs cursor-pointer"
          >
            <i className={`fa-solid fa-arrows-rotate text-xs ${isLoading ? 'fa-spin text-blue-600' : ''}`} />
            <span>Refresh Diagnostics</span>
          </button>
        </div>

        {/* System Health Status Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-xs space-y-2 hover:shadow-sm transition-shadow">
            <div className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">Shopify Auth &amp; HMAC</div>
            <div className="flex items-center gap-2">
              <i className="fa-solid fa-circle-check text-emerald-500 text-sm" />
              <span className="font-bold text-xs text-slate-900">Verified &amp; Active</span>
            </div>
            <p className="text-[11px] text-slate-400">Timing-safe HMAC SHA-256</p>
          </div>

          <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-xs space-y-2 hover:shadow-sm transition-shadow">
            <div className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">Meta Graph OAuth</div>
            <div className="flex items-center gap-2">
              <i className="fa-solid fa-circle-check text-blue-600 text-sm" />
              <span className="font-bold text-xs text-slate-900">Token Valid (AES-256)</span>
            </div>
            <p className="text-[11px] text-slate-400">Graph API {META_CONFIG.graphVersion}</p>
          </div>

          <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-xs space-y-2 hover:shadow-sm transition-shadow">
            <div className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">CAPI Match Engine</div>
            <div className="flex items-center gap-2">
              <i className="fa-solid fa-bolt text-purple-600 text-sm" />
              <span className="font-bold text-xs text-slate-900">High Quality (9.4)</span>
            </div>
            <p className="text-[11px] text-slate-400">SHA-256 E.164 &amp; Lowercase</p>
          </div>

          <div className="bg-white p-5 rounded-2xl border border-slate-200/80 shadow-xs space-y-2 hover:shadow-sm transition-shadow">
            <div className="text-[11px] font-bold text-slate-400 uppercase tracking-wider">Background Job Queue</div>
            <div className="flex items-center gap-2">
              <i className="fa-solid fa-shield-halved text-emerald-500 text-sm" />
              <span className="font-bold text-xs text-slate-900">Worker Ready</span>
            </div>
            <p className="text-[11px] text-slate-400">Exponential backoff active</p>
          </div>
        </div>

        {/* Audit Log Table */}
        <div className="bg-white rounded-2xl border border-slate-200/80 shadow-xs overflow-hidden">
          <div className="p-5 border-b border-slate-100 flex items-center justify-between flex-wrap gap-2">
            <div className="flex items-center gap-2">
              <i className="fa-regular fa-file-lines text-blue-600 text-sm" />
              <h3 className="font-bold text-sm text-slate-900">Audit Trail History ({logs.length})</h3>
            </div>
            <span className="text-[11px] text-slate-400">PII automatically masked for security</span>
          </div>

          {logs.length === 0 ? (
            <div className="p-16 text-center text-xs text-slate-400">No audit log records found yet.</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs text-slate-600 min-w-[640px]">
                <thead className="bg-slate-50/80 text-slate-400 uppercase tracking-wider text-[10px] font-bold border-b border-slate-200/80">
                  <tr>
                    <th className="py-3 px-5">Timestamp</th>
                    <th className="py-3 px-4">Action</th>
                    <th className="py-3 px-4">Actor</th>
                    <th className="py-3 px-5">Metadata</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {logs.map((log) => (
                    <tr key={log.id} className="hover:bg-slate-50/70 transition-colors">
                      <td className="py-3.5 px-5 text-slate-400 font-mono text-[11px] whitespace-nowrap">
                        {new Date(log.created_at).toLocaleString()}
                      </td>
                      <td className="py-3.5 px-4 font-bold text-slate-900">{log.action}</td>
                      <td className="py-3.5 px-4">
                        <span className="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-slate-100/80 text-slate-700 border border-slate-200/60 shadow-2xs">
                          {log.actor}
                        </span>
                      </td>
                      <td className="py-3.5 px-5 font-mono text-[11px] text-slate-500 max-w-md truncate">
                        {JSON.stringify(log.metadata || {})}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </AppLayout>
  );
}
