'use client';

import { useState } from 'react';
import { useParams, useSearchParams } from 'next/navigation';
import { motion, useReducedMotion } from 'framer-motion';
import Link from 'next/link';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import { siteConfig } from '@/lib/siteConfig';
import {
  Trophy,
  Users,
  Calendar,
  Eye,
  TrendingUp,
  Download,
  Image as ImageIcon,
  ExternalLink,
  ChevronRight,
  Star,
  Clock,
  CheckCircle2,
  Flag,
  Car,
  BarChart3,
  ArrowUpRight,
  Megaphone,
  CreditCard,
  FileText
} from 'lucide-react';

// Mock data for league detail
const MOCK_LEAGUE = {
  id: 'league-1',
  name: 'GT3 Masters Championship',
  game: 'iRacing',
  tier: 'premium' as const,
  season: 'Season 3',
  description: 'Premier GT3 racing with top-tier drivers competing across the world\'s most iconic circuits. Weekly broadcasts and an active community make this league a premium sponsorship opportunity.',
  drivers: 48,
  races: 12,
  completedRaces: 8,
  totalImpressions: 45200,
  avgViewsPerRace: 5650,
  engagement: 4.2,
  rating: 4.8,
  seasonStatus: 'active' as const,
  seasonDates: { start: '2025-10-01', end: '2026-02-28' },
  nextRace: { name: 'Spa-Francorchamps', date: '2025-12-20' },
  sponsorSlots: {
    main: { 
      available: true, 
      price: 1200, 
      benefits: [
        'Primary logo placement on all liveries',
        'League page header banner',
        'Race results page branding',
        'Social media feature posts',
        'Newsletter sponsor spot',
      ]
    },
    secondary: { 
      available: 1, 
      total: 2, 
      price: 400,
      benefits: [
        'Secondary logo on liveries',
        'League page sidebar placement',
        'Race results mention',
        'Social media mentions',
      ]
    },
  },
};

const MOCK_DRIVERS = [
  { id: 'd1', name: 'Max Verstappen', country: 'NL', position: 1, races: 8, impressions: 4200, team: 'Red Bull Racing' },
  { id: 'd2', name: 'Lewis Hamilton', country: 'GB', position: 2, races: 8, impressions: 3980, team: 'Mercedes AMG' },
  { id: 'd3', name: 'Charles Leclerc', country: 'MC', position: 3, races: 8, impressions: 3750, team: 'Ferrari' },
  { id: 'd4', name: 'Lando Norris', country: 'GB', position: 4, races: 7, impressions: 3420, team: 'McLaren' },
  { id: 'd5', name: 'Carlos Sainz', country: 'ES', position: 5, races: 8, impressions: 3100, team: 'Ferrari' },
];

const MOCK_RACES = [
  { id: 'r1', name: 'Spa-Francorchamps', date: '2025-12-20', views: 0, status: 'upcoming' },
  { id: 'r2', name: 'Monza', date: '2025-12-08', views: 5800, status: 'completed' },
  { id: 'r3', name: 'Silverstone', date: '2025-11-24', views: 6200, status: 'completed' },
  { id: 'r4', name: 'Nürburgring', date: '2025-11-10', views: 5400, status: 'completed' },
];

type TabType = 'overview' | 'drivers' | 'races' | 'sponsor';

