import React, { forwardRef } from 'react'
import { FormProvider, UseFormReturn, FieldValues, SubmitHandler, useFormContext, Controller } from 'react-hook-form'
import { ChevronDown } from 'lucide-react'
import DatePicker from '@/components/ui/DatePicker'
import MonthYearPicker from '@/components/ui/MonthYearPicker'

// --- Form Wrapper ---
interface FormProps<T extends FieldValues, TContext = any, TTransformedValues extends FieldValues = T> extends Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onSubmit'> {
  form: UseFormReturn<T, TContext, TTransformedValues>
  onSubmit: SubmitHandler<TTransformedValues>
  children: React.ReactNode
}

export function Form<T extends FieldValues, TContext = any, TTransformedValues extends FieldValues = T>({ form, onSubmit, children, className, ...props }: FormProps<T, TContext, TTransformedValues>) {
  return (
    <FormProvider {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className={className} {...props}>
        {children}
      </form>
    </FormProvider>
  )
}

// --- Form Section ---
export function FormSection({ title, children }: { title: string, children: React.ReactNode }) {
  return (
    <div className="mb-6 last:mb-0">
      <h3 className="text-xs font-bold text-gray-500 uppercase tracking-widest mb-3 pb-2 border-b border-gray-100">
        {title}
      </h3>
      <div className="grid grid-cols-2 gap-x-5 gap-y-4">
        {children}
      </div>
    </div>
  )
}

// --- Form Field Wrapper ---
export function FormField({ colSpan = 1, className = '', children }: { colSpan?: number, className?: string, children: React.ReactNode }) {
  return (
    <div className={`${colSpan === 2 ? 'col-span-2' : 'col-span-1'} ${className}`}>
      {children}
    </div>
  )
}

// --- Form Label ---
interface FormLabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {
  required?: boolean
  hint?: React.ReactNode
}

export function FormLabel({ children, required, hint, className = '', ...props }: FormLabelProps) {
  return (
    <label className={`block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1 ${className}`} {...props}>
      {children}
      {required && <span className="text-red-500 ml-0.5">*</span>}
      {hint && <span className="normal-case font-normal tracking-normal ml-1.5 text-gray-400">— {hint}</span>}
    </label>
  )
}

// --- Form Input ---
interface FormInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
  name: string
}

export const FormInput = forwardRef<HTMLInputElement, FormInputProps>(
  ({ name, className = '', ...props }, ref) => {
    const { register, formState: { errors } } = useFormContext()
    const error = errors[name]?.message as string | undefined
    const isReadOnly = (props as any).readOnly

    return (
      <div className="w-full">
        <input
          {...register(name)}
          {...props}
          className={`w-full px-3 py-2 text-sm border rounded-lg placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-slate-800 transition-all ${error ? 'border-red-300' : 'border-gray-200'} ${isReadOnly ? 'bg-gray-100 text-gray-600 cursor-not-allowed' : 'bg-white'} ${className}`}
        />
        {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
      </div>
    )
  }
)
FormInput.displayName = 'FormInput'

// --- Form Select ---
interface FormSelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
  name: string
  options: string[] | { label: string; value: string }[]
}

export const FormSelect = forwardRef<HTMLSelectElement, FormSelectProps>(
  ({ name, options, className = '', ...props }, ref) => {
    const { register, watch, formState: { errors } } = useFormContext()
    const error = errors[name]?.message as string | undefined
    const value = watch(name)

    return (
      <div className="w-full">
        <div className="relative">
          <select
            {...register(name)}
            {...props}
            className={`w-full px-3 py-2 pr-8 text-sm border rounded-lg bg-white appearance-none focus:outline-none focus:ring-2 focus:ring-slate-800 transition-all ${error ? 'border-red-300' : 'border-gray-200'
              } ${!value ? 'text-gray-400' : 'text-gray-900'} ${className}`}
          >
            <option value="">Select…</option>
            {options.map((o) => {
              const val = typeof o === 'string' ? o : o.value
              const label = typeof o === 'string' ? o : o.label
              return <option key={val} value={val}>{label}</option>
            })}
          </select>
          <ChevronDown className="absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
        </div>
        {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
      </div>
    )
  }
)
FormSelect.displayName = 'FormSelect'

// --- Form Textarea ---
interface FormTextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  name: string
}

