'use client';
import { useEffect, useRef, useState } from 'react';

type VideoData = {
  id: string;
  src: string;
  label: string;
};

type PlayerProps = {
  dataFileName: string;
  title: string;
  onMeasurementChange: (label: string, value: number) => void;
  measurementData?: Record<string, number>;  

};

export default function VideoPlayer({ dataFileName, title, onMeasurementChange, measurementData }: PlayerProps) {
  const [formData, setFormData] = useState<VideoData[]>([]);
  const [activeFieldId, setActiveFieldId] = useState<string | null>(null);
  const [videoUrl, setVideoUrl] = useState<string | null>(null);
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const loadData = async () => {
      const data: VideoData[] = (await import(`@/public/data/measurement/${dataFileName}`)).default;
      setFormData(data);
    };
    loadData();
  }, [dataFileName]);

  const handleFocus = (field: VideoData) => {
    setActiveFieldId(field.id);
    setVideoUrl(field.src);
  };

  function labelToKey(label: string) {
    return label.toLowerCase().replace(/\s+/g, '_').replace(/[^\w_]/g, '');
  }

  const handleBlur = () => {
    setActiveFieldId(null);
    if (videoRef.current) videoRef.current.pause();
  };

  useEffect(() => {
    if (videoRef.current && videoUrl) {
      videoRef.current.load();
      videoRef.current.play().catch(() => { });
    }
  }, [videoUrl]);

  return (
    <div className="relative grid w-full grid-cols-8 gap-2 p-2 md:p-5 pb-10 md:gap-10 mob-noise bg-teal-100">
      <div className="col-span-5 md:col-span-6">
        <div className='flex flex-col w-full sticky -top-2  mob-noise bg-teal-100 py-2'>
          <h3 className="uppercase">{title}</h3>
        </div>
        <div className="grid grid-cols-1 gap-1 md:grid-cols-2 md:gap-5">
          {formData.map((item) => (
            <div
              key={item.id}
              className="grid grid-cols-7 items-center gap-4 border border-gray-950/30 bg-white p-2 align-middle"
            >
              <div className="col-span-4 text-xs/3 font-medium capitalize">
                <label htmlFor={item.id}>{item.label}</label>
              </div>
              <div className="col-span-3">
                <input
                  type="number"
                  id={item.id}
                  placeholder="in inch"
                  onFocus={() => handleFocus(item)}
                  onBlur={handleBlur}
                  min={5}
                  max={80}
                  value={measurementData ? measurementData[labelToKey(item.label)] ?? "" : ""}
                  onChange={(e) =>
                    onMeasurementChange(item.label, parseFloat(e.target.value) || 0)
                  }
                  className="w-full text-lg font-semibold placeholder:text-sm placeholder:font-normal"
                />

              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="relative col-span-3 gap-3 md:col-span-2">
        <div className="sticky top-20">
          <div className="pb-3">
            <p className="font-mono text-xs/3 font-medium normal-case">
              Tap or Click on input field, video will auto play here.
            </p>
          </div>
          {videoUrl && (
            <div className="relative">
              <div className="absolute top-0 left-0 z-10 flex h-full w-full items-center justify-between bg-gray-950/50 align-middle">
                <span className="flex h-15 w-15 animate-spin items-center">
                  <i
                    className="icon-[bx--loader-circle]"
                  ></i>
                </span>
              </div>
              <div className="relative z-30">
                <video
                  ref={videoRef}
                  muted
                  playsInline
                  autoPlay
                  loop
                  className="video-responsive"
                >
                  <source src={videoUrl} type="video/mp4" />
                </video>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
