"use client"

import {
  type Control,
  type FieldPath,
  type FieldValues,
} from "react-hook-form"

import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
} from "@/components/ui/form"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { cn } from "@/lib/utils"

type StatusSwitchProps = {
  checked: boolean
  onCheckedChange?: (checked: boolean) => void
  label: string
  description?: string
  className?: string
  disabled?: boolean
}

function StatusSwitch({
  checked,
  onCheckedChange,
  label,
  description,
  className,
  disabled,
}: StatusSwitchProps) {
  return (
    <div
      className={cn(
        "flex justify-between items-start gap-3 p-3 border rounded-lg",
        className
      )}
    >
      <div className="gap-0.5 grid min-w-0">
        <Label>{label}</Label>
        {description ? (
          <p className="text-muted-foreground text-xs leading-snug">{description}</p>
        ) : null}
      </div>
      <Switch
        className="shrink-0"
        checked={checked}
        onCheckedChange={onCheckedChange}
        disabled={disabled}
        aria-label={label}
      />
    </div>
  )
}

type StatusSwitchFieldProps<
  TFieldValues extends FieldValues,
  TName extends FieldPath<TFieldValues>,
> = {
  control: Control<TFieldValues>
  name: TName
  label: string
  description?: string
  className?: string
  disabled?: boolean
}

function StatusSwitchField<
  TFieldValues extends FieldValues,
  TName extends FieldPath<TFieldValues>,
>({
  control,
  name,
  label,
  description,
  className,
  disabled,
}: StatusSwitchFieldProps<TFieldValues, TName>) {
  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => (
        <FormItem
          className={cn(
            "flex justify-between items-start gap-3 p-3 border rounded-lg",
            className
          )}
        >
          <div className="gap-0.5 grid min-w-0">
            <FormLabel>{label}</FormLabel>
            {description ? (
              <FormDescription className="text-xs leading-snug">
                {description}
              </FormDescription>
            ) : null}
          </div>
          <FormControl>
            <Switch
              className="shrink-0"
              checked={field.value}
              onCheckedChange={field.onChange}
              disabled={disabled}
            />
          </FormControl>
        </FormItem>
      )}
    />
  )
}

export { StatusSwitch, StatusSwitchField }
