"use client";

import { useRef, type ChangeEvent } from "react";
import { useTranslations } from "next-intl";
import { Music } from "lucide-react";

interface AudioTrackProps {
  totalDuration: number;
  pxPerSecond: number;
  fileName: string | null;
  onFileSelect: (fileName: string, src: string) => void;
}

export function AudioTrack({
  totalDuration,
  pxPerSecond,
  fileName,
  onFileSelect,
}: AudioTrackProps) {
  const t = useTranslations("auto.componentsStudioTimelineAudioTrack");
  const inputRef = useRef<HTMLInputElement>(null);
  const width = Math.max(totalDuration * pxPerSecond, pxPerSecond * 5);

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === "string") {
        onFileSelect(file.name, reader.result);
      }
    };
    reader.readAsDataURL(file);
    event.target.value = "";
  };

  return (
    <>
      <input
        ref={inputRef}
        type="file"
        accept="audio/*"
        className="hidden"
        onChange={handleChange}
      />
      <button
        type="button"
        onClick={() => inputRef.current?.click()}
        className="flex h-9 w-full items-center gap-2 rounded-md border border-[#2a2d3e] bg-[#1a1d2e]/80 px-3 text-left text-[11px] text-gray-300 transition-colors hover:border-[#3d4260] hover:bg-[#1f2234] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#4c6ef5]"
        style={{ width }}
      >
        <Music className="h-3.5 w-3.5 shrink-0 text-gray-500" aria-hidden />
        <span className="truncate">
          {fileName ?? t("emptyState")}
        </span>
      </button>
    </>
  );
}