export default function SponsorLeagueDetailPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const shouldReduceMotion = useReducedMotion();
  
  const showSponsorAction = searchParams.get('action') === 'sponsor';
  const [activeTab, setActiveTab] = useState<TabType>(showSponsorAction ? 'sponsor' : 'overview');
  const [selectedTier, setSelectedTier] = useState<'main' | 'secondary'>('main');

  const league = MOCK_LEAGUE;
  const tierConfig = {
    premium: { color: 'text-yellow-400', bgColor: 'bg-yellow-500/10', border: 'border-yellow-500/30' },
    standard: { color: 'text-primary-blue', bgColor: 'bg-primary-blue/10', border: 'border-primary-blue/30' },
    starter: { color: 'text-gray-400', bgColor: 'bg-gray-500/10', border: 'border-gray-500/30' },
  };

  const config = tierConfig[league.tier];

  return (
    <div className="max-w-7xl mx-auto py-8 px-4">
      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm text-gray-400 mb-6">
        <Link href="/sponsor/dashboard" className="hover:text-white transition-colors">Dashboard</Link>
        <ChevronRight className="w-4 h-4" />
        <Link href="/sponsor/leagues" className="hover:text-white transition-colors">Leagues</Link>
        <ChevronRight className="w-4 h-4" />
        <span className="text-white">{league.name}</span>
      </div>

      {/* Header */}
      <div className="flex flex-col lg:flex-row lg:items-start justify-between gap-6 mb-8">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-2">
            <span className={`px-3 py-1 rounded-full text-sm font-medium capitalize ${config.bgColor} ${config.color} border ${config.border}`}>
              ⭐ {league.tier}
            </span>
            <span className="px-3 py-1 rounded-full text-sm font-medium bg-performance-green/10 text-performance-green">
              Active Season
            </span>
            <div className="flex items-center gap-1 px-2 py-1 rounded bg-iron-gray/50">
              <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
              <span className="text-sm font-medium text-white">{league.rating}</span>
            </div>
          </div>
          <h1 className="text-3xl font-bold text-white mb-2">{league.name}</h1>
          <p className="text-gray-400 mb-4">{league.game} • {league.season} • {league.completedRaces}/{league.races} races completed</p>
          <p className="text-gray-400 max-w-2xl">{league.description}</p>
        </div>
        
        <div className="flex flex-col sm:flex-row gap-3">
          <Link href={`/leagues/${league.id}`}>
            <Button variant="secondary">
              <ExternalLink className="w-4 h-4 mr-2" />
              View League
            </Button>
          </Link>
          {(league.sponsorSlots.main.available || league.sponsorSlots.secondary.available > 0) && (
            <Button variant="primary" onClick={() => setActiveTab('sponsor')}>
              <Megaphone className="w-4 h-4 mr-2" />
              Become a Sponsor
            </Button>
          )}
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-8">
        <motion.div
          initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary-blue/10">
                <Eye className="w-5 h-5 text-primary-blue" />
              </div>
              <div>
                <div className="text-xl font-bold text-white">{league.totalImpressions.toLocaleString()}</div>
                <div className="text-xs text-gray-400">Total Views</div>
              </div>
            </div>
          </Card>
        </motion.div>
        <motion.div
          initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
        >
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-performance-green/10">
                <TrendingUp className="w-5 h-5 text-performance-green" />
              </div>
              <div>
                <div className="text-xl font-bold text-white">{league.avgViewsPerRace.toLocaleString()}</div>
                <div className="text-xs text-gray-400">Avg/Race</div>
              </div>
            </div>
          </Card>
        </motion.div>
        <motion.div
          initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
        >
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-purple-500/10">
                <Users className="w-5 h-5 text-purple-400" />
              </div>
              <div>
                <div className="text-xl font-bold text-white">{league.drivers}</div>
                <div className="text-xs text-gray-400">Drivers</div>
              </div>
            </div>
          </Card>
        </motion.div>
        <motion.div
          initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
        >
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-warning-amber/10">
                <BarChart3 className="w-5 h-5 text-warning-amber" />
              </div>
              <div>
                <div className="text-xl font-bold text-white">{league.engagement}%</div>
                <div className="text-xs text-gray-400">Engagement</div>
              </div>
            </div>
          </Card>
        </motion.div>
        <motion.div
          initial={shouldReduceMotion ? {} : { opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
        >
          <Card className="p-4">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-racing-red/10">
                <Calendar className="w-5 h-5 text-racing-red" />
              </div>
              <div>
                <div className="text-xl font-bold text-white">{league.races - league.completedRaces}</div>
                <div className="text-xs text-gray-400">Races Left</div>
              </div>
            </div>
          </Card>
        </motion.div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-6 border-b border-charcoal-outline overflow-x-auto">
        {(['overview', 'drivers', 'races', 'sponsor'] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-3 text-sm font-medium capitalize transition-colors border-b-2 -mb-px whitespace-nowrap ${
              activeTab === tab
                ? 'text-primary-blue border-primary-blue'
                : 'text-gray-400 border-transparent hover:text-white'
            }`}
          >
            {tab === 'sponsor' ? '🎯 Become a Sponsor' : tab}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card className="p-5">
            <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
              <Trophy className="w-5 h-5 text-primary-blue" />
              League Information
            </h3>
            <div className="space-y-3">
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Platform</span>
                <span className="text-white font-medium">{league.game}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Season</span>
                <span className="text-white font-medium">{league.season}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Duration</span>
                <span className="text-white font-medium">Oct 2025 - Feb 2026</span>
              </div>
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Drivers</span>
                <span className="text-white font-medium">{league.drivers}</span>
              </div>
              <div className="flex justify-between py-2">
                <span className="text-gray-400">Races</span>
                <span className="text-white font-medium">{league.races}</span>
              </div>
            </div>
          </Card>

          <Card className="p-5">
            <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
              <TrendingUp className="w-5 h-5 text-performance-green" />
              Sponsorship Value
            </h3>
            <div className="space-y-3">
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Total Season Views</span>
                <span className="text-white font-medium">{league.totalImpressions.toLocaleString()}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Projected Total</span>
                <span className="text-white font-medium">{Math.round(league.avgViewsPerRace * league.races).toLocaleString()}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Main Sponsor CPM</span>
                <span className="text-performance-green font-medium">
                  ${((league.sponsorSlots.main.price / (league.avgViewsPerRace * league.races)) * 1000).toFixed(2)}
                </span>
              </div>
              <div className="flex justify-between py-2 border-b border-charcoal-outline/50">
                <span className="text-gray-400">Engagement Rate</span>
                <span className="text-white font-medium">{league.engagement}%</span>
              </div>
              <div className="flex justify-between py-2">
                <span className="text-gray-400">League Rating</span>
                <div className="flex items-center gap-1">
                  <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
                  <span className="text-white font-medium">{league.rating}/5.0</span>
                </div>
              </div>
            </div>
          </Card>

          {/* Next Race */}
          {league.nextRace && (
            <Card className="p-5 lg:col-span-2">
              <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <Flag className="w-5 h-5 text-warning-amber" />
                Next Race
              </h3>
              <div className="flex items-center justify-between p-4 rounded-lg bg-warning-amber/10 border border-warning-amber/30">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-lg bg-warning-amber/20 flex items-center justify-center">
                    <Flag className="w-6 h-6 text-warning-amber" />
                  </div>
                  <div>
                    <p className="font-semibold text-white text-lg">{league.nextRace.name}</p>
                    <p className="text-sm text-gray-400">{league.nextRace.date}</p>
                  </div>
                </div>
                <Button variant="secondary">
                  View Schedule
                </Button>
              </div>
            </Card>
          )}
        </div>
      )}

      {activeTab === 'drivers' && (
        <Card>
          <div className="p-4 border-b border-charcoal-outline">
            <h3 className="text-lg font-semibold text-white">Championship Standings</h3>
            <p className="text-sm text-gray-400">Top drivers carrying sponsor branding</p>
          </div>
          <div className="divide-y divide-charcoal-outline/50">
            {MOCK_DRIVERS.map((driver) => (
              <div key={driver.id} className="flex items-center justify-between p-4 hover:bg-iron-gray/30 transition-colors">
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 rounded-full bg-iron-gray flex items-center justify-center text-lg font-bold text-white">
                    {driver.position}
                  </div>
                  <div>
                    <div className="font-medium text-white">{driver.name}</div>
                    <div className="text-sm text-gray-500">{driver.team} • {driver.country}</div>
                  </div>
                </div>
                <div className="flex items-center gap-6">
                  <div className="text-right">
                    <div className="font-medium text-white">{driver.races}</div>
                    <div className="text-xs text-gray-500">races</div>
                  </div>
                  <div className="text-right">
                    <div className="font-semibold text-white">{driver.impressions.toLocaleString()}</div>
                    <div className="text-xs text-gray-500">views</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {activeTab === 'races' && (
        <Card>
          <div className="p-4 border-b border-charcoal-outline">
            <h3 className="text-lg font-semibold text-white">Race Calendar</h3>
            <p className="text-sm text-gray-400">Season schedule with view statistics</p>
          </div>
          <div className="divide-y divide-charcoal-outline/50">
            {MOCK_RACES.map((race) => (
              <div key={race.id} className="flex items-center justify-between p-4 hover:bg-iron-gray/30 transition-colors">
                <div className="flex items-center gap-4">
                  <div className={`w-3 h-3 rounded-full ${
                    race.status === 'completed' ? 'bg-performance-green' : 'bg-warning-amber'
                  }`} />
                  <div>
                    <div className="font-medium text-white">{race.name}</div>
                    <div className="text-sm text-gray-500">{race.date}</div>
                  </div>
                </div>
                <div className="flex items-center gap-4">
                  {race.status === 'completed' ? (
                    <div className="text-right">
                      <div className="font-semibold text-white">{race.views.toLocaleString()}</div>
                      <div className="text-xs text-gray-500">views</div>
                    </div>
                  ) : (
                    <span className="px-3 py-1 rounded-full text-xs font-medium bg-warning-amber/20 text-warning-amber">
                      Upcoming
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </Card>
      )}

      {activeTab === 'sponsor' && (
        <div className="space-y-6">
          {/* Tier Selection */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Main Sponsor */}
            <Card 
              className={`p-5 cursor-pointer transition-all ${
                selectedTier === 'main' 
                  ? 'border-primary-blue ring-2 ring-primary-blue/20' 
                  : 'hover:border-charcoal-outline/80'
              } ${!league.sponsorSlots.main.available ? 'opacity-60' : ''}`}
              onClick={() => league.sponsorSlots.main.available && setSelectedTier('main')}
            >
              <div className="flex items-start justify-between mb-4">
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <Trophy className="w-5 h-5 text-yellow-400" />
                    <h3 className="text-lg font-semibold text-white">Main Sponsor</h3>
                  </div>
                  <p className="text-sm text-gray-400">Primary branding position</p>
                </div>
                {league.sponsorSlots.main.available ? (
                  <span className="px-2 py-1 rounded text-xs font-medium bg-performance-green/20 text-performance-green">
                    Available
                  </span>
                ) : (
                  <span className="px-2 py-1 rounded text-xs font-medium bg-gray-500/20 text-gray-400">
                    Filled
                  </span>
                )}
              </div>
              
              <div className="text-3xl font-bold text-white mb-4">
                ${league.sponsorSlots.main.price}
                <span className="text-sm font-normal text-gray-500">/season</span>
              </div>

              <ul className="space-y-2 mb-4">
                {league.sponsorSlots.main.benefits.map((benefit, i) => (
                  <li key={i} className="flex items-center gap-2 text-sm text-gray-300">
                    <CheckCircle2 className="w-4 h-4 text-performance-green flex-shrink-0" />
                    {benefit}
                  </li>
                ))}
              </ul>

              {selectedTier === 'main' && league.sponsorSlots.main.available && (
                <div className="w-4 h-4 rounded-full bg-primary-blue absolute top-4 right-4 flex items-center justify-center">
                  <CheckCircle2 className="w-3 h-3 text-white" />
                </div>
              )}
            </Card>

            {/* Secondary Sponsor */}
            <Card 
              className={`p-5 cursor-pointer transition-all ${
                selectedTier === 'secondary' 
                  ? 'border-primary-blue ring-2 ring-primary-blue/20' 
                  : 'hover:border-charcoal-outline/80'
              } ${league.sponsorSlots.secondary.available === 0 ? 'opacity-60' : ''}`}
              onClick={() => league.sponsorSlots.secondary.available > 0 && setSelectedTier('secondary')}
            >
              <div className="flex items-start justify-between mb-4">
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <Star className="w-5 h-5 text-purple-400" />
                    <h3 className="text-lg font-semibold text-white">Secondary Sponsor</h3>
                  </div>
                  <p className="text-sm text-gray-400">Supporting branding position</p>
                </div>
                {league.sponsorSlots.secondary.available > 0 ? (
                  <span className="px-2 py-1 rounded text-xs font-medium bg-performance-green/20 text-performance-green">
                    {league.sponsorSlots.secondary.available}/{league.sponsorSlots.secondary.total} Available
                  </span>
                ) : (
                  <span className="px-2 py-1 rounded text-xs font-medium bg-gray-500/20 text-gray-400">
                    Full
                  </span>
                )}
              </div>
              
              <div className="text-3xl font-bold text-white mb-4">
                ${league.sponsorSlots.secondary.price}
                <span className="text-sm font-normal text-gray-500">/season</span>
              </div>

              <ul className="space-y-2 mb-4">
                {league.sponsorSlots.secondary.benefits.map((benefit, i) => (
                  <li key={i} className="flex items-center gap-2 text-sm text-gray-300">
                    <CheckCircle2 className="w-4 h-4 text-performance-green flex-shrink-0" />
                    {benefit}
                  </li>
                ))}
              </ul>

              {selectedTier === 'secondary' && league.sponsorSlots.secondary.available > 0 && (
                <div className="w-4 h-4 rounded-full bg-primary-blue absolute top-4 right-4 flex items-center justify-center">
                  <CheckCircle2 className="w-3 h-3 text-white" />
                </div>
              )}
            </Card>
          </div>

          {/* Checkout Summary */}
          <Card className="p-5">
            <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
              <CreditCard className="w-5 h-5 text-primary-blue" />
              Sponsorship Summary
            </h3>
            
            <div className="space-y-3 mb-6">
              <div className="flex justify-between py-2">
                <span className="text-gray-400">Selected Tier</span>
                <span className="text-white font-medium capitalize">{selectedTier} Sponsor</span>
              </div>
              <div className="flex justify-between py-2">
                <span className="text-gray-400">Season Price</span>
                <span className="text-white font-medium">
                  ${selectedTier === 'main' ? league.sponsorSlots.main.price : league.sponsorSlots.secondary.price}
                </span>
              </div>
              <div className="flex justify-between py-2">
                <span className="text-gray-400">Platform Fee ({siteConfig.fees.platformFeePercent}%)</span>
                <span className="text-white font-medium">
                  ${((selectedTier === 'main' ? league.sponsorSlots.main.price : league.sponsorSlots.secondary.price) * siteConfig.fees.platformFeePercent / 100).toFixed(2)}
                </span>
              </div>
              <div className="flex justify-between py-2 border-t border-charcoal-outline pt-4">
                <span className="text-white font-semibold">Total (excl. VAT)</span>
                <span className="text-white font-bold text-xl">
                  ${((selectedTier === 'main' ? league.sponsorSlots.main.price : league.sponsorSlots.secondary.price) * (1 + siteConfig.fees.platformFeePercent / 100)).toFixed(2)}
                </span>
              </div>
            </div>

            <p className="text-xs text-gray-500 mb-4">
              {siteConfig.vat.notice}
            </p>

            <div className="flex gap-3">
              <Button variant="primary" className="flex-1">
                <Megaphone className="w-4 h-4 mr-2" />
                Request Sponsorship
              </Button>
              <Button variant="secondary">
                <FileText className="w-4 h-4 mr-2" />
                Download Info Pack
              </Button>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}