'use client'

import * as React from 'react'
import { Button } from '@admin/components/ui/button'
import { Form, FormControl, FormField, FormItem } from '@admin/components/ui/form'
import { Input } from '@admin/components/ui/input'
import { CornerDownLeft, Search, X } from 'lucide-react'
import { useForm } from 'react-hook-form'

interface SearchInputProps {
  value?: string
  placeholder?: string
  isPending?: boolean
  onSearch: (value: string | null) => void
}

interface SearchFormValues {
  search: string
}

export function SearchInput({
  value,
  placeholder = 'Search...',
  isPending,
  onSearch
}: SearchInputProps) {
  const searchFormValues = React.useMemo(() => ({ search: value ?? '' }), [value])
  const form = useForm<SearchFormValues>({
    defaultValues: searchFormValues,
    values: searchFormValues
  })

  const onSubmit = React.useCallback(
    (data: SearchFormValues) => {
      const trimmed = data.search.trim()
      onSearch(trimmed || null)
    },
    [onSearch]
  )

  return (
    <Form {...form}>
      <form
        autoComplete="off"
        onSubmit={form.handleSubmit(onSubmit)}
        className="flex w-full items-center"
      >
        <FormField
          control={form.control}
          name="search"
          render={({ field }) => (
            <FormItem className="w-full">
              <div className="relative w-full">
                <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-foreground" />
                <FormControl>
                  <Input {...field} placeholder={placeholder} className="w-full pl-9" />
                </FormControl>

                {value ? (
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon-sm"
                    disabled={isPending}
                    onClick={() => {
                      form.reset({ search: '' })
                      onSearch(null)
                    }}
                    aria-label="Clear search"
                    className="absolute top-1/2 right-2 size-7 -translate-y-1/2 text-foreground"
                  >
                    <X className="size-4" />
                  </Button>
                ) : (
                  <Button
                    type="submit"
                    variant="ghost"
                    size="icon-sm"
                    className="absolute top-1/2 right-2 size-7 -translate-y-1/2 text-foreground"
                    disabled={isPending}
                    aria-busy={isPending}
                    aria-label="Submit search"
                  >
                    <CornerDownLeft className="size-4" />
                  </Button>
                )}
              </div>
            </FormItem>
          )}
        />
      </form>
    </Form>
  )
}
