"use client";

import { CircleHelp } from "lucide-react";
import { Controller, type Control, type FieldPath, type FieldValues } from "react-hook-form";

import { stockFieldLabels } from "@/components/form/common/field-labels";
import { formSpanFull } from "@/components/form/common/form-layout";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";

const DEFAULT_DESCRIPTION =
  "Adjust cash balance for the selected bank and currency by this transaction amount.";

type UpdatePortfolioCashFieldProps<T extends FieldValues> = {
  control: Control<T>;
  formId: string;
  name?: FieldPath<T>;
  description?: string;
};

export function UpdatePortfolioCashField<T extends FieldValues>({
  control,
  formId,
  name = "portfolio_cash_synced" as FieldPath<T>,
  description = DEFAULT_DESCRIPTION,
}: UpdatePortfolioCashFieldProps<T>) {
  return (
    <Controller
      control={control}
      name={name}
      render={({ field }) => (
        <div className={`flex min-w-0 items-center gap-3 ${formSpanFull}`}>
          <Checkbox
            id={`${formId}-portfolio-cash-synced`}
            checked={Boolean(field.value)}
            onCheckedChange={(checked) => field.onChange(checked === true)}
          />
          <div className="flex min-w-0 items-center gap-1.5 leading-none">
            <Label htmlFor={`${formId}-portfolio-cash-synced`} className="cursor-pointer font-normal">
              {stockFieldLabels.portfolio_cash_synced}
            </Label>
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  className="inline-flex shrink-0 text-muted-foreground hover:text-foreground"
                  aria-label="About update portfolio cash"
                >
                  <CircleHelp className="size-3.5" />
                </button>
              </TooltipTrigger>
              <TooltipContent side="top" className="max-w-[280px] text-xs leading-relaxed">
                {description}
              </TooltipContent>
            </Tooltip>
          </div>
        </div>
      )}
    />
  );
}
