import { X, Calendar, Tv, Mic, Radio, Film, ExternalLink, CheckCircle, Loader2, MonitorPlay, User, Clapperboard, Megaphone, PenTool, Sparkles } from 'lucide-react'
import { format, parseISO } from 'date-fns'
import { useQuery } from '@tanstack/react-query'
import { api } from '../lib/api'

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[]
  all_roles?: { credit_type: string; character_name: string | null; job_title: string | null }[]
}

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 },
}

interface Props {
  appearance: Appearance
  onClose: () => void
  onMarkWatched?: (id: number) => void
}

export default function AppearanceDetailModal({ appearance, onClose, onMarkWatched }: Props) {
  // Fetch all episodes if this is a podcast or TV show with multiple episodes
  const { data: episodes, isLoading: episodesLoading } = useQuery({
    queryKey: ['show-episodes', appearance.celebrity_id, appearance.show_name, appearance.appearance_type],
    queryFn: () => api.getShowEpisodes(appearance.celebrity_id, appearance.show_name, appearance.appearance_type),
    enabled: (appearance.appearance_type === 'Podcast' || appearance.appearance_type === 'TV') && appearance.episode_count > 1,
  })
  const typeIcon = {
    TV: Tv,
    Movie: Film,
    Podcast: Mic,
    Radio: Radio,
  }[appearance.appearance_type]

  const TypeIcon = typeIcon || Tv

  return (
    <div
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-black/50 backdrop-blur-sm"
      onClick={onClose}
    >
      <div
        className="card-glass-hover rounded-t-2xl sm:rounded-2xl p-4 sm:p-6 w-full sm:max-w-3xl max-h-[85vh] sm:max-h-[90vh] overflow-y-auto sm:mx-4"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header with Close - sticky on mobile */}
        <div className="flex justify-between items-center mb-4 -mx-4 sm:-mx-6 -mt-4 sm:-mt-6 px-4 sm:px-6 pt-4 sm:pt-6 pb-2 sticky top-0 bg-inherit z-10">
          {/* Drag handle for mobile */}
          <div className="w-10 h-1 bg-slate-300 dark:bg-slate-600 rounded-full sm:hidden mx-auto absolute left-1/2 -translate-x-1/2 top-2" />
          <div className="flex-1" />
          <button
            onClick={onClose}
            className="p-2 hover:bg-secondary rounded-lg transition-colors touch-manipulation min-w-[44px] min-h-[44px] flex items-center justify-center"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content with Poster - stack on mobile */}
        <div className="flex flex-col sm:flex-row sm:items-start gap-4 sm:gap-6 mb-6">
          {/* Poster - centered on mobile */}
          {appearance.poster_url ? (
            <div className="flex-shrink-0 flex justify-center sm:justify-start">
              <img
                src={`/api/appearances/poster/${appearance.id}`}
                alt={appearance.show_name}
                className="w-24 sm:w-48 h-auto object-contain rounded-xl shadow-lg"
              />
            </div>
          ) : (
            <div className="flex-shrink-0 flex justify-center sm:justify-start">
              <div className="w-24 sm:w-48 h-36 sm:h-72 bg-gradient-to-br from-blue-600 to-cyan-600 rounded-xl flex items-center justify-center shadow-lg">
                <TypeIcon className="w-12 sm:w-16 h-12 sm:h-16 text-white" />
              </div>
            </div>
          )}

          {/* Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 sm:gap-3 mb-4">
              <div className="w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-blue-600 to-cyan-600 rounded-xl flex items-center justify-center flex-shrink-0">
                <TypeIcon className="w-5 h-5 sm:w-6 sm:h-6 text-white" />
              </div>
              <div className="min-w-0 flex-1">
                <h2 className="text-lg sm:text-2xl font-bold text-foreground truncate">{appearance.celebrity_name}</h2>
                <div className="flex items-center gap-1.5 sm:gap-2 flex-wrap">
                  <p className="text-xs sm:text-sm text-muted-foreground">{appearance.appearance_type} Appearance</p>
                  {/* Show all credit types for this show */}
                  {(appearance.all_credit_types || [appearance.credit_type]).filter((ct): ct is string => Boolean(ct)).map((creditType) => {
                    const cc = creditTypeConfig[creditType]
                    if (!cc) return null
                    const CreditIcon = cc.icon
                    return (
                      <span key={creditType} className={`text-xs px-2 py-0.5 rounded flex items-center gap-1 font-medium ${cc.color}`}>
                        <CreditIcon className="w-3 h-3" />
                        {cc.label}
                      </span>
                    )
                  })}
                </div>
              </div>
            </div>

            {/* Role/Character Info — show all roles when multiple */}
            {appearance.all_roles && appearance.all_roles.length > 1 ? (
              <div className="mb-4 space-y-2">
                {appearance.all_roles.map((role) => {
                  const cc = creditTypeConfig[role.credit_type]
                  const RoleIcon = cc?.icon || User
                  return (
                    <div key={role.credit_type} className="flex items-center gap-3 p-3 bg-secondary/50 rounded-xl">
                      <span className={`text-xs px-2 py-1 rounded flex items-center gap-1 flex-shrink-0 font-medium ${cc?.color || 'bg-slate-500/10 text-slate-400'}`}>
                        <RoleIcon className="w-3 h-3" />
                        {cc?.label || role.credit_type}
                      </span>
                      {(role.character_name || role.job_title) && (
                        <p className="text-sm font-medium text-foreground">
                          {role.credit_type === 'acting' || role.credit_type === 'guest' || role.credit_type === 'host'
                            ? (role.character_name ? `as ${role.character_name}` : role.job_title)
                            : (role.job_title || role.character_name)}
                        </p>
                      )}
                    </div>
                  )
                })}
              </div>
            ) : (appearance.character_name || appearance.job_title) ? (
              <div className="mb-4 p-3 bg-secondary/50 rounded-xl">
                <p className="text-xs text-muted-foreground mb-1">
                  {appearance.credit_type === 'acting' || appearance.credit_type === 'guest' || appearance.credit_type === 'host' ? 'Role' : 'Credit'}
                </p>
                <p className="text-base font-medium text-foreground">
                  {appearance.character_name || appearance.job_title}
                </p>
              </div>
            ) : null}

            {/* Show Info */}
            <div className="space-y-3 sm:space-y-4 mb-4 sm:mb-6">
          <div>
            <h3 className="text-base sm:text-lg font-semibold text-foreground mb-1 break-words">{appearance.show_name}</h3>
            {appearance.network && (
              <p className="text-xs sm:text-sm text-muted-foreground">{appearance.network}</p>
            )}
          </div>

          {/* For TV/Podcast with multiple episodes, don't show episode-specific info in header */}
          {appearance.episode_title && !((appearance.appearance_type === 'TV' || appearance.appearance_type === 'Podcast') && appearance.episode_count > 1) && (
            <div>
              <p className="text-sm text-muted-foreground">Episode</p>
              <div className="flex items-center justify-between gap-2">
                <p className="text-base font-medium text-foreground flex-1">
                  {appearance.season_number && appearance.episode_number && (
                    <span className="text-muted-foreground mr-2">
                      S{appearance.season_number}E{appearance.episode_number}
                    </span>
                  )}
                  {appearance.episode_title}
                </p>
                {appearance.url && (
                  <a
                    href={appearance.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex-shrink-0 p-1.5 hover:bg-blue-500/10 rounded-lg transition-colors"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <ExternalLink className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                  </a>
                )}
              </div>
            </div>
          )}

          {/* Show episode count and latest date for multi-episode shows */}
          {(appearance.appearance_type === 'TV' || appearance.appearance_type === 'Podcast') && appearance.episode_count > 1 && (
            <div className="flex flex-col sm:flex-row gap-2 sm:gap-4">
              <div className="flex items-center gap-2 p-2 sm:p-3 bg-purple-500/10 border border-purple-500/30 rounded-xl flex-1">
                <Tv className="w-4 h-4 sm:w-5 sm:h-5 text-purple-600 dark:text-purple-400 flex-shrink-0" />
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground">Episodes</p>
                  <p className="text-sm sm:text-base font-semibold text-foreground">
                    {appearance.episode_count} episodes
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2 p-2 sm:p-3 bg-blue-500/10 border border-blue-500/30 rounded-xl flex-1">
                <Calendar className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
                <div className="min-w-0">
                  <p className="text-xs text-muted-foreground">Latest Episode</p>
                  <p className="text-sm sm:text-base font-semibold text-foreground">
                    {format(parseISO(appearance.appearance_date), 'MMM d, yyyy')}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Air Date - only show for single-episode shows or movies */}
          {!((appearance.appearance_type === 'TV' || appearance.appearance_type === 'Podcast') && appearance.episode_count > 1) && (
            <div className={`flex items-center gap-2 p-2 sm:p-3 rounded-xl ${appearance.appearance_date.startsWith('1900') ? 'bg-purple-500/10 border border-purple-500/30' : 'bg-blue-500/10 border border-blue-500/30'}`}>
              <Calendar className={`w-4 h-4 sm:w-5 sm:h-5 flex-shrink-0 ${appearance.appearance_date.startsWith('1900') ? 'text-purple-600 dark:text-purple-400' : 'text-blue-600 dark:text-blue-400'}`} />
              <div className="min-w-0">
                <p className="text-xs text-muted-foreground">{appearance.appearance_date.startsWith('1900') ? 'Status' : 'Airs on'}</p>
                <p className="text-sm sm:text-base font-semibold text-foreground truncate">
                  {appearance.appearance_date.startsWith('1900') ? 'Coming Soon' : format(parseISO(appearance.appearance_date), 'MMM d, yyyy')}
                </p>
              </div>
            </div>
          )}

          {/* Description */}
          {appearance.description && (
            <div>
              <p className="text-sm text-muted-foreground mb-1">Description</p>
              <p className="text-sm text-foreground">{appearance.description}</p>
            </div>
          )}

          {/* Audio Player for main episode */}
          {appearance.appearance_type === 'Podcast' && appearance.audio_url && (
            <div>
              <p className="text-sm text-muted-foreground mb-2">Listen</p>
              <audio controls className="w-full" preload="metadata">
                <source src={appearance.audio_url} type="audio/mpeg" />
                Your browser does not support the audio element.
              </audio>
            </div>
          )}
            </div>
          </div>
        </div>

        {/* Episode List (for podcasts and TV shows with multiple episodes) */}
        {(appearance.appearance_type === 'Podcast' || appearance.appearance_type === 'TV') && appearance.episode_count > 1 && (
          <div className="mb-6 border-t border-slate-200 dark:border-slate-700 pt-6">
            {episodesLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="w-6 h-6 animate-spin text-blue-600" />
              </div>
            ) : episodes && episodes.length > 0 ? (
              (() => {
                // Filter out placeholder entries (season 0, episode 0 with no real title)
                // These are show-level fallback entries, not actual episode appearances
                const filteredEpisodes = episodes.filter(ep =>
                  !(ep.season_number === 0 && ep.episode_number === 0)
                )
                // For TV: show all episodes, For podcasts: filter out current
                const displayEpisodes = appearance.appearance_type === 'TV'
                  ? filteredEpisodes
                  : filteredEpisodes.filter(ep => ep.id !== appearance.id)
                const EpisodeIcon = appearance.appearance_type === 'TV' ? Tv : Mic

                // Don't show section if no real episodes after filtering
                if (displayEpisodes.length === 0) return null

                return (
                  <>
                    <h3 className="text-lg font-semibold text-foreground mb-4 flex items-center gap-2">
                      <EpisodeIcon className="w-5 h-5" />
                      {appearance.appearance_type === 'TV' ? 'All Episodes' : 'Other Episodes'} ({displayEpisodes.length})
                    </h3>
                    <div className="space-y-2 max-h-64 overflow-y-auto">
                      {displayEpisodes.map((episode, index) => (
                  <div
                    key={episode.id}
                    className="p-3 bg-secondary/50 rounded-lg hover:bg-secondary transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-foreground truncate">
                          {appearance.appearance_type === 'TV' && episode.season_number && episode.episode_number ? (
                            <span className="text-muted-foreground mr-2">S{episode.season_number}E{episode.episode_number}</span>
                          ) : null}
                          {episode.episode_title || `Episode ${index + 1}`}
                        </p>
                        <div className="flex items-center gap-2 mt-0.5 flex-wrap">
                          <p className="text-xs text-muted-foreground">
                            {format(parseISO(episode.appearance_date), 'MMM d, yyyy')}
                          </p>
                          {(episode.all_credit_types || (episode.credit_type ? [episode.credit_type] : [])).map((ct: string) => {
                            const cc = creditTypeConfig[ct]
                            return cc ? (
                              <span key={ct} className={`text-xs px-1.5 py-0.5 rounded font-medium flex items-center gap-1 ${cc.color}`}>
                                <cc.icon className="w-3 h-3" />
                                {cc.label}
                              </span>
                            ) : null
                          })}
                          {episode.all_roles && episode.all_roles.length > 0 ? (
                            episode.all_roles.map((role: { credit_type: string; character_name: string | null; job_title: string | null }) => (
                              (role.character_name || role.job_title) && (
                                <span key={role.credit_type + '-role'} className="text-xs text-muted-foreground">
                                  {role.credit_type === 'acting' || role.credit_type === 'guest' || role.credit_type === 'host'
                                    ? (role.character_name ? `as ${role.character_name}` : '')
                                    : (role.job_title || '')}
                                </span>
                              )
                            ))
                          ) : (
                            <>
                              {episode.character_name && (
                                <span className="text-xs text-muted-foreground">as {episode.character_name}</span>
                              )}
                              {episode.job_title && !episode.character_name && (
                                <span className="text-xs text-muted-foreground">{episode.job_title}</span>
                              )}
                            </>
                          )}
                        </div>
                        {episode.audio_url && (
                          <audio controls className="w-full mt-2" preload="metadata">
                            <source src={episode.audio_url} type="audio/mpeg" />
                            Your browser does not support the audio element.
                          </audio>
                        )}
                      </div>
                      {/* Actions on RIGHT, vertically centered */}
                      <div className="flex items-center gap-2 flex-shrink-0">
                        {episode.plex_watch_url && (
                          <a
                            href={episode.plex_watch_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-1 px-2 py-1 bg-gradient-to-r from-amber-600 to-orange-600 text-white text-xs rounded hover:from-amber-700 hover:to-orange-700 transition-colors"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <MonitorPlay className="w-3 h-3" />
                            Plex
                          </a>
                        )}
                        {episode.url && (
                          <a
                            href={episode.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="p-1.5 hover:bg-blue-500/10 rounded-lg transition-colors"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <ExternalLink className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                          </a>
                        )}
                      </div>
                    </div>
                  </div>
                      ))}
                    </div>
                  </>
                )
              })()
            ) : (
              <p className="text-sm text-muted-foreground">No episodes available</p>
            )}
          </div>
        )}

        {/* Actions - stack on mobile */}
        <div className="flex flex-col sm:flex-row gap-2 sm:gap-3">
          {appearance.plex_watch_url && (
            <a
              href={appearance.plex_watch_url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex-1 bg-gradient-to-r from-amber-600 to-orange-600 text-white rounded-lg py-3 sm:py-2 font-medium flex items-center justify-center gap-2 hover:from-amber-700 hover:to-orange-700 transition-all touch-manipulation min-h-[44px]"
            >
              <MonitorPlay className="w-4 h-4" />
              Watch on Plex
            </a>
          )}

          {appearance.watch_url && (
            <a
              href={appearance.watch_url}
              target="_blank"
              rel="noopener noreferrer"
              className="flex-1 btn-primary flex items-center justify-center gap-2 py-3 sm:py-2 touch-manipulation min-h-[44px]"
            >
              <ExternalLink className="w-4 h-4" />
              Watch Live
            </a>
          )}

          {onMarkWatched && appearance.status !== 'watched' && (
            <button
              onClick={() => onMarkWatched(appearance.id)}
              className="flex-1 btn-secondary flex items-center justify-center gap-2 py-3 sm:py-2 touch-manipulation min-h-[44px]"
            >
              <CheckCircle className="w-4 h-4" />
              Mark as Watched
            </button>
          )}

          {appearance.status === 'watched' && (
            <div className="flex-1 flex items-center justify-center gap-2 text-green-600 dark:text-green-400 bg-green-500/10 border border-green-500/30 rounded-lg py-3 sm:py-2 min-h-[44px]">
              <CheckCircle className="w-4 h-4" />
              <span className="text-sm font-medium">Watched</span>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
