"use client";

import Image from "next/image";
import { Pause, Play, Volume2 } from "lucide-react";
import { useRef, useState } from "react";
import type { AudioFile } from "@/features/audio/types";

type AudioPlayerCardProps = {
  audioFile: AudioFile;
};

function formatTime(seconds: number) {
  if (!Number.isFinite(seconds)) {
    return "۰:۰۰";
  }

  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60).toString().padStart(2, "0");

  return `${minutes}:${remainingSeconds}`.replace(/\d/g, (digit) =>
    "۰۱۲۳۴۵۶۷۸۹"[Number(digit)],
  );
}

export function AudioPlayerCard({ audioFile }: AudioPlayerCardProps) {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);

  const progress = duration > 0 ? (currentTime / duration) * 100 : 0;

  const togglePlayback = async () => {
    const audio = audioRef.current;

    if (!audio) {
      return;
    }

    if (audio.paused) {
      try {
        await audio.play();
      } catch {
        setIsPlaying(false);
      }
      return;
    }

    audio.pause();
  };

  const handleSeek = (value: number) => {
    const audio = audioRef.current;

    if (!audio) {
      return;
    }

    audio.currentTime = value;
    setCurrentTime(value);
  };

  return (
    <article className="overflow-hidden rounded-[2rem] bg-card shadow-soft-sm ring-1 ring-border/70 transition-shadow hover:shadow-soft">
      <audio
        ref={audioRef}
        preload="metadata"
        src={audioFile.audioFileAddress}
        onDurationChange={(event) => setDuration(event.currentTarget.duration)}
        onTimeUpdate={(event) => setCurrentTime(event.currentTarget.currentTime)}
        onPlay={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
        onEnded={() => {
          setIsPlaying(false);
          setCurrentTime(0);
        }}
      />

      <div className="flex gap-4 p-4 sm:gap-5 sm:p-5">
        <div className="relative size-20 shrink-0 overflow-hidden rounded-2xl bg-gradient-to-br from-[#1D2D50] to-[#2EC4B6] shadow-soft-sm sm:size-24">
          {audioFile.coverImage ? (
            <Image
              src={audioFile.coverImage}
              alt={`کاور ${audioFile.title}`}
              fill
              unoptimized
              sizes="96px"
              className="object-cover"
            />
          ) : (
            <Volume2 className="absolute inset-0 m-auto size-9 text-white/90" />
          )}
        </div>

        <div className="min-w-0 flex-1 pt-1">
          <h2 className="truncate text-base font-bold text-card-foreground sm:text-lg">
            {audioFile.title}
          </h2>
          {audioFile.shortDescription ? (
            <p className="mt-1 line-clamp-2 text-sm leading-6 text-muted-foreground">
              {audioFile.shortDescription}
            </p>
          ) : null}
        </div>
      </div>

      <div className="border-t border-border bg-muted/35 px-4 py-3.5 sm:px-5">
        <div className="flex items-center gap-3" dir="ltr">
          <button
            type="button"
            onClick={() => void togglePlayback()}
            aria-label={isPlaying ? "توقف پخش" : "پخش فایل صوتی"}
            className="flex size-11 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-[0_6px_18px_rgba(242,153,74,0.32)] transition-transform hover:scale-105 active:scale-95"
          >
            {isPlaying ? (
              <Pause className="size-5 fill-current" />
            ) : (
              <Play className="ms-0.5 size-5 fill-current" />
            )}
          </button>

          <input
            aria-label="موقعیت پخش"
            type="range"
            min="0"
            max={duration || 0}
            step="0.1"
            value={Math.min(currentTime, duration || 0)}
            onChange={(event) => handleSeek(Number(event.target.value))}
            style={{ backgroundSize: `${progress}% 100%` }}
            className="h-1.5 w-full cursor-pointer appearance-none rounded-full bg-[linear-gradient(#F2994A,#F2994A)] bg-no-repeat accent-[#F2994A] [&::-moz-range-thumb]:size-3.5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-[#F2994A] [&::-webkit-slider-thumb]:size-3.5 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-[#F2994A]"
          />

          <span className="w-20 shrink-0 text-end text-xs font-medium tabular-nums text-muted-foreground">
            {formatTime(currentTime)} / {formatTime(duration)}
          </span>
        </div>
      </div>
    </article>
  );
}
