'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
  Trophy,
  Calendar,
  Clock,
  Gift,
  Building2,
  ChevronDown,
  ChevronUp,
  Loader2,
  AlertCircle,
  Users,
  Star,
  Award,
  Info,
  CheckCircle,
} from 'lucide-react'
import { BRAND } from '@/lib/constants'

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

interface Prize {
  position: string
  description: string
  value?: string
}

interface Competition {
  id: string
  title: string
  slug: string
  description: string | null
  industry: string | null
  startDate: string | null
  endDate: string | null
  prizePool: string | null
  maxEntries: number | null
  eligibilityGrades: number[]
  rules: string | null
  judgingCriteria: string[]
  prizes: Prize[]
  status: string
  createdAt: string
  sponsor: {
    id: string
    companyName: string
    industry: string | null
    sponsorshipTier: string | null
  } | null
}

/* ------------------------------------------------------------------ */
/* Helper                                                              */
/* ------------------------------------------------------------------ */

function StatusBadge({ status }: { status: string }) {
  const config: Record<string, { label: string; className: string }> = {
    active: { label: 'Active', className: 'bg-green-100 text-green-700 border-green-200' },
    upcoming: { label: 'Upcoming', className: 'bg-blue-100 text-blue-700 border-blue-200' },
    completed: { label: 'Completed', className: 'bg-gray-100 text-gray-600 border-gray-200' },
    closed: { label: 'Closed', className: 'bg-red-100 text-red-600 border-red-200' },
  }
  const c = config[status] || config.upcoming
  return (
    <Badge variant="outline" className={`text-[10px] font-medium ${c.className}`}>
      <span className={`mr-1 h-1.5 w-1.5 rounded-full ${
        status === 'active' ? 'bg-green-500' : status === 'upcoming' ? 'bg-blue-500' : 'bg-gray-400'
      }`} />
      {c.label}
    </Badge>
  )
}

function formatDate(dateStr: string | null) {
  if (!dateStr) return null
  return new Date(dateStr).toLocaleDateString('en-ZA', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  })
}

function isDeadlineSoon(dateStr: string | null) {
  if (!dateStr) return false
  const diff = new Date(dateStr).getTime() - Date.now()
  return diff > 0 && diff < 7 * 24 * 60 * 60 * 1000 // within 7 days
}

/* ------------------------------------------------------------------ */
/* Competition Card                                                    */
/* ------------------------------------------------------------------ */

