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,
} from 'lucide-react';
import { useToast } from '../../context/ToastContext';
import { StatCard } from '../dashboard/StatCard';
import { analyticsService } from '../../services/analyticsService';
import { logger } from '@/utils/logger';

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);

  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 data', {
          error: e instanceof Error ? e.message : String(e),
          stack: e instanceof Error ? e.stack : undefined,
          dateRange,
        });
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [dateRange]);

  const handleExport = () => {
    addToast('Exporting Analytics Report...', 'info');
  };

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

  return (
    <div className="space-y-8 pb-20 animate-fadeIn">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-end border-b border-kodo-steel/50 pb-6 gap-4">
        <div>
          <h1 className="text-3xl font-display font-bold text-white mb-2">
            ANALYTICS DASHBOARD
          </h1>
          <p className="text-gray-400 font-mono text-sm">
            Performance insights and audience growth.
          </p>
        </div>

        <div className="flex gap-3">
          <div className="bg-kodo-ink p-1 rounded-lg border border-kodo-steel flex">
            {['7d', '30d', '90d', 'YTD'].map((range) => (
              <button
                key={range}
                onClick={() => setDateRange(range)}
                className={`px-3 py-1.5 rounded text-xs font-bold uppercase transition-colors ${dateRange === range ? 'bg-kodo-slate text-white' : 'text-gray-500 hover:text-white'}`}
              >
                {range}
              </button>
            ))}
          </div>
          <Button
            variant="secondary"
            icon={<Download className="w-4 h-4" />}
            onClick={handleExport}
          >
            EXPORT
          </Button>
        </div>
      </div>

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

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Main Chart */}
        <Card variant="default" className="lg:col-span-2">
          <div className="flex justify-between items-center mb-6">
            <h3 className="font-bold text-white text-lg">
              Performance Over Time
            </h3>
            <div className="flex gap-4 text-xs">
              <div className="flex items-center gap-2 text-gray-400">
                <div className="w-3 h-3 bg-kodo-cyan rounded-full"></div> Plays
              </div>
              <div className="flex items-center gap-2 text-gray-400">
                <div className="w-3 h-3 bg-kodo-gold rounded-full"></div> Sales
              </div>
            </div>
          </div>
          <div className="h-64 flex items-end gap-2 px-4 pb-4 border-b border-white/5">
            {Array.from({ length: 12 }).map((_, i) => (
              <div
                key={i}
                className="flex-1 flex flex-col justify-end gap-1 h-full group cursor-pointer"
              >
                <div
                  className="w-full bg-kodo-gold/30 hover:bg-kodo-gold transition-all rounded-t"
                  style={{ height: `${Math.random() * 40}%` }}
                ></div>
                <div
                  className="w-full bg-kodo-cyan/30 hover:bg-kodo-cyan transition-all rounded-t"
                  style={{ height: `${Math.random() * 60 + 20}%` }}
                ></div>
              </div>
            ))}
          </div>
          <div className="flex justify-between text-xs text-gray-500 mt-2 px-2">
            <span>Start</span>
            <span>End</span>
          </div>
        </Card>

        {/* Traffic Sources */}
        <div className="space-y-6">
          <Card variant="default">
            <h3 className="font-bold text-white mb-4">Traffic Sources</h3>
            <div className="space-y-4">
              {trafficSources.map((src: any) => (
                <div key={src.label}>
                  <div className="flex justify-between text-xs text-gray-400 mb-1">
                    <span>{src.label}</span>
                    <span>{src.val}%</span>
                  </div>
                  <div className="h-2 bg-kodo-steel rounded-full overflow-hidden">
                    <div
                      className={`h-full ${src.color}`}
                      style={{ width: `${src.val}%` }}
                    ></div>
                  </div>
                </div>
              ))}
            </div>
          </Card>

          <Card variant="default">
            <h3 className="font-bold text-white mb-4">Device Breakdown</h3>
            <div className="flex justify-around text-center">
              <div>
                <Smartphone className="w-8 h-8 text-kodo-cyan mx-auto mb-2" />
                <div className="text-2xl font-bold text-white">
                  {deviceStats.mobile}%
                </div>
                <div className="text-xs text-gray-500">Mobile</div>
              </div>
              <div>
                <Monitor className="w-8 h-8 text-kodo-magenta mx-auto mb-2" />
                <div className="text-2xl font-bold text-white">
                  {deviceStats.desktop}%
                </div>
                <div className="text-xs text-gray-500">Desktop</div>
              </div>
            </div>
          </Card>
        </div>
      </div>

      {/* Top Tracks Table */}
      <Card variant="default">
        <div className="flex justify-between items-center mb-6">
          <h3 className="font-bold text-white text-lg">Top Tracks</h3>
          <Button variant="ghost" size="sm">
            View All
          </Button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="text-xs text-gray-500 uppercase border-b border-kodo-steel/50">
                <th className="pb-3 pl-4">Track Name</th>
                <th className="pb-3">Plays</th>
                <th className="pb-3">Trend</th>
                <th className="pb-3">Revenue</th>
                <th className="pb-3 text-right pr-4">Action</th>
              </tr>
            </thead>
            <tbody className="text-sm">
              {topTracks.map((track: any) => (
                <tr
                  key={track.id}
                  className="border-b border-kodo-steel/20 hover:bg-white/5 transition-colors group"
                >
                  <td className="py-4 pl-4 font-bold text-white">
                    {track.title}
                  </td>
                  <td className="py-4 text-gray-300">
                    {track.plays.toLocaleString()}
                  </td>
                  <td className="py-4">
                    <span
                      className={`flex items-center gap-1 text-xs font-bold ${track.change >= 0 ? 'text-kodo-lime' : 'text-kodo-red'}`}
                    >
                      {track.change >= 0 ? (
                        <ArrowUp className="w-3 h-3" />
                      ) : (
                        <ArrowDown className="w-3 h-3" />
                      )}
                      {Math.abs(track.change)}%
                    </span>
                  </td>
                  <td className="py-4 font-mono text-kodo-cyan">
                    ${track.revenue.toFixed(2)}
                  </td>
                  <td className="py-4 text-right pr-4">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onNavigateTrack(track.id)}
                    >
                      Details <ChevronRight className="w-4 h-4 ml-1" />
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
};