export const FormTextarea = forwardRef<HTMLTextAreaElement, FormTextareaProps>(
  ({ name, className = '', ...props }, ref) => {
    const { register, formState: { errors } } = useFormContext()
    const error = errors[name]?.message as string | undefined

    return (
      <div className="w-full">
        <textarea
          {...register(name)}
          {...props}
          className={`w-full px-3 py-2 text-sm border rounded-lg bg-white placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-slate-800 transition-all resize-none ${error ? 'border-red-300' : 'border-gray-200'
            } ${className}`}
        />
        {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
      </div>
    )
  }
)
FormTextarea.displayName = 'FormTextarea'

// --- Form DatePicker ---
interface FormDatePickerProps {
  name: string
  placeholder?: string
  maxDate?: string
}

export function FormDatePicker({ name, placeholder, maxDate }: FormDatePickerProps) {
  const { control, formState: { errors } } = useFormContext()
  const error = errors[name]?.message as string | undefined

  return (
    <div className="w-full">
      <Controller
        name={name}
        control={control}
        render={({ field: { value, onChange } }) => (
          <DatePicker
            value={value || ''}
            placeholder={placeholder}
            maxDate={maxDate}
            hasError={!!error}
            onChange={onChange}
          />
        )}
      />
      {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
    </div>
  )
}

// --- Form MonthYearPicker ---
interface FormMonthYearPickerProps {
  name: string
  placeholder?: string
}

export function FormMonthYearPicker({ name, placeholder }: FormMonthYearPickerProps) {
  const { control, formState: { errors } } = useFormContext()
  const error = errors[name]?.message as string | undefined

  return (
    <div className="w-full">
      <Controller
        name={name}
        control={control}
        render={({ field: { value, onChange } }) => (
          <MonthYearPicker
            value={value || ''}
            hasError={!!error}
            onChange={onChange}
            placeholder={placeholder}
          />
        )}
      />
      {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
    </div>
  )
}

// --- Form Checkbox ---
interface FormCheckboxProps extends React.InputHTMLAttributes<HTMLInputElement> {
  name: string
  label: React.ReactNode
}

export const FormCheckbox = forwardRef<HTMLInputElement, FormCheckboxProps>(
  ({ name, label, className = '', ...props }, ref) => {
    const { register, formState: { errors } } = useFormContext()
    const error = errors[name]?.message as string | undefined

    return (
      <div className="w-full">
        <label className="flex items-center gap-2 cursor-pointer">
          <input
            type="checkbox"
            {...register(name)}
            {...props}
            className={`w-4 h-4 rounded accent-slate-800 ${className}`}
          />
          <span className="text-sm text-gray-700">{label}</span>
        </label>
        {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
      </div>
    )
  }
)
FormCheckbox.displayName = 'FormCheckbox'


interface FormFileInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'value'> {
  name: string
  label?: React.ReactNode
}

export function FormFileInput({ name, label, className = '', accept = 'application/pdf', ...props }: FormFileInputProps) {
  const { control, formState: { errors }, getFieldState } = useFormContext()
  const { error } = getFieldState(name)
  const errorMsg = error?.message as string | undefined


  return (
    <div className="w-full">
      {label && (
        <label className="block text-[10px] font-semibold uppercase tracking-widest text-gray-500 mb-1">
          {label}
        </label>
      )}
      <Controller
        name={name}
        control={control}
        render={({ field: { value, onChange, ref } }) => (
          <div>
            <input
              type="file"
              ref={ref}
              accept={accept}
              onChange={(e) => onChange(e.target.files)}
              {...props}
              className={`block w-full text-sm text-gray-700 file:mr-4 file:py-2 file:px-3
                file:rounded-lg file:border-0 file:text-sm file:font-semibold
                file:bg-slate-800 file:text-white hover:file:bg-slate-700
                cursor-pointer focus:outline-none ${errorMsg ? 'border border-red-300 rounded-lg' : ''} ${className}`}
            />
            {typeof value === 'string' && value && (
              <a
                href={value}
                target="_blank"
                rel="noopener noreferrer"
                className="text-[10px] text-blue-600 underline mt-0.5 block truncate"
              >
                {value.split('/').pop()}
              </a>
            )}
          </div>
        )}
      />
      {errorMsg && <p className="text-[10px] text-red-500 mt-0.5">{errorMsg}</p>}
    </div>
  )
}


// --- Form File Upload ---
interface FormFileUploadProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type'> {
  name: string
}

export const FormFileUpload = forwardRef<HTMLInputElement, FormFileUploadProps>(
  ({ name, className = '', ...props }, ref) => {
    const { control, formState: { errors } } = useFormContext()
    const error = errors[name]?.message as string | undefined

    return (
      <div className="w-full">
        <Controller
          name={name}
          control={control}
          render={({ field: { onChange } }) => (
            <div className="relative">
              <input
                type="file"
                ref={ref}
                onChange={(e) => onChange(e.target.files)}
                {...props}
                className={`w-full px-3 py-2 text-sm border rounded-lg bg-white placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-slate-800 transition-all file:mr-3 file:py-1 file:px-3 file:rounded file:border-0 file:text-xs file:font-semibold file:bg-slate-100 file:text-slate-700 hover:file:bg-slate-200 ${error ? 'border-red-300' : 'border-gray-200'} ${className}`}
              />
            </div>
          )}
        />
        {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
      </div>
    )
  }
)
FormFileUpload.displayName = 'FormFileUpload'

// --- Form RadioGroup ---
interface FormRadioGroupProps extends React.FieldsetHTMLAttributes<HTMLFieldSetElement> {
  name: string
  options: { label: string; value: string }[] | string[]
  direction?: 'horizontal' | 'vertical'
}

export const FormRadioGroup = forwardRef<HTMLFieldSetElement, FormRadioGroupProps>(
  ({ name, options, direction = 'vertical', className = '', ...props }, ref) => {
    const { register, watch, formState: { errors } } = useFormContext()
    const error = errors[name]?.message as string | undefined
    const value = watch(name)

    const directionClass = direction === 'horizontal' ? 'flex flex-row gap-6' : 'flex flex-col gap-3'

    return (
      <div className="w-full">
        <fieldset ref={ref} className={`${directionClass} mt-3`} {...props}>
          {options.map((option) => {
            const val = typeof option === 'string' ? option : option.value
            const label = typeof option === 'string' ? option : option.label

            return (
              <label key={val} className="flex items-center gap-2 cursor-pointer">
                <input
                  type="radio"
                  value={val}
                  {...register(name)}
                  className={`w-4 h-4 accent-slate-800 cursor-pointer ${className}`}
                  checked={value === val}
                />
                <span className="text-sm text-gray-700">{label}</span>
              </label>
            )
          })}
        </fieldset>
        {error && <p className="text-[10px] text-red-500 mt-0.5">{error}</p>}
      </div>
    )
  }
)
FormRadioGroup.displayName = 'FormRadioGroup'
