"use client";

import { UseFormReturn, Path } from "react-hook-form";
import {
  FormField,
  FormItem,
  FormLabel,
} from "@/app/shadcn_components/ui/form";
import {
  measuresList,
  measuresDisplayLabels,
} from "@/app/db/schema/recommendations";
import { BaseFormValues } from "./FormSchema";

type MeasuresCheckboxesProps<T extends BaseFormValues> = {
  form: UseFormReturn<T>;
  name?: Path<T>; // Optional override for custom field key
};

function MeasuresCheckboxes<T extends BaseFormValues>({
  form,
  name = "measures" as Path<T>,
}: MeasuresCheckboxesProps<T>) {
  const { control, setValue } = form;

  return (
    <div className="flex flex-col gap-4 mt-4">
      <div className="flex justify-start gap-4">
        <button
          type="button"
          onClick={() =>
            setValue(name, measuresList as any, { shouldValidate: true })
          }
          className="text-sm text-brandbrown underline"
        >
          Select All
        </button>
        <button
          type="button"
          onClick={() => setValue(name, [] as any, { shouldValidate: true })}
          className="text-sm text-brandbrown underline"
        >
          Untick All
        </button>
      </div>

      <div className="grid grid-cols-2 gap-4">
        {measuresList.map((measure) => (
          <FormField
            key={measure}
            control={control}
            name={name}
            render={({ field }) => (
              <FormItem className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  value={measure}
                  checked={field.value?.includes(measure) ?? false}
                  onChange={(e) => {
                    const checked = e.target.checked;
                    const current = new Set(field.value ?? []);
                    checked ? current.add(measure) : current.delete(measure);
                    field.onChange(Array.from(current));
                  }}
                  className="h-4 w-4"
                />
                <FormLabel className="text-sm">
                  {measuresDisplayLabels[measure]}
                </FormLabel>
              </FormItem>
            )}
          />
        ))}
      </div>
    </div>
  );
}

export default MeasuresCheckboxes;
