"use client";

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

interface DualRangeSliderProps {
  min: number;
  max: number;
  start: number;
  end: number;
  onChange: (start: number, end: number) => void;
  minimumGap?: number;
  disabled?: boolean;
  startLabel?: string;
  endLabel?: string;
}

export function DualRangeSlider({
  min,
  max,
  start,
  end,
  onChange,
  minimumGap = 0,
  disabled = false,
  startLabel = "Start",
  endLabel = "End"
}: DualRangeSliderProps) {
  const safeMin = Math.min(min, max);
  const safeMax = Math.max(min, max);
  const normalizedStart = clampNumber(Math.min(start, end), safeMin, safeMax);
  const normalizedEnd = clampNumber(Math.max(start, end), safeMin, safeMax);

  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>
          {startLabel}: {formatSecondsAsTimecode(normalizedStart)}
        </span>
        <span>
          {endLabel}: {formatSecondsAsTimecode(normalizedEnd)}
        </span>
      </div>

      <Slider
        min={safeMin}
        max={safeMax}
        step={0.01}
        disabled={disabled}
        value={[normalizedStart, normalizedEnd]}
        onValueChange={(rawValues) => {
          const values = Array.isArray(rawValues) ? rawValues : [rawValues];
          const draftStart = clampNumber(values[0] ?? safeMin, safeMin, safeMax);
          const draftEnd = clampNumber(values[1] ?? safeMax, safeMin, safeMax);
          const orderedStart = Math.min(draftStart, draftEnd);
          const orderedEnd = Math.max(draftStart, draftEnd);
          const gapSafeEnd = Math.max(orderedEnd, orderedStart + minimumGap);
          const finalEnd = clampNumber(gapSafeEnd, safeMin, safeMax);
          const finalStart = clampNumber(Math.min(orderedStart, finalEnd - minimumGap), safeMin, safeMax);

          onChange(finalStart, finalEnd);
        }}
      />
    </section>
  );
}
