"use client"

import * as React from "react"
import { cn } from "@/lib/utils"

export interface InputProps
  extends React.InputHTMLAttributes<HTMLInputElement> {
    label?: string
    error?: string
    helper?: string
    leftIcon?: React.ReactNode
    rightIcon?: React.ReactNode
    loading?: boolean
    variant?: "default" | "filled" | "outlined" | "ghost"
  }

const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ 
    className, 
    type, 
    label, 
    error, 
    helper, 
    leftIcon, 
    rightIcon, 
    loading = false,
    variant = "default",
    ...props 
  }, ref) => {
    const [focused, setFocused] = React.useState(false)
    const [filled, setFilled] = React.useState(false)

    const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
      setFocused(true)
      props.onFocus?.(e)
    }

    const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
      setFocused(false)
      setFilled(e.target.value.length > 0)
      props.onBlur?.(e)
    }

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      setFilled(e.target.value.length > 0)
      props.onChange?.(e)
    }

    const variants = {
      default: `
        bg-surface border border-border-subtle
        focus:border-primary focus:ring-2 focus:ring-primary/20
        hover:border-border
        ${error ? 'border-destructive focus:border-destructive focus:ring-destructive/20' : ''}
      `,
      filled: `
        bg-surface-elevated border-0 border-b-2 border-border-subtle
        focus:border-primary focus:ring-0
        hover:border-border
        ${error ? 'border-b-destructive focus:border-destructive' : ''}
      `,
      outlined: `
        bg-transparent border-2 border-border-subtle
        focus:border-primary focus:ring-2 focus:ring-primary/20
        hover:border-border
        ${error ? 'border-destructive focus:border-destructive focus:ring-destructive/20' : ''}
      `,
      ghost: `
        bg-transparent border-0 border-b border-border-subtle
        focus:border-primary focus:ring-0
        hover:border-border
        ${error ? 'border-b-destructive focus:border-destructive' : ''}
      `
    }

    const inputClasses = cn(
      "flex h-10 w-full rounded-lg px-3 py-2 text-sm transition-all duration-200 ease-out",
      "file:text-foreground placeholder:text-muted-foreground",
      "disabled:cursor-not-allowed disabled:opacity-50",
      "outline-none focus:outline-none",
      "read-only:cursor-default read-only:bg-surface/50",
      variants[variant],
      leftIcon && "ps-10",
      rightIcon && "pe-10",
      (leftIcon && rightIcon) && "px-10",
      error && "text-destructive",
      className
    )

    const containerClasses = cn(
      "relative w-full",
      label && "space-y-2"
    )

    const labelClasses = cn(
      "text-sm font-medium transition-all duration-200",
      error ? "text-destructive" : "text-foreground",
      focused && "text-primary",
      filled && "text-muted-foreground"
    )

    return (
      <div className={containerClasses}>
        {label && (
          <label className={labelClasses}>
            {label}
          </label>
        )}
        
        <div className="relative">
          {/* Left Icon */}
          {leftIcon && (
            <div className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none">
              {leftIcon}
            </div>
          )}
          
          {/* Input Field */}
          <input
            type={type}
            className={inputClasses}
            ref={ref}
            onFocus={handleFocus}
            onBlur={handleBlur}
            onChange={handleChange}
            disabled={loading}
            aria-invalid={!!error}
            aria-describedby={error ? `${props.id}-error` : helper ? `${props.id}-helper` : undefined}
            {...props}
          />
          
          {/* Right Icon or Loading */}
          {(rightIcon || loading) && (
            <div className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground pointer-events-none">
              {loading ? (
                <svg
                  className="animate-spin h-4 w-4"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  ></circle>
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  ></path>
                </svg>
              ) : (
                rightIcon
              )}
            </div>
          )}
          
          {/* Focus Ring */}
          {focused && (
            <div className="absolute inset-0 rounded-lg pointer-events-none">
              <div className="absolute inset-0 rounded-lg border-2 border-primary/20 animate-pulse" />
            </div>
          )}
        </div>
        
        {/* Helper Text */}
        {helper && !error && (
          <p className="text-xs text-muted-foreground mt-1" id={`${props.id}-helper`}>
            {helper}
          </p>
        )}
        
        {/* Error Message */}
        {error && (
          <p className="text-xs text-destructive mt-1 flex items-center gap-1" id={`${props.id}-error`}>
            <svg
              className="h-3 w-3 flex-shrink-0"
              fill="currentColor"
              viewBox="0 0 20 20"
            >
              <path
                fillRule="evenodd"
                d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
                clipRule="evenodd"
              />
            </svg>
            {error}
          </p>
        )}
      </div>
    )
  }
)
Input.displayName = "Input"

export { Input }

// Enhanced Search Input Component
export const SearchInput = React.forwardRef<
  HTMLInputElement,
  Omit<InputProps, 'leftIcon'> & {
    onClear?: () => void
    showClear?: boolean
  }
>(({ className, showClear = true, onClear, value, ...props }, ref) => {
  const [focused, setFocused] = React.useState(false)

  const handleClear = () => {
    onClear?.()
    // Trigger change event
    const event = new Event('input', { bubbles: true })
    const input = ref as React.RefObject<HTMLInputElement>
    if (input?.current) {
      input.current.value = ''
      input.current.dispatchEvent(event)
    }
  }

  return (
    <div className="relative">
      <Input
        ref={ref}
        type="search"
        leftIcon={
          <svg
            className="h-4 w-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
            />
          </svg>
        }
        rightIcon={
          showClear && value && (
            <button
              type="button"
              onClick={handleClear}
              className="text-muted-foreground hover:text-foreground transition-colors"
            >
              <svg
                className="h-4 w-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          )
        }
        className={cn(
          "ps-10 pe-10",
          focused && "shadow-lg shadow-primary/10",
          className
        )}
        onFocus={(e) => {
          setFocused(true)
          props.onFocus?.(e)
        }}
        onBlur={(e) => {
          setFocused(false)
          props.onBlur?.(e)
        }}
        {...props}
      />
    </div>
  )
})
SearchInput.displayName = "SearchInput"

// File Input Component
export const FileInput = React.forwardRef<
  HTMLInputElement,
  Omit<InputProps, 'type'> & {
    accept?: string
    multiple?: boolean
    onFileSelect?: (files: FileList | null) => void
  }
>(({ className, onFileSelect, accept, multiple = false, ...props }, ref) => {
  const [dragActive, setDragActive] = React.useState(false)
  const [fileName, setFileName] = React.useState<string>("")

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true)
    } else if (e.type === "dragleave") {
      setDragActive(false)
    }
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      setFileName(e.dataTransfer.files[0].name)
      onFileSelect?.(e.dataTransfer.files)
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setFileName(e.target.files[0].name)
      onFileSelect?.(e.target.files)
    }
  }

  return (
    <div className="relative">
      <Input
        ref={ref}
        type="file"
        accept={accept}
        multiple={multiple}
        className={cn(
          "file:me-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 cursor-pointer",
          dragActive && "border-primary bg-primary/5",
          className
        )}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
        onChange={handleChange}
        {...props}
      />
      
      {fileName && (
        <div className="absolute inset-y-0 right-0 flex items-center pe-3">
          <span className="text-xs text-muted-foreground truncate max-w-32">
            {fileName}
          </span>
        </div>
      )}
    </div>
  )
})
FileInput.displayName = "FileInput"
