"use client";
import Image from "next/image";
import { Play, Pause, SkipBack, SkipForward, Volume2, X } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  togglePlay,
  stopAll,
  playNext,
  playPrev,
  clearAudioError,
  setRepeat,
} from "@/store/slices/playerSlice";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { cn } from "@/utils/cn";
import { useTranslation } from "@/i18n";

interface BottomPlayerProps {
  collapsed: boolean;
}

export function BottomPlayer({ collapsed }: BottomPlayerProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { t } = useTranslation();
  const { isPlaying, currentTrack, type, progress, audioError } =
    useAppSelector((s) => s.player);

  useEffect(() => {
    if (audioError) {
      console.warn("[BottomPlayer] Audio error:", audioError);
      dispatch(clearAudioError());
    }
  }, [audioError, dispatch]);

  // Only show for audio type with a loaded track
  if (!currentTrack || type !== "audio") return null;

  const img = currentTrack.thumbnail || currentTrack.landscapeImg || "";
  const title = currentTrack.title || "Unknown Track";
  const artist = currentTrack.channelName || "";

  return (
    <div
      className={cn(
        "fixed left-0 right-0 z-50 border-t bg-[var(--card)] border-[var(--border)]",
        "bottom-14 md:bottom-0",
        "md:grid",
        collapsed ? "md:grid-cols-[56px_1fr]" : "md:grid-cols-[200px_1fr]",
      )}
    >
      {/* Progress bar */}
      <div className="h-[3px]" style={{ background: "var(--border)" }}>
        <div
          className="h-full transition-all duration-300"
          style={{ width: `${progress}%`, background: "var(--accent)" }}
        />
      </div>

      <div
        className="flex items-center gap-3 px-4 py-2 md:px-5 cursor-pointer"
        onClick={() => router.push("/now-playing")}
      >
        {/* Thumbnail */}
        <div
          className="w-10 h-10 rounded-lg overflow-hidden shrink-0"
          style={{ background: "var(--deep)" }}
        >
          {img ? (
            <Image
              src={img}
              alt={title}
              width={40}
              height={40}
              className="w-full h-full object-cover"
              unoptimized
            />
          ) : (
            <div
              className="w-full h-full"
              style={{
                background: "linear-gradient(135deg, var(--accent), #9b2d8b)",
              }}
            />
          )}
        </div>

        {/* Info */}
        <div className="flex-1 min-w-0">
          <p className="text-xs font-medium truncate" style={{ color: "var(--text-primary)" }}>{title}</p>
          <p className="text-[10px] truncate" style={{ color: "var(--text-muted)" }}>
            {artist}
          </p>
        </div>

        {/* Controls */}
        <div
          className="flex items-center gap-1"
          onClick={(e) => e.stopPropagation()}
        >
          <button
            onClick={() => dispatch(playPrev())}
            className="w-8 h-8 rounded-lg flex items-center justify-center transition-colors hover:bg-white/5"
            aria-label={t("player_previous")}
          >
            <SkipBack size={16} strokeWidth={1.6} style={{ color: "var(--text-primary)" }} />
          </button>

          <button
            onClick={() => dispatch(togglePlay())}
            className="w-9 h-9 rounded-full flex items-center justify-center transition-all active:scale-95"
            style={{ background: "var(--accent)" }}
            aria-label={isPlaying ? t("player_pause") : t("player_play")}
          >
            {isPlaying ? (
              <Pause size={15} fill="white" strokeWidth={0} />
            ) : (
              <Play size={15} fill="white" strokeWidth={0} className="ml-0.5" />
            )}
          </button>

          <button
            onClick={() => { dispatch(setRepeat(false)); dispatch(playNext()); }}
            className="w-8 h-8 rounded-lg flex items-center justify-center transition-colors hover:bg-white/5"
            aria-label={t("player_next")}
          >
            <SkipForward size={16} strokeWidth={1.6} style={{ color: "var(--text-primary)" }} />
          </button>

          <button
            className="w-8 h-8 rounded-lg items-center justify-center transition-colors hover:bg-white/5 hidden sm:flex"
            aria-label={t("player_volume")}
          >
            <Volume2 size={15} strokeWidth={1.6} style={{ color: "var(--text-muted)" }} />
          </button>

          <button
            onClick={() => dispatch(stopAll())}
            className="w-8 h-8 rounded-lg flex items-center justify-center transition-colors hover:bg-white/5"
            aria-label={t("player_close")}
          >
            <X size={15} strokeWidth={1.6} style={{ color: "var(--text-muted)" }} />
          </button>
        </div>
      </div>
    </div>
  );
}
