'use client';

import { useState, useEffect } from 'react';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import { 
  BarChart3, 
  Eye, 
  Users, 
  Trophy, 
  TrendingUp, 
  Calendar,
  DollarSign,
  Target,
  ArrowUpRight,
  ArrowDownRight,
  ExternalLink,
  Loader2
} from 'lucide-react';
import Link from 'next/link';

interface SponsorshipMetrics {
  impressions: number;
  impressionsChange: number;
  uniqueViewers: number;
  viewersChange: number;
  races: number;
  drivers: number;
  exposure: number;
  exposureChange: number;
}

interface SponsoredLeague {
  id: string;
  name: string;
  tier: 'main' | 'secondary';
  drivers: number;
  races: number;
  impressions: number;
  status: 'active' | 'upcoming' | 'completed';
}

interface SponsorDashboardData {
  sponsorId: string;
  sponsorName: string;
  metrics: SponsorshipMetrics;
  sponsoredLeagues: SponsoredLeague[];
  investment: {
    activeSponsorships: number;
    totalInvestment: number;
    costPerThousandViews: number;
  };
}


function MetricCard({ 
  title, 
  value, 
  change, 
  icon: Icon,
  suffix = '',
}: { 
  title: string; 
  value: number | string; 
  change?: number;
  icon: typeof Eye;
  suffix?: string;
}) {
  const isPositive = change && change > 0;
  const isNegative = change && change < 0;

  return (
    <Card className="p-4">
      <div className="flex items-start justify-between mb-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-blue/10">
          <Icon className="w-5 h-5 text-primary-blue" />
        </div>
        {change !== undefined && (
          <div className={`flex items-center gap-1 text-sm ${
            isPositive ? 'text-performance-green' : isNegative ? 'text-racing-red' : 'text-gray-400'
          }`}>
            {isPositive ? <ArrowUpRight className="w-4 h-4" /> : isNegative ? <ArrowDownRight className="w-4 h-4" /> : null}
            {Math.abs(change)}%
          </div>
        )}
      </div>
      <div className="text-2xl font-bold text-white mb-1">
        {typeof value === 'number' ? value.toLocaleString() : value}{suffix}
      </div>
      <div className="text-sm text-gray-400">{title}</div>
    </Card>
  );
}

function LeagueRow({ league }: { league: SponsoredLeague }) {
  const statusColors = {
    active: 'bg-performance-green/20 text-performance-green',
    upcoming: 'bg-warning-amber/20 text-warning-amber',
    completed: 'bg-gray-500/20 text-gray-400',
  };

  const tierColors = {
    main: 'bg-primary-blue/20 text-primary-blue border-primary-blue/30',
    secondary: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
  };

  return (
    <div className="flex items-center justify-between p-4 border-b border-charcoal-outline last:border-b-0 hover:bg-iron-gray/30 transition-colors">
      <div className="flex items-center gap-4">
        <div className={`px-2 py-1 rounded text-xs font-medium border ${tierColors[league.tier]}`}>
          {league.tier === 'main' ? 'Main Sponsor' : 'Secondary'}
        </div>
        <div>
          <div className="font-medium text-white">{league.name}</div>
          <div className="text-sm text-gray-400">
            {league.drivers} drivers • {league.races} races
          </div>
        </div>
      </div>
      <div className="flex items-center gap-6">
        <div className="text-right">
          <div className="text-sm font-medium text-white">{league.impressions.toLocaleString()}</div>
          <div className="text-xs text-gray-500">impressions</div>
        </div>
        <div className={`px-2 py-1 rounded text-xs font-medium ${statusColors[league.status]}`}>
          {league.status}
        </div>
        <Link href={`/leagues/${league.id}`}>
          <Button variant="secondary" className="text-xs">
            <ExternalLink className="w-3 h-3 mr-1" />
            View
          </Button>
        </Link>
      </div>
    </div>
  );
}

