import { useState, useEffect } from 'react';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';
import { Link, useNavigate } from 'react-router-dom';

interface AnalyticsRecord {
  id: number;
  ipAddress: string;
  country: string;
  city: string;
  device: string;
  browser: string;
  path: string;
  timestamp: string;
}

export default function Analytics() {
  const [logs, setLogs] = useState<AnalyticsRecord[]>([]);
  const { user, token } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    if (user?.role !== 'superadmin') {
      navigate('/dashboard');
      return;
    }

    const fetchAnalytics = async () => {
      try {
        const res = await axios.get('/api/analytics', { headers: { Authorization: `Bearer ${token}` } });
        setLogs(res.data);
      } catch (err) {
        console.error("Failed to fetch analytics", err);
      }
    };
    if (token) fetchAnalytics();
  }, [token, user, navigate]);

  return (
    <div className="font-body-md text-body-md overflow-x-hidden min-h-screen bg-[#f8fafc] text-[#0f172a] -mt-5 -mx-3 px-3 py-10" style={{ fontFamily: 'Inter, sans-serif' }}>
      <div className="px-4 py-8 max-w-[1440px] mx-auto">
        
        {/* Header Section */}
        <div className="mb-10 flex justify-between items-end">
          <div>
            <h1 className="font-display-lg text-[32px] md:text-[48px] font-bold leading-tight text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>
              Visitor Analytics
            </h1>
            <p className="font-body-lg text-[16px] md:text-[18px] text-[#475569] mt-2">Track IPs, geolocation, and device usage across public magic links.</p>
          </div>
          <Link to="/dashboard" className="px-6 py-3 bg-[#f1f5f9] border border-black/10 rounded-lg text-[#0f172a] font-semibold flex items-center gap-2 hover:bg-black/5 transition-colors no-underline">
            <span className="material-symbols-outlined">arrow_back</span>
            Back to Dashboard
          </Link>
        </div>

        {/* Global Stats Row */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-[24px] mb-12">
          <div className="glass-card p-6 rounded-xl flex flex-col justify-center">
            <span className="text-[#475569] font-semibold text-[14px] mb-2">Total Visits Logged</span>
            <span className="font-bold text-[36px] text-[#4edea3]" style={{ fontFamily: 'Outfit, sans-serif' }}>{logs.length}</span>
          </div>
          <div className="glass-card p-6 rounded-xl flex flex-col justify-center">
            <span className="text-[#475569] font-semibold text-[14px] mb-2">Mobile Usage</span>
            <span className="font-bold text-[36px] text-[#c0c1ff]" style={{ fontFamily: 'Outfit, sans-serif' }}>
              {logs.length > 0 ? Math.round((logs.filter(l => l.device === 'Mobile').length / logs.length) * 100) : 0}%
            </span>
          </div>
          <div className="glass-card p-6 rounded-xl flex flex-col justify-center">
            <span className="text-[#475569] font-semibold text-[14px] mb-2">Top Browser</span>
            <span className="font-bold text-[36px] text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>
              {logs.length > 0 ? Object.entries(logs.reduce((acc: any, log) => { acc[log.browser] = (acc[log.browser] || 0) + 1; return acc; }, {})).sort((a: any, b: any) => b[1] - a[1])[0][0] : 'N/A'}
            </span>
          </div>
          <div className="glass-card p-6 rounded-xl flex flex-col justify-center relative overflow-hidden">
            <div className="absolute -right-4 -top-4 w-32 h-32 bg-[#ffb4ab]/10 rounded-full blur-3xl"></div>
            <span className="text-[#475569] font-semibold text-[14px] mb-2">Active Regions</span>
            <span className="font-bold text-[36px] text-[#ffb4ab]" style={{ fontFamily: 'Outfit, sans-serif' }}>
              {new Set(logs.map(l => l.country)).size}
            </span>
          </div>
        </div>

        {/* Traffic Logs Table */}
        <div className="glass-card rounded-xl overflow-hidden mb-12">
          <div className="px-8 py-6 border-b border-black/10">
            <h3 className="text-[24px] font-semibold text-[#0f172a]" style={{ fontFamily: 'Outfit, sans-serif' }}>Raw Traffic Feed</h3>
          </div>
          
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-white/30 text-[#475569] text-[14px] font-semibold uppercase tracking-wider">
                  <th className="px-8 py-4">Timestamp</th>
                  <th className="px-8 py-4">IP Address</th>
                  <th className="px-8 py-4">Location</th>
                  <th className="px-8 py-4">Device</th>
                  <th className="px-8 py-4">Browser</th>
                  <th className="px-8 py-4">Target Path</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {logs.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-8 py-8 text-center text-[#475569]">No traffic logged yet. Visit a magic link to generate data.</td>
                  </tr>
                ) : (
                  logs.map(log => (
                    <tr key={log.id} className="hover:bg-black/5 transition-colors">
                      <td className="px-8 py-5 text-[#475569] text-[14px]">{new Date(log.timestamp).toLocaleString()}</td>
                      <td className="px-8 py-5 font-mono text-[#c0c1ff] text-[14px]">{log.ipAddress}</td>
                      <td className="px-8 py-5 text-[#0f172a] text-[14px] flex items-center gap-2">
                        <span className="material-symbols-outlined text-[16px] text-[#4edea3]">location_on</span>
                        {log.city !== 'Unknown' ? `${log.city}, ${log.country}` : log.country}
                      </td>
                      <td className="px-8 py-5">
                        <span className="px-3 py-1 bg-[#e2e8f0]/40 text-[#475569] border border-black/5 rounded-full text-[12px] font-semibold">
                          {log.device}
                        </span>
                      </td>
                      <td className="px-8 py-5 text-[#0f172a] text-[14px]">{log.browser}</td>
                      <td className="px-8 py-5 text-[#475569] text-[12px] max-w-[200px] truncate" title={log.path}>
                        {log.path}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>

      </div>
    </div>
  );
}