function CompetitionCard({ competition }: { competition: Competition }) {
  const [showRules, setShowRules] = useState(false)
  const [showPrizes, setShowPrizes] = useState(false)

  return (
    <Card className="group hover:shadow-md transition-all border-gray-200 hover:border-[#91C4D9]/40">
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between gap-2">
          <div className="flex-1 min-w-0">
            <CardTitle className="text-base font-semibold leading-snug">{competition.title}</CardTitle>
            {competition.industry && (
              <p className="text-xs text-gray-500 mt-0.5">{competition.industry}</p>
            )}
          </div>
          <StatusBadge status={competition.status} />
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        {competition.description && (
          <p className="text-sm text-gray-600 line-clamp-3 leading-relaxed">{competition.description}</p>
        )}

        {/* Meta info */}
        <div className="flex flex-wrap gap-2">
          {competition.prizePool && (
            <Badge variant="outline" className="text-xs font-normal bg-yellow-50 border-yellow-200 text-yellow-700">
              <Gift className="w-3 h-3 mr-1" />
              {competition.prizePool}
            </Badge>
          )}
          {competition.endDate && (
            <Badge
              variant="outline"
              className={`text-xs font-normal ${
                isDeadlineSoon(competition.endDate)
                  ? 'bg-red-50 border-red-200 text-red-600'
                  : ''
              }`}
            >
              <Clock className="w-3 h-3 mr-1" />
              {formatDate(competition.endDate)}
            </Badge>
          )}
          {competition.maxEntries && (
            <Badge variant="outline" className="text-xs font-normal">
              <Users className="w-3 h-3 mr-1" />
              Max {competition.maxEntries} entries
            </Badge>
          )}
        </div>

        {/* Sponsor */}
        {competition.sponsor && (
          <div className="flex items-center gap-2 text-xs text-gray-500">
            <Building2 className="w-3.5 h-3.5" />
            <span>Sponsored by <span className="font-medium text-gray-700">{competition.sponsor.companyName}</span></span>
            {competition.sponsor.sponsorshipTier && (
              <Badge variant="secondary" className="text-[9px] ml-1">
                {competition.sponsor.sponsorshipTier}
              </Badge>
            )}
          </div>
        )}

        {/* Prize Breakdown */}
        {competition.prizes && competition.prizes.length > 0 && (
          <div className="border-t pt-2">
            <button
              onClick={() => setShowPrizes(!showPrizes)}
              className="flex items-center gap-1 text-xs font-medium text-gray-600 hover:text-[#5b9ebd] transition-colors"
            >
              <Star className="w-3 h-3" />
              Prize Breakdown
              {showPrizes ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
            </button>
            {showPrizes && (
              <div className="mt-2 space-y-1.5">
                {competition.prizes.map((prize, i) => (
                  <div key={i} className="flex items-center justify-between text-xs bg-gray-50 rounded-lg px-3 py-2">
                    <span className="font-medium text-gray-700">{prize.position}</span>
                    <span className="text-gray-500">{prize.description}</span>
                    {prize.value && (
                      <span className="font-semibold" style={{ color: BRAND.colors.primaryDark }}>
                        {prize.value}
                      </span>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Rules */}
        {competition.rules && (
          <div className="border-t pt-2">
            <button
              onClick={() => setShowRules(!showRules)}
              className="flex items-center gap-1 text-xs font-medium text-gray-600 hover:text-[#5b9ebd] transition-colors"
            >
              <Info className="w-3 h-3" />
              Rules & Guidelines
              {showRules ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
            </button>
            {showRules && (
              <div className="mt-2 text-xs text-gray-600 bg-gray-50 rounded-lg p-3 whitespace-pre-wrap leading-relaxed">
                {competition.rules}
              </div>
            )}
          </div>
        )}

        {/* Judging Criteria */}
        {competition.judgingCriteria && competition.judgingCriteria.length > 0 && (
          <div className="border-t pt-2">
            <p className="text-xs font-medium text-gray-600 mb-1.5">Judging Criteria</p>
            <div className="flex flex-wrap gap-1">
              {competition.judgingCriteria.map((c, i) => (
                <Badge key={i} variant="secondary" className="text-[10px] font-normal">
                  {c}
                </Badge>
              ))}
            </div>
          </div>
        )}

        {/* Action */}
        <div className="pt-1">
          {competition.status === 'active' ? (
            <Button
              className="w-full rounded-lg text-white text-sm h-9"
              style={{ background: BRAND.colors.primaryGradient }}
            >
              <Award className="w-4 h-4 mr-2" />
              Enter Competition
            </Button>
          ) : competition.status === 'upcoming' ? (
            <div className="flex items-center justify-center gap-2 text-sm text-gray-500 py-2">
              <Calendar className="w-4 h-4" />
              Opens {formatDate(competition.startDate)}
            </div>
          ) : (
            <div className="flex items-center justify-center gap-2 text-sm text-gray-400 py-2">
              <CheckCircle className="w-4 h-4" />
              Competition ended
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  )
}

/* ------------------------------------------------------------------ */
/* Empty State                                                         */
/* ------------------------------------------------------------------ */

function EmptyState({ tab }: { tab: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center">
      <div className="w-16 h-16 rounded-2xl bg-gray-100 flex items-center justify-center mb-4">
        <Trophy className="w-8 h-8 text-gray-400" />
      </div>
      <h3 className="text-lg font-semibold text-gray-900 mb-2">
        {tab === 'active' && 'No active competitions'}
        {tab === 'upcoming' && 'No upcoming competitions'}
        {tab === 'completed' && 'No completed competitions'}
      </h3>
      <p className="text-gray-500 max-w-md">
        {tab === 'active'
          ? 'There are no competitions running right now. Check back soon or browse upcoming competitions!'
          : tab === 'upcoming'
            ? 'No competitions are scheduled yet. Stay tuned for exciting challenges coming your way!'
            : 'No competitions have been completed yet. Keep an eye on active and upcoming competitions!'}
      </p>
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Main Page                                                           */
/* ------------------------------------------------------------------ */

export default function CompetitionsPage() {
  const [competitions, setCompetitions] = useState<Competition[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState('active')

  useEffect(() => {
    async function fetchCompetitions() {
      setLoading(true)
      setError(null)
      try {
        const res = await fetch('/api/competitions')
        if (!res.ok) throw new Error('Failed to fetch competitions')
        const data = await res.json()
        setCompetitions(data.competitions || [])
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred')
      } finally {
        setLoading(false)
      }
    }
    fetchCompetitions()
  }, [])

  const filtered = competitions.filter((c) => c.status === activeTab)
  const counts = {
    active: competitions.filter((c) => c.status === 'active').length,
    upcoming: competitions.filter((c) => c.status === 'upcoming').length,
    completed: competitions.filter((c) => c.status === 'completed' || c.status === 'closed').length,
  }

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      {/* Page Header */}
      <div className="mb-6">
        <div className="flex items-center gap-2 mb-1">
          <div
            className="w-8 h-8 rounded-lg flex items-center justify-center"
            style={{ background: BRAND.colors.primaryGradient }}
          >
            <Trophy className="w-4 h-4 text-white" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Competitions</h1>
        </div>
        <p className="text-sm text-gray-500">
          Compete, win prizes, and showcase your skills
        </p>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-3 gap-3 mb-6">
        {[
          { label: 'Active', count: counts.active, color: 'text-green-600 bg-green-50' },
          { label: 'Upcoming', count: counts.upcoming, color: 'text-blue-600 bg-blue-50' },
          { label: 'Completed', count: counts.completed, color: 'text-gray-600 bg-gray-50' },
        ].map((s) => (
          <Card key={s.label} className="border-dashed">
            <CardContent className="p-4 text-center">
              <p className="text-2xl font-bold" style={{ color: BRAND.colors.primaryDark }}>{s.count}</p>
              <p className={`text-xs font-medium mt-1 inline-block px-2 py-0.5 rounded-full ${s.color}`}>
                {s.label}
              </p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="mb-6">
          <TabsTrigger value="active" className="gap-1.5">
            <span className="h-2 w-2 rounded-full bg-green-500" />
            Active
            {counts.active > 0 && (
              <span className="ml-1 text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded-full">{counts.active}</span>
            )}
          </TabsTrigger>
          <TabsTrigger value="upcoming" className="gap-1.5">
            <span className="h-2 w-2 rounded-full bg-blue-500" />
            Upcoming
            {counts.upcoming > 0 && (
              <span className="ml-1 text-xs bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded-full">{counts.upcoming}</span>
            )}
          </TabsTrigger>
          <TabsTrigger value="completed" className="gap-1.5">
            <span className="h-2 w-2 rounded-full bg-gray-400" />
            Completed
            {counts.completed > 0 && (
              <span className="ml-1 text-xs bg-gray-100 text-gray-600 px-1.5 py-0.5 rounded-full">{counts.completed}</span>
            )}
          </TabsTrigger>
        </TabsList>

        {['active', 'upcoming', 'completed'].map((tab) => (
          <TabsContent key={tab} value={tab}>
            {/* Loading */}
            {loading && (
              <div className="flex flex-col items-center justify-center py-16">
                <Loader2 className="w-8 h-8 text-[#5b9ebd] animate-spin mb-4" />
                <p className="text-gray-500">Loading competitions...</p>
              </div>
            )}

            {/* Error */}
            {error && !loading && (
              <div className="flex flex-col items-center justify-center py-16 text-center">
                <AlertCircle className="w-12 h-12 text-red-400 mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">Could not load competitions</h3>
                <p className="text-gray-500 mb-4 max-w-md">{error}</p>
              </div>
            )}

            {/* Empty */}
            {!loading && !error && filtered.length === 0 && (
              <EmptyState tab={tab} />
            )}

            {/* Competition cards */}
            {!loading && !error && filtered.length > 0 && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {filtered.map((comp) => (
                  <CompetitionCard key={comp.id} competition={comp} />
                ))}
              </div>
            )}
          </TabsContent>
        ))}
      </Tabs>
    </div>
  )
}
