"use client";

import * as React from "react";
import { Controller, type Control, type FieldPath, type FieldValues } from "react-hook-form";

import { formFieldClass, formInputClass } from "@/components/form/common/form-layout";
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { cn } from "@/lib/utils";

export type KnockFtOption = { value: string; label: string };

type KnockAmountFieldProps<T extends FieldValues> = {
  control: Control<T>;
  knockFtName: FieldPath<T>;
  knockName: FieldPath<T>;
  knockTName: FieldPath<T>;
  label?: string;
  knockFtOptions: KnockFtOption[];
  className?: string;
};

export function KnockAmountField<T extends FieldValues>({
  control,
  knockFtName,
  knockName,
  knockTName,
  label = "Knock Amount",
  knockFtOptions,
  className,
}: KnockAmountFieldProps<T>) {
  return (
    <Controller
      control={control}
      name={knockTName}
      render={({ field: knockTField, fieldState: knockTState }) => (
        <Field className={cn(formFieldClass, "col-span-full", className)} data-invalid={!!knockTState.error}>
          <FieldLabel>{label}</FieldLabel>
          <div className="flex flex-col gap-2 sm:flex-row sm:items-stretch">
            <div className="flex min-w-0 flex-1">
              <Controller
                control={control}
                name={knockFtName}
                render={({ field: knockFtField }) => (
                  <Select value={knockFtField.value ?? "1"} onValueChange={knockFtField.onChange}>
                    <SelectTrigger
                      className={cn(
                        formInputClass,
                        "w-[9.5rem] shrink-0 rounded-r-none border-r-0",
                      )}
                      aria-label="Knock type"
                    >
                      <SelectValue placeholder="Knock In" />
                    </SelectTrigger>
                    <SelectContent>
                      {knockFtOptions.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                          {option.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              />
              <Controller
                control={control}
                name={knockName}
                render={({ field: knockField, fieldState: knockState }) => (
                  <Input
                    {...knockField}
                    id={String(knockName)}
                    type="number"
                    step="any"
                    placeholder="Knock Amount"
                    value={knockField.value ?? ""}
                    onChange={(event) => {
                      const raw = event.target.value;
                      knockField.onChange(raw === "" ? "" : Number(raw));
                    }}
                    aria-invalid={!!knockState.error}
                    className={cn(formInputClass, "min-w-0 flex-1 rounded-l-none")}
                  />
                )}
              />
            </div>

            <div className="flex shrink-0 overflow-hidden rounded-md border border-input">
              {(
                [
                  { value: "", label: "Value" },
                  { value: "1", label: "Percentage" },
                ] as const
              ).map((option) => {
                const active = (knockTField.value ?? "") === option.value;
                return (
                  <button
                    key={option.label}
                    type="button"
                    className={cn(
                      "min-w-[5.5rem] px-3 py-2 text-sm font-medium transition-colors",
                      active
                        ? "bg-primary text-primary-foreground"
                        : "bg-background text-foreground hover:bg-muted/60",
                    )}
                    onClick={() => knockTField.onChange(option.value)}
                  >
                    {option.label}
                  </button>
                );
              })}
            </div>
          </div>
          {knockTState.error ? <FieldError errors={[knockTState.error]} /> : null}
        </Field>
      )}
    />
  );
}
