'use client';

import React, { useState, useEffect } from 'react';
import Sidebar from '@/components/dashboard/Sidebar';
import Header from '@/components/dashboard/Header';
import {
  BarChart3,
  Activity,
  CheckCircle2,
  XCircle,
  Clock,
  Calendar,
  Layers,
  Sparkles,
} from 'lucide-react';

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

  const fetchUsageData = async () => {
    try {
      const [accRes, usageRes] = await Promise.all([
        fetch('/api/v1/account'),
        fetch('/api/v1/usage'),
      ]);
      const accData = await accRes.json();
      const usageData = await usageRes.json();

      if (accData.success) {
        setUser(accData.data.user);
        setWallet(accData.data.wallet);
      }
      if (usageData.success) {
        setUsage(usageData.data);
      }
    } catch {}
    finally {
      setLoading(false);
    }
  };

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

  const total = usage?.summary?.totalRequests || 0;
  const success = usage?.summary?.successfulRequests || 0;
  const failed = usage?.summary?.failedRequests || 0;

  // Mock days data for visualization
  const days = [
    { day: 'Mon', count: 12, success: 11, fail: 1 },
    { day: 'Tue', count: 24, success: 22, fail: 2 },
    { day: 'Wed', count: 45, success: 44, fail: 1 },
    { day: 'Thu', count: 38, success: 35, fail: 3 },
    { day: 'Fri', count: 62, success: 60, fail: 2 },
    { day: 'Sat', count: 18, success: 18, fail: 0 },
    { day: 'Sun', count: 29, success: 27, fail: 2 },
  ];

  const maxCount = Math.max(...days.map((d) => d.count), 1);

  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={fetchUsageData} />

        <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">
                <BarChart3 className="w-5 h-5 text-emerald-400" />
                API Usage & Latency Analytics
              </h1>
              <p className="text-xs text-slate-400 mt-0.5">
                Real-time metrics, throughput charts, and error rate distributions.
              </p>
            </div>

            <div className="flex items-center gap-2 text-xs text-slate-400 bg-slate-900 border border-slate-800 px-3 py-1.5 rounded-xl">
              <Calendar className="w-3.5 h-3.5 text-emerald-400" />
              <span>Last 7 Days (Sandbox)</span>
            </div>
          </div>

          {/* Metric Summary Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="glass-panel p-5 rounded-2xl border border-slate-800 space-y-2">
              <span className="text-xs text-slate-400 font-semibold">Total Requests</span>
              <div className="text-2xl font-extrabold text-white font-mono">{total.toLocaleString()}</div>
              <div className="text-[11px] text-emerald-400">100% Sandbox traffic</div>
            </div>

            <div className="glass-panel p-5 rounded-2xl border border-slate-800 space-y-2">
              <span className="text-xs text-slate-400 font-semibold">Success Rate</span>
              <div className="text-2xl font-extrabold text-emerald-400 font-mono">
                {usage?.summary?.successRate || 100}%
              </div>
              <div className="text-[11px] text-slate-400">{success} verified calls</div>
            </div>

            <div className="glass-panel p-5 rounded-2xl border border-slate-800 space-y-2">
              <span className="text-xs text-slate-400 font-semibold">Average Latency</span>
              <div className="text-2xl font-extrabold text-teal-400 font-mono">
                {usage?.summary?.avgLatencyMs || 280}ms
              </div>
              <div className="text-[11px] text-slate-400">p95 &lt; 400ms</div>
            </div>

            <div className="glass-panel p-5 rounded-2xl border border-slate-800 space-y-2">
              <span className="text-xs text-slate-400 font-semibold">Simulated Errors</span>
              <div className="text-2xl font-extrabold text-rose-400 font-mono">{failed}</div>
              <div className="text-[11px] text-slate-400">404, timeouts & mismatches</div>
            </div>
          </div>

          {/* Graphical Usage Bar Chart */}
          <div className="glass-panel rounded-2xl p-6 border border-slate-800 space-y-6">
            <div className="flex items-center justify-between border-b border-slate-800 pb-4">
              <div className="space-y-1">
                <h3 className="text-sm font-bold text-white flex items-center gap-2">
                  <Activity className="w-4 h-4 text-emerald-400" />
                  Daily API Verification Throughput
                </h3>
                <p className="text-xs text-slate-400">Distribution of successful vs failed requests</p>
              </div>

              <div className="flex items-center gap-4 text-xs">
                <div className="flex items-center gap-1.5">
                  <span className="w-2.5 h-2.5 rounded-sm bg-emerald-500"></span>
                  <span className="text-slate-300">Success</span>
                </div>
                <div className="flex items-center gap-1.5">
                  <span className="w-2.5 h-2.5 rounded-sm bg-rose-500"></span>
                  <span className="text-slate-300">Failed / Not Found</span>
                </div>
              </div>
            </div>

            {/* Custom Interactive SVG / CSS Chart */}
            <div className="h-64 flex items-end justify-between gap-4 pt-6 pb-2 px-4 bg-slate-950/40 rounded-xl border border-slate-900">
              {days.map((item) => {
                const heightPercent = Math.max((item.count / maxCount) * 100, 10);
                const successPercent = (item.success / item.count) * 100;
                const failPercent = (item.fail / item.count) * 100;

                return (
                  <div key={item.day} className="flex-1 flex flex-col items-center gap-2 group h-full justify-end">
                    <div className="text-[10px] text-slate-400 font-mono opacity-0 group-hover:opacity-100 transition-opacity">
                      {item.count} reqs
                    </div>

                    <div
                      style={{ height: `${heightPercent}%` }}
                      className="w-full max-w-[48px] rounded-t-lg overflow-hidden flex flex-col justify-end transition-all duration-300 group-hover:scale-105"
                    >
                      {item.fail > 0 && (
                        <div
                          style={{ height: `${failPercent}%` }}
                          className="w-full bg-rose-500/80 hover:bg-rose-400"
                        />
                      )}
                      <div
                        style={{ height: `${successPercent}%` }}
                        className="w-full bg-emerald-500 hover:bg-emerald-400 shadow-lg shadow-emerald-500/20"
                      />
                    </div>

                    <span className="text-xs font-semibold text-slate-400 group-hover:text-white">
                      {item.day}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Two-Column Breakdown: Endpoint usage & Status Codes */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Endpoint distribution */}
            <div className="glass-panel rounded-2xl p-6 border border-slate-800 space-y-4">
              <h3 className="text-sm font-bold text-white flex items-center gap-2">
                <Layers className="w-4 h-4 text-emerald-400" />
                Endpoint Breakdown
              </h3>
              <div className="space-y-3">
                <div className="space-y-1">
                  <div className="flex justify-between text-xs font-mono">
                    <span className="text-slate-300">POST /api/v1/verification/nin</span>
                    <span className="text-emerald-400 font-bold">85%</span>
                  </div>
                  <div className="h-2 rounded-full bg-slate-800 overflow-hidden">
                    <div className="h-full bg-emerald-500 w-[85%] rounded-full" />
                  </div>
                </div>

                <div className="space-y-1">
                  <div className="flex justify-between text-xs font-mono">
                    <span className="text-slate-300">POST /api/v1/verification/phone-nin</span>
                    <span className="text-teal-400 font-bold">15%</span>
                  </div>
                  <div className="h-2 rounded-full bg-slate-800 overflow-hidden">
                    <div className="h-full bg-teal-500 w-[15%] rounded-full" />
                  </div>
                </div>
              </div>
            </div>

            {/* Status Code breakdown */}
            <div className="glass-panel rounded-2xl p-6 border border-slate-800 space-y-4">
              <h3 className="text-sm font-bold text-white flex items-center gap-2">
                <Sparkles className="w-4 h-4 text-emerald-400" />
                HTTP Status Codes
              </h3>
              <div className="grid grid-cols-2 gap-3">
                <div className="p-3.5 rounded-xl bg-slate-900 border border-slate-800 space-y-1">
                  <span className="text-[10px] text-emerald-400 font-mono font-bold block">200 OK</span>
                  <div className="text-lg font-bold text-white font-mono">{success}</div>
                  <span className="text-[10px] text-slate-500">Successful verifications</span>
                </div>

                <div className="p-3.5 rounded-xl bg-slate-900 border border-slate-800 space-y-1">
                  <span className="text-[10px] text-amber-400 font-mono font-bold block">404 NOT FOUND</span>
                  <div className="text-lg font-bold text-white font-mono">{failed}</div>
                  <span className="text-[10px] text-slate-500">Unassigned identities</span>
                </div>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}
