"use client";

import { useState } from "react";
import { cn } from "@/lib/helpers";
import { useLanguageStore } from "@/store/languageStore";
import { checkable } from "@/lib/a11y";

interface CheckboxProps {
  id: string;
  label: string;
  checked?: boolean;
  onChange?: (checked: boolean) => void;
  className?: string;
}

export default function FilterCheckBox({
  id,
  label,
  checked = false,
  onChange,
  className = "",
}: CheckboxProps) {
  const [isChecked, setIsChecked] = useState(checked);
  /*
   * Re-sync with the `checked` prop during render, not in an effect.
   *
   * This component is both controlled and uncontrolled: `handleChange` updates
   * the local copy so the box responds immediately, and also calls `onChange`
   * so a controlled parent can push a new `checked` back down. The copy
   * therefore has to follow the prop when it changes.
   *
   * Doing that in an effect meant the stale value was painted first and
   * corrected on the next commit — a one-frame flash of the wrong state, and
   * what `react-hooks/set-state-in-effect` is warning about. Adjusting during
   * render is React's documented pattern for "a prop changed, reset some
   * state": the re-render happens before the browser paints, so nothing
   * visibly flickers.
   */
  const [prevChecked, setPrevChecked] = useState(checked);
  if (checked !== prevChecked) {
    setPrevChecked(checked);
    setIsChecked(checked);
  }

  const handleChange = () => {
    const newChecked = !isChecked;
    setIsChecked(newChecked);
    if (onChange) {
      onChange(newChecked);
    }
  };

  const selectedLanguage = useLanguageStore((s) => s.language);
  const isRtl = selectedLanguage === "ar";

  return (
    <div
      className={`flex items-center gap-2 ${className} cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-5`}
      /* There is no `<input>` in here — the tick is an SVG — so the role,
         the checked state and the keyboard path all have to be supplied. */
      {...checkable(isChecked, handleChange)}
    >
      <div
        className={`h-5 w-5 flex items-center justify-center border rounded cursor-pointer 
          ${isChecked ? "bg-primary-5 border-primary-5" : "border-gray-300"}
        `}
      >
        {isChecked && (
          <svg
            className="w-4 h-4 text-white font-bold"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="2"
              d="M5 13l4 4L19 7"
            />
          </svg>
        )}
      </div>

      <label
        htmlFor={id}
        className={cn(
          "text-primary-5 cursor-pointer",
          isRtl
            ? "mr-2 ml-0 text-secondary-102"
            : "ml-2 text-secondary-102 lg:text-lg md:text-sm",
        )}
      >
        {label}
      </label>
    </div>
  );
}
