import { useState } from 'react'
import { Calendar, Tv, Mic, Radio, Film, ChevronRight, User, Clapperboard, Megaphone, PenTool, Sparkles } from 'lucide-react'
import { format, parseISO, formatDistanceToNow, isBefore } from 'date-fns'
import AppearanceDetailModal from './AppearanceDetailModal'

interface Appearance {
  id: number
  celebrity_id: number
  celebrity_name: string
  appearance_type: 'TV' | 'Movie' | 'Podcast' | 'Radio'
  show_name: string
  episode_title: string | null
  network: string | null
  appearance_date: string
  url: string | null
  audio_url: string | null
  watch_url: string | null
  description: string | null
  tmdb_show_id: number | null
  season_number: number | null
  episode_number: number | null
  status: string
  poster_url: string | null
  episode_count: number
  credit_type: 'acting' | 'host' | 'directing' | 'producing' | 'writing' | 'creator' | 'guest' | null
  character_name: string | null
  job_title: string | null
  plex_rating_key: string | null
  plex_watch_url: string | null
  all_credit_types?: string[]
}

interface Props {
  appearances: Appearance[]
  onMarkWatched?: (id: number) => void
}

export default function UpcomingAppearancesCard({ appearances, onMarkWatched }: Props) {
  const [selectedAppearance, setSelectedAppearance] = useState<Appearance | null>(null)

  const typeConfig = {
    TV: { icon: Tv, color: 'bg-gradient-to-br from-purple-600 to-indigo-600', label: 'TV' },
    Movie: { icon: Film, color: 'bg-gradient-to-br from-red-600 to-pink-600', label: 'Movie' },
    Podcast: { icon: Mic, color: 'bg-gradient-to-br from-green-600 to-emerald-600', label: 'Podcast' },
    Radio: { icon: Radio, color: 'bg-gradient-to-br from-orange-600 to-amber-600', label: 'Radio' },
  }

  const creditTypeConfig: Record<string, { label: string; color: string; icon: typeof User }> = {
    acting: { label: 'Acting', color: 'bg-blue-500/10 text-blue-600 dark:text-blue-400', icon: User },
    directing: { label: 'Directing', color: 'bg-amber-500/10 text-amber-600 dark:text-amber-400', icon: Clapperboard },
    producing: { label: 'Producing', color: 'bg-green-500/10 text-green-600 dark:text-green-400', icon: Megaphone },
    writing: { label: 'Writing', color: 'bg-purple-500/10 text-purple-600 dark:text-purple-400', icon: PenTool },
    creator: { label: 'Creator', color: 'bg-pink-500/10 text-pink-600 dark:text-pink-400', icon: Sparkles },
    guest: { label: 'Guest', color: 'bg-cyan-500/10 text-cyan-600 dark:text-cyan-400', icon: User },
    host: { label: 'Host', color: 'bg-orange-500/10 text-orange-600 dark:text-orange-400', icon: Mic },
  }

  return (
    <>
      <div className="card-glass-hover rounded-xl p-4 md:p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-gradient-to-br from-cyan-600 to-blue-600 rounded-lg flex items-center justify-center">
              <Calendar className="w-5 h-5 text-white" />
            </div>
            <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
              Upcoming Appearances
            </h3>
          </div>
          <span className="text-xs text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded">
            {appearances.length} upcoming
          </span>
        </div>

        {appearances && appearances.length > 0 ? (
          <div className="space-y-3">
            {appearances.map((appearance) => {
              const config = typeConfig[appearance.appearance_type]
              const Icon = config.icon
              const isSoon = isBefore(parseISO(appearance.appearance_date), new Date(Date.now() + 7 * 24 * 60 * 60 * 1000))

              return (
                <div
                  key={appearance.id}
                  onClick={() => setSelectedAppearance(appearance)}
                  className="flex items-center justify-between p-4 bg-secondary/50 rounded-xl hover:bg-secondary group cursor-pointer transition-all"
                >
                  {/* Poster/Icon + Info */}
                  <div className="flex items-center gap-4 min-w-0 flex-1">
                    {appearance.poster_url ? (
                      <div className="w-12 h-12 rounded-lg overflow-hidden flex-shrink-0 bg-slate-200 dark:bg-slate-700">
                        <img
                          src={`https://image.tmdb.org/t/p/w92${appearance.poster_url}`}
                          alt={appearance.show_name}
                          className="w-full h-full object-cover"
                        />
                      </div>
                    ) : (
                      <div className={`w-12 h-12 ${config.color} rounded-lg flex items-center justify-center flex-shrink-0`}>
                        <Icon className="w-6 h-6 text-white" />
                      </div>
                    )}

                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <p className="text-sm font-semibold text-foreground truncate">
                          {appearance.celebrity_name}
                        </p>
                        <span className="text-xs px-2 py-0.5 bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded flex-shrink-0">
                          {config.label}
                        </span>
                        {(appearance.all_credit_types || (appearance.credit_type ? [appearance.credit_type] : [])).map((ct) => {
                          const cc = creditTypeConfig[ct]
                          if (!cc) return null
                          const CreditIcon = cc.icon
                          return (
                            <span key={ct} className={`text-xs px-2 py-0.5 rounded flex items-center gap-1 flex-shrink-0 ${cc.color}`}>
                              <CreditIcon className="w-3 h-3" />
                              {cc.label}
                            </span>
                          )
                        })}
                        {isSoon && appearance.status === 'upcoming' && (
                          <span className="text-xs px-2 py-0.5 bg-orange-500/10 text-orange-600 dark:text-orange-400 rounded flex-shrink-0">
                            Soon
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-foreground truncate">
                        {appearance.show_name}
                        {appearance.network && (
                          <span className="text-muted-foreground"> • {appearance.network}</span>
                        )}
                      </p>
                      {appearance.episode_title && (
                        <p className="text-xs text-muted-foreground truncate mt-0.5">
                          {appearance.season_number && appearance.episode_number && (
                            <span>S{appearance.season_number}E{appearance.episode_number}: </span>
                          )}
                          {appearance.episode_title}
                        </p>
                      )}
                    </div>
                  </div>

                  {/* Date + Arrow */}
                  <div className="flex items-center gap-3 ml-4 flex-shrink-0">
                    <div className="text-right">
                      <p className="text-xs font-medium text-foreground">
                        {format(parseISO(appearance.appearance_date), 'MMM d, yyyy')}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {formatDistanceToNow(parseISO(appearance.appearance_date), { addSuffix: true })}
                      </p>
                    </div>
                    <ChevronRight className="w-4 h-4 text-muted-foreground group-hover:text-foreground transition-colors" />
                  </div>
                </div>
              )
            })}
          </div>
        ) : (
          <div className="text-center text-slate-500 dark:text-slate-400 py-8">
            <Calendar className="w-12 h-12 mx-auto mb-2 opacity-50" />
            <p>No upcoming appearances scheduled</p>
            <p className="text-xs mt-1">Sync TMDb to discover appearances</p>
          </div>
        )}
      </div>

      {/* Detail Modal */}
      {selectedAppearance && (
        <AppearanceDetailModal
          appearance={selectedAppearance}
          onClose={() => setSelectedAppearance(null)}
          onMarkWatched={onMarkWatched}
        />
      )}
    </>
  )
}