export default function SponsorDashboardPage() {
  const [timeRange, setTimeRange] = useState<'7d' | '30d' | '90d' | 'all'>('30d');
  const [data, setData] = useState<SponsorDashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchDashboard() {
      try {
        const response = await fetch('/api/sponsors/dashboard');
        if (response.ok) {
          const dashboardData: SponsorDashboardData = await response.json();
          setData(dashboardData);
        } else {
          setError('Failed to load sponsor dashboard');
        }
      } catch {
        setError('Failed to load sponsor dashboard');
      } finally {
        setLoading(false);
      }
    }

    fetchDashboard();
  }, []);

  if (loading) {
    return (
      <div className="max-w-7xl mx-auto py-8 px-4 flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-primary-blue" />
      </div>
    );
  }

  if (!data) {
    return (
      <div className="max-w-7xl mx-auto py-8 px-4">
        <div className="rounded-lg bg-warning-amber/10 border border-warning-amber/30 p-4">
          <p className="text-sm text-warning-amber">
            {error ?? 'No sponsor dashboard data available yet.'}
          </p>
        </div>
      </div>
    );
  }

  const dashboardData = data;

  return (
    <div className="max-w-7xl mx-auto py-8 px-4">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white">Sponsor Dashboard</h1>
          <p className="text-gray-400">Track your sponsorship performance and exposure</p>
        </div>
        <div className="flex items-center gap-2">
          {(['7d', '30d', '90d', 'all'] as const).map((range) => (
            <button
              key={range}
              onClick={() => setTimeRange(range)}
              className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
                timeRange === range
                  ? 'bg-primary-blue text-white'
                  : 'bg-iron-gray/50 text-gray-400 hover:bg-iron-gray'
              }`}
            >
              {range === 'all' ? 'All Time' : range}
            </button>
          ))}
        </div>
      </div>

      {/* Metrics Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <MetricCard
          title="Total Impressions"
          value={dashboardData.metrics.impressions}
          change={dashboardData.metrics.impressionsChange}
          icon={Eye}
        />
        <MetricCard
          title="Unique Viewers"
          value={dashboardData.metrics.uniqueViewers}
          change={dashboardData.metrics.viewersChange}
          icon={Users}
        />
        <MetricCard
          title="Exposure Score"
          value={dashboardData.metrics.exposure}
          change={dashboardData.metrics.exposureChange}
          icon={Target}
          suffix="%"
        />
        <MetricCard
          title="Active Drivers"
          value={dashboardData.metrics.drivers}
          icon={Trophy}
        />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Sponsored Leagues */}
        <div className="lg:col-span-2">
          <Card>
            <div className="flex items-center justify-between p-4 border-b border-charcoal-outline">
              <h2 className="text-lg font-semibold text-white">Sponsored Leagues</h2>
              <Link href="/leagues">
                <Button variant="secondary" className="text-sm">
                  Browse Leagues
                </Button>
              </Link>
            </div>
            <div>
              {dashboardData.sponsoredLeagues.length > 0 ? (
                dashboardData.sponsoredLeagues.map((league) => (
                  <LeagueRow key={league.id} league={league} />
                ))
              ) : (
                <div className="p-8 text-center text-gray-400">
                  <p>No active sponsorships yet.</p>
                  <Link href="/leagues" className="text-primary-blue hover:underline mt-2 inline-block">
                    Browse leagues to sponsor
                  </Link>
                </div>
              )}
            </div>
          </Card>
        </div>

        {/* Quick Stats & Actions */}
        <div className="space-y-6">
          {/* Investment Summary */}
          <Card className="p-4">
            <h3 className="text-lg font-semibold text-white mb-4">Investment Summary</h3>
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-gray-400">Active Sponsorships</span>
                <span className="font-medium text-white">{dashboardData.investment.activeSponsorships}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-gray-400">Total Investment</span>
                <span className="font-medium text-white">${dashboardData.investment.totalInvestment.toLocaleString()}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-gray-400">Cost per 1K Views</span>
                <span className="font-medium text-performance-green">${dashboardData.investment.costPerThousandViews.toFixed(2)}</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-gray-400">Next Payment</span>
                <span className="font-medium text-white">Dec 15, 2025</span>
              </div>
            </div>
          </Card>

          {/* Recent Activity */}
          <Card className="p-4">
            <h3 className="text-lg font-semibold text-white mb-4">Recent Activity</h3>
            <div className="space-y-3">
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 rounded-full bg-performance-green mt-2" />
                <div>
                  <p className="text-sm text-white">GT3 Pro Championship race completed</p>
                  <p className="text-xs text-gray-500">2 hours ago • 1,240 views</p>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 rounded-full bg-primary-blue mt-2" />
                <div>
                  <p className="text-sm text-white">New driver joined Endurance Masters</p>
                  <p className="text-xs text-gray-500">5 hours ago</p>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <div className="w-2 h-2 rounded-full bg-warning-amber mt-2" />
                <div>
                  <p className="text-sm text-white">Touring Car Cup season starting soon</p>
                  <p className="text-xs text-gray-500">1 day ago</p>
                </div>
              </div>
            </div>
          </Card>

          {/* Quick Actions */}
          <Card className="p-4">
            <h3 className="text-lg font-semibold text-white mb-4">Quick Actions</h3>
            <div className="space-y-2">
              <Button variant="secondary" className="w-full justify-start">
                <BarChart3 className="w-4 h-4 mr-2" />
                View Detailed Analytics
              </Button>
              <Link href="/sponsor/billing" className="block">
                <Button variant="secondary" className="w-full justify-start">
                  <DollarSign className="w-4 h-4 mr-2" />
                  Manage Payments
                </Button>
              </Link>
              <Link href="/leagues" className="block">
                <Button variant="secondary" className="w-full justify-start">
                  <Target className="w-4 h-4 mr-2" />
                  Find New Leagues
                </Button>
              </Link>
            </div>
          </Card>
        </div>
      </div>

      {/* Alpha Notice */}
      <div className="mt-8 rounded-lg bg-warning-amber/10 border border-warning-amber/30 p-4">
        <p className="text-xs text-gray-400">
          <strong className="text-warning-amber">Alpha Note:</strong> Sponsor analytics data shown here is demonstration-only.
          Real analytics will be available when the sponsorship system is fully implemented.
        </p>
      </div>
    </div>
  );
}