import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import {
  Activity, Users, DollarSign, Download, Play, Smartphone, Monitor, ChevronRight, ArrowUp, ArrowDown, Loader2, Globe, TrendingUp
} from 'lucide-react';
import { useToast } from '../../components/feedback/ToastProvider';
import { StatCard } from '../dashboard/StatCard';
import { analyticsService } from '../../services/analyticsService';
import { logger } from '@/utils/logger';
import { cn } from '@/lib/utils';

interface AnalyticsViewProps {
  onNavigateTrack: (trackId: string) => void;
}

export const AnalyticsView: React.FC<AnalyticsViewProps> = ({ onNavigateTrack }) => {
  const { addToast } = useToast();
  const [dateRange, setDateRange] = useState('30d');
  const [stats, setStats] = useState<any>({});
  const [topTracks, setTopTracks] = useState<any[]>([]);
  const [trafficSources, setTrafficSources] = useState<any[]>([]);
  const [deviceStats, setDeviceStats] = useState<any>({});
  const [loading, setLoading] = useState(true);
  const [hoveredData, setHoveredData] = useState<any>(null);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const [global, tracks, sources, devices] = await Promise.all([
          analyticsService.getGlobalStats(dateRange),
          analyticsService.getTopTracks(dateRange),
          analyticsService.getTrafficSources(),
          analyticsService.getDeviceBreakdown(),
        ]);
        setStats(global);
        setTopTracks(tracks);
        setTrafficSources(sources);
        setDeviceStats(devices);
      } catch (e) {
        logger.error('Error loading analytics', { error: e });
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [dateRange]);

  const handleExport = (format: 'csv' | 'json') => {
    addToast(`Building ${format.toUpperCase()} archive...`, 'info');
    setTimeout(() => {
      const blob = new Blob([JSON.stringify(stats, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `veza-analytics-${dateRange}-${new Date().toISOString().split('T')[0]}.${format}`;
      a.click();
      addToast('Data packet exported successfully', 'success');
    }, 1500);
  };

  if (loading) return <div className="flex justify-center py-24"><Loader2 className="w-10 h-10 text-primary animate-spin" /></div>;

  return (
    <div className="space-y-8 pb-24 animate-fadeIn container py-8">
      {/* Dynamic Header */}
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-end gap-6 border-b border-white/5 pb-8">
        <div>
          <h1 className="text-4xl font-display font-bold text-white mb-2 flex items-center gap-3">
            <Activity className="text-primary w-8 h-8" /> NEURAL ANALYTICS
          </h1>
          <p className="text-muted-foreground font-mono text-xs tracking-[0.2em]">DEEP PACKET INSPECTION • AUDIENCE METRICS</p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <div className="bg-black/40 p-1 rounded-xl border border-white/10 backdrop-blur-md flex">
            {['7d', '30d', '90d', 'ytd'].map((range) => (
              <button
                key={range}
                onClick={() => setDateRange(range)}
                className={cn(
                  "px-4 py-2 rounded-lg text-[10px] font-bold uppercase tracking-widest transition-all",
                  dateRange === range ? "bg-primary text-black shadow-glow-cyan" : "text-muted-foreground hover:text-white"
                )}
              >
                {range}
              </button>
            ))}
          </div>

          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={() => handleExport('csv')} className="border-white/10 hover:border-primary/50">
              <Download className="w-4 h-4 mr-2" /> CSV
            </Button>
            <Button variant="primary" size="sm" onClick={() => handleExport('json')} className="shadow-glow-cyan">
              REPORT
            </Button>
          </div>
        </div>
      </div>

      {/* Primary KPI Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard label="Network Plays" value={stats.total_plays?.toLocaleString()} icon={<Play className="w-4 h-4" />} trend={stats.trends?.plays} color="cyan" sparklineData={stats.sparklines?.plays} />
        <StatCard label="Gross Revenue" value={`$${stats.total_revenue?.toLocaleString()}`} icon={<DollarSign className="w-4 h-4" />} trend={stats.trends?.revenue} color="gold" sparklineData={stats.sparklines?.revenue} />
        <StatCard label="Active Nodes" value={stats.followers?.toLocaleString()} icon={<Users className="w-4 h-4" />} trend={stats.trends?.followers} color="magenta" sparklineData={stats.sparklines?.followers} />
        <StatCard label="Profile Pulse" value={stats.profile_views?.toLocaleString()} icon={<TrendingUp className="w-4 h-4" />} trend={stats.trends?.views} color="red" sparklineData={stats.sparklines?.views} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Advanced Interactive Area Chart */}
        <Card variant="glass" className="lg:col-span-2 p-8 bg-black/40 border-white/5 relative overflow-hidden group">
          <div className="flex justify-between items-center mb-8 relative z-10">
            <div>
              <h3 className="text-xl font-bold text-white mb-1">Performance Dynamics</h3>
              <p className="text-xs text-muted-foreground font-mono">SCALAR TEMPORAL RESOLUTION</p>
            </div>
            <div className="flex gap-6 text-[10px] font-mono uppercase tracking-widest">
              <div className="flex items-center gap-2"><div className="w-2 h-2 rounded-full bg-primary" /> Plays</div>
              <div className="flex items-center gap-2"><div className="w-2 h-2 rounded-full bg-gold-500" /> Revenue</div>
            </div>
          </div>

          <div className="h-64 relative flex items-end">
            {/* Chart Background Grid */}
            <div className="absolute inset-0 grid grid-rows-4 w-full h-full pointer-events-none opacity-20">
              {[...Array(5)].map((_, i) => <div key={i} className="border-b border-white/10 w-full" />)}
            </div>

            {/* Functional Bars with tooltips on hover */}
            <div className="flex-1 flex items-end gap-1 h-full z-10 px-2">
              {Array.from({ length: 30 }).map((_, i) => {
                const val1 = Math.random() * 60 + 20;
                const val2 = Math.random() * 40 + 10;
                return (
                  <div key={i} className="flex-1 group/bar relative h-full flex flex-col justify-end gap-0.5 cursor-pointer"
                    onMouseEnter={() => setHoveredData({ index: i, val1, val2 })}>
                    <div className="w-full bg-gold-500/20 group-hover/bar:bg-gold-500/60 rounded-t-sm transition-all" style={{ height: `${val2}%` }} />
                    <div className="w-full bg-primary/20 group-hover/bar:bg-primary/60 rounded-t-sm transition-all shadow-glow-cyan" style={{ height: `${val1}%` }} />

                    {/* Floating Tooltip */}
                    {hoveredData?.index === i && (
                      <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-4 bg-black/90 border border-white/20 p-2 rounded text-[10px] font-mono whitespace-nowrap z-50 animate-fadeIn backdrop-blur-xl">
                        <div className="text-primary">PLAYS: {Math.floor(val1 * 1230)}</div>
                        <div className="text-gold-500">REV: ${(val2 * 42).toFixed(2)}</div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
          <div className="flex justify-between text-[10px] font-mono text-muted-foreground mt-4 px-2 uppercase tracking-tighter">
            <span>{dateRange} AGO</span>
            <span>REALTIME FEED</span>
            <span>PRESENT</span>
          </div>
        </Card>

        {/* Breakdown Panel */}
        <div className="space-y-6">
          <Card variant="glass" className="p-6 bg-black/40 border-white/5">
            <h3 className="font-bold text-white mb-6 text-sm uppercase tracking-widest flex items-center gap-2">
              <Globe className="w-4 h-4 text-magenta-500" /> Origins
            </h3>
            <div className="space-y-5">
              {trafficSources.map((src: any) => (
                <div key={src.label} className="group cursor-default">
                  <div className="flex justify-between text-xs mb-2">
                    <span className="text-muted-foreground group-hover:text-white transition-colors uppercase font-mono">{src.label}</span>
                    <span className="text-white font-bold">{src.val}%</span>
                  </div>
                  <div className="h-1.5 bg-white/5 rounded-full overflow-hidden">
                    <div className={cn("h-full transition-all duration-1000", src.color.replace('bg-kodo-', 'bg-'))} style={{ width: `${src.val}%` }} />
                  </div>
                </div>
              ))}
            </div>
          </Card>

          <Card variant="glass" className="p-6 bg-black/40 border-white/5">
            <h3 className="font-bold text-white mb-6 text-sm uppercase tracking-widest flex items-center gap-2">
              <Smartphone className="w-4 h-4 text-cyan-500" /> Platforms
            </h3>
            <div className="flex items-center justify-between gap-8 px-4">
              <div className="text-center group flex-1">
                <div className="w-12 h-12 rounded-2xl bg-white/5 flex items-center justify-center mx-auto mb-3 group-hover:bg-primary/10 transition-all border border-transparent group-hover:border-primary/20">
                  <Smartphone className="w-6 h-6 text-muted-foreground group-hover:text-primary transition-colors" />
                </div>
                <div className="text-2xl font-bold text-white">{deviceStats.mobile}%</div>
                <div className="text-[10px] text-muted-foreground uppercase font-mono mt-1">MOBILE</div>
              </div>
              <div className="w-px h-12 bg-white/10" />
              <div className="text-center group flex-1">
                <div className="w-12 h-12 rounded-2xl bg-white/5 flex items-center justify-center mx-auto mb-3 group-hover:bg-magenta-500/10 transition-all border border-transparent group-hover:border-magenta-500/20">
                  <Monitor className="w-6 h-6 text-muted-foreground group-hover:text-magenta-500 transition-colors" />
                </div>
                <div className="text-2xl font-bold text-white">{deviceStats.desktop}%</div>
                <div className="text-[10px] text-muted-foreground uppercase font-mono mt-1">NODE</div>
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* Top Performing Entities */}
      <Card variant="glass" className="bg-black/40 border-white/5 overflow-hidden p-0 relative group">
        <div className="absolute inset-x-0 bottom-0 h-[2px] bg-gradient-to-r from-transparent via-primary/40 to-transparent group-hover:via-primary transition-all opacity-50" />

        <div className="flex justify-between items-center p-6 border-b border-white/5 bg-white/2">
          <div>
            <h3 className="text-xl font-bold text-white">Top Frequency Nodes</h3>
            <p className="text-xs text-muted-foreground font-mono">SORTED BY PEAK VOLTAGE</p>
          </div>
          <Button variant="ghost" size="sm" className="hover:bg-white/5">FULL FEED</Button>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="text-[10px] text-muted-foreground uppercase tracking-[0.2em] border-b border-white/5 bg-black/20">
                <th className="py-4 pl-8">SIGNAL IDENTITY</th>
                <th className="py-4">PLAYS</th>
                <th className="py-4">DELTA</th>
                <th className="py-4">REVENUE</th>
                <th className="py-4 text-right pr-8">PROTOCOL</th>
              </tr>
            </thead>
            <tbody className="text-sm divide-y divide-white/5">
              {topTracks.map((track: any) => (
                <tr key={track.id} className="hover:bg-white/5 transition-all group">
                  <td className="py-5 pl-8">
                    <div className="font-bold text-white group-hover:text-primary transition-colors">{track.title}</div>
                    <div className="text-[10px] text-muted-foreground font-mono">TRACK_ID: {track.id.toUpperCase()}</div>
                  </td>
                  <td className="py-5 text-white font-mono">{track.plays.toLocaleString()}</td>
                  <td className="py-5">
                    <span className={cn("inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider border",
                      track.change >= 0 ? "text-lime-500 border-lime-500/20 bg-lime-500/10" : "text-red-500 border-red-500/20 bg-red-500/10")}>
                      {track.change >= 0 ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />}
                      {Math.abs(track.change)}%
                    </span>
                  </td>
                  <td className="py-5 font-bold text-gold-500">${track.revenue.toFixed(2)}</td>
                  <td className="py-5 text-right pr-8">
                    <Button variant="outline" size="sm" onClick={() => onNavigateTrack(track.id)}
                      className="bg-black/40 border-white/10 hover:border-primary/50 group-hover:shadow-glow-cyan transition-all">
                      INSPECT <ChevronRight className="w-4 h-4 ml-1" />
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
};
