import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useAuthStore } from '../../store/authStore';
import { BarChart, Server, Layers } from 'lucide-react';

export const UsageAnalytics = () => {
  const { idToken } = useAuthStore();
  const [usageData, setUsageData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUsage = async () => {
      try {
        const response = await axios.get('http://localhost:8000/api/subscriber/usage', {
          headers: { Authorization: `Bearer ${idToken}` }
        });
        setUsageData(response.data);
      } catch (error) {
        console.error("Failed to fetch usage data:", error);
      } finally {
        setLoading(false);
      }
    };

    if (idToken) fetchUsage();
  }, [idToken]);

  if (loading) return <div className="text-gray-400">Loading analytics...</div>;

  return (
    <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-white mb-2">AI Usage Analytics</h1>
        <p className="text-gray-400">Monitor your model inference and vector search operations.</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-gradient-to-br from-blue-900/40 to-purple-900/40 border border-blue-500/20 p-6 rounded-2xl">
          <div className="flex items-center gap-3 mb-2">
            <BarChart className="text-blue-400" />
            <h3 className="text-gray-300 font-medium">Total Tokens</h3>
          </div>
          <p className="text-4xl font-black text-white">{usageData?.total_tokens?.toLocaleString() || 0}</p>
        </div>
        
        <div className="bg-gradient-to-br from-emerald-900/40 to-teal-900/40 border border-emerald-500/20 p-6 rounded-2xl">
          <div className="flex items-center gap-3 mb-2">
            <Server className="text-emerald-400" />
            <h3 className="text-gray-300 font-medium">Estimated Cost</h3>
          </div>
          <p className="text-4xl font-black text-white">${usageData?.total_cost?.toFixed(2) || '0.00'}</p>
        </div>

        <div className="bg-gradient-to-br from-amber-900/40 to-orange-900/40 border border-amber-500/20 p-6 rounded-2xl">
          <div className="flex items-center gap-3 mb-2">
            <Layers className="text-amber-400" />
            <h3 className="text-gray-300 font-medium">Vector Searches</h3>
          </div>
          <p className="text-4xl font-black text-white">4,291</p>
        </div>
      </div>

      <div className="bg-gray-800/40 border border-gray-700/50 rounded-2xl p-6 backdrop-blur-md">
        <h3 className="text-xl font-semibold text-white mb-6">Recent Inference Logs</h3>
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm text-gray-400">
            <thead className="text-xs text-gray-500 uppercase bg-gray-900/50 border-b border-gray-700">
              <tr>
                <th className="px-6 py-4 rounded-tl-xl">Model</th>
                <th className="px-6 py-4">Tokens Used</th>
                <th className="px-6 py-4">Cost ($)</th>
                <th className="px-6 py-4 rounded-tr-xl">Timestamp</th>
              </tr>
            </thead>
            <tbody>
              {usageData?.recent_logs?.length > 0 ? (
                usageData.recent_logs.map((log, idx) => (
                  <tr key={idx} className="border-b border-gray-700/50 hover:bg-gray-800/50 transition-colors">
                    <td className="px-6 py-4 font-medium text-gray-200">
                      <span className="bg-blue-500/10 text-blue-400 px-2 py-1 rounded border border-blue-500/20">
                        {log.model}
                      </span>
                    </td>
                    <td className="px-6 py-4">{log.tokens.toLocaleString()}</td>
                    <td className="px-6 py-4 text-emerald-400">${log.cost.toFixed(4)}</td>
                    <td className="px-6 py-4">{new Date(log.timestamp).toLocaleString()}</td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan="4" className="px-6 py-8 text-center text-gray-500">
                    No recent activity found.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};
