"use client";

import { StepBack, StepForward } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Slider } from "@/components/ui/slider";
import { clampNumber, formatSecondsAsClock, formatSecondsAsTimecode } from "@/lib/client/time-format";

interface TimelineScrubberProps {
  durationSeconds: number;
  currentTimeSeconds: number;
  onSeek: (seconds: number) => void;
  onStepFrame?: (direction: -1 | 1) => void;
  disabled?: boolean;
}

export function TimelineScrubber({
  durationSeconds,
  currentTimeSeconds,
  onSeek,
  onStepFrame,
  disabled = false
}: TimelineScrubberProps) {
  const safeDuration = Math.max(durationSeconds, 0.01);
  const boundedCurrent = clampNumber(currentTimeSeconds, 0, safeDuration);

  return (
    <section className="rounded-xl border border-white/10 bg-slate-900/55 p-4">
      <div className="mb-3 flex items-center justify-between gap-2 text-xs text-slate-300 sm:text-sm">
        <span>{formatSecondsAsTimecode(boundedCurrent)}</span>
        <span>{formatSecondsAsClock(safeDuration)}</span>
      </div>

      <Slider
        min={0}
        max={safeDuration}
        step={0.001}
        value={[boundedCurrent]}
        disabled={disabled}
        onValueChange={(rawValue) => {
          const values = Array.isArray(rawValue) ? rawValue : [rawValue];
          onSeek(clampNumber(values[0] ?? 0, 0, safeDuration));
        }}
      />

      {onStepFrame ? (
        <div className="mt-3 flex flex-wrap items-center gap-2">
          <Button variant="outline" size="sm" disabled={disabled} onClick={() => onStepFrame(-1)}>
            <StepBack data-icon="inline-start" />
            Prev Frame
          </Button>
          <Button variant="outline" size="sm" disabled={disabled} onClick={() => onStepFrame(1)}>
            Next Frame
            <StepForward data-icon="inline-end" />
          </Button>
        </div>
      ) : null}
    </section>
  );
}
