/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import React, { useCallback, useEffect, useState } from 'react';

import { Direction, Range } from 'react-range';

interface YearSliderProps {
  min: number;
  max: number;
  initial?: number;
  className?: string;
  height?: number | string;
  paramName?: string;
  onFinalChange?: (year: number) => void;
  onChange?: (year: number) => void; // Live change during drag
  controlled?: number;
}
const YearSlider: React.FC<YearSliderProps> = ({
  min,
  max,
  initial,
  className,
  height = 300,
  onFinalChange,
  onChange,
  controlled,
}) => {
  const [value, setValue] = useState<number>(initial || max);

  // Year markers
  const renderYearMarkers = () => {
    const markerYears = [2000, 1975, 1950];

    return markerYears.map((year) => {
      if (year < min || year > max) return null;

      const position = (year - min) / (max - min);
      const bottomPercent = position * 100;

      return (
        <React.Fragment key={year}>
          <div
            className="absolute w-4 h-px bg-mma-blue pointer-events-none"
            style={{ bottom: `${bottomPercent}%`, right: 0 }}
          />
          {Math.abs(year - value) > 10 && (
            <div
              className="hidden lg:block absolute text-xs font-semibold text-mma-blue select-none font-slab"
              style={{
                bottom: `${bottomPercent}%`,
                left: 24,
                transform: 'translateY(50%)',
              }}
            >
              {year}
            </div>
          )}
        </React.Fragment>
      );
    });
  };

  // Min/Max labels
  const renderMinMaxLabels = () => {
    const gap = 8;

    return (
      <>
        {/* Desktop Max Label */}
        {max >= value + gap && (
          <div className="hidden lg:block absolute top-0 text-lg font-bold text-mma-blue select-none font-slab pl-6">
            {max}
          </div>
        )}

        {/* Mobile Max Label */}
        {max >= value + gap && (
          <div
            className="lg:hidden absolute text-xs font-bold text-mma-blue select-none font-slab"
            style={{
              top: 8,
              left: 8,
              transform: 'translateX(-50%) rotate(-90deg)',
              lineHeight: '12px',
            }}
          >
            {max}
          </div>
        )}

        {/* Desktop Min Label */}
        {min <= value - gap && (
          <div className="hidden lg:block absolute bottom-0 text-lg font-bold text-mma-blue select-none font-slab pl-6">
            {min}
          </div>
        )}

        {/* Mobile Min Label */}
        {min <= value - gap && (
          <div
            className="lg:hidden absolute text-xs font-bold text-mma-blue select-none font-slab"
            style={{
              bottom: 8,
              left: 8,
              transform: 'translateX(-50%) rotate(-90deg)',
              lineHeight: '12px',
            }}
          >
            {min}
          </div>
        )}
      </>
    );
  };

  // Thumb
  const renderThumb = (props: any) => {
    const { key: reactKey, style: styleFromLib, ...rest } = props;

    return (
      <div
        key={reactKey}
        {...rest}
        className="absolute cursor-pointer"
        style={{ ...styleFromLib, width: 0, height: 0 }}
      >
        {/* Mobile thumb */}
        <div
          className="lg:hidden absolute text-sm font-bold text-white font-slab bg-mma-blue rounded-t px-1 py-0.5 shadow-sm"
          style={{
            left: -2,
            top: 'calc(50%)',
            transform: 'translateX(-50%) rotate(-90deg)',
            lineHeight: '15px',
          }}
        >
          {value}
        </div>

        {/* Desktop thumb */}
        <div
          className="hidden lg:flex items-center justify-center absolute bg-mma-blue text-white font-slab font-bold text-lg rounded-full px-3 py-1.5 border border-white shadow-sm whitespace-nowrap"
          style={{
            left: 8,
            top: '50%',
            transform: 'translateY(-50%)',
            lineHeight: '18px',
          }}
        >
          {/* Arrow */}
          <div
            className="absolute"
            style={{
              left: -6,
              top: '50%',
              transform: 'translateY(-50%)',
              width: 0,
              height: 0,
              borderTop: '12px solid transparent',
              borderBottom: '12px solid transparent',
              borderRight: '12px solid #3b3f58',
            }}
          />
          {value}
        </div>
      </div>
    );
  };

  useEffect(() => {
    if (typeof controlled === 'number' && !Number.isNaN(controlled)) {
      setValue(controlled);
    }
  }, [controlled]);

  const handleFinalChange = useCallback(
    (vals: number[]) => {
      const year = Math.min(max, Math.max(min, Math.round(vals[0])));
      setValue(year);

      onFinalChange?.(year);
    },
    [min, max, onFinalChange]
  );

  return (
    <div className={`flex items-center justify-center ${className}`}>
      <Range
        values={[value]}
        min={min}
        max={max}
        step={1}
        direction={Direction.Up}
        onChange={(vals) => {
          const year = Math.round(vals[0]);
          setValue(year);
          onChange?.(year);
        }}
        onFinalChange={handleFinalChange}
        renderTrack={({ props, children }) => {
          const { key: reactKey, style: styleFromLib, ...rest } = props as any;
          return (
            <div
              key={reactKey}
              {...rest}
              className="relative bg-mma-yellow w-4"
              style={{
                ...styleFromLib,
                height: typeof height === 'number' ? `${height}px` : height,
              }}
            >
              {children}

              {renderYearMarkers()}
              {renderMinMaxLabels()}
            </div>
          );
        }}
        renderThumb={({ props }) => renderThumb(props)}
      />
    </div>
  );
};

export default YearSlider;
