import { useFormContext } from 'react-hook-form';
import { useRef, useState } from 'react';
import { CheckIcon, PencilIcon, XMarkIcon } from '@heroicons/react/24/outline';
import FormError from './FormError';
import { Button } from '../element/Button';
export interface FormInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement | HTMLTextAreaElement>, 'type'> {
    name: string;
    label?: string;
    type?: 'text' | 'textarea' | 'password' | 'email' | 'number' | 'tel' | 'url' | 'search' | 'date' | 'time' | 'datetime-local';
    rows?: number;
    viewMode?: boolean;

}
export function FormInput({
    name,
    label,
    type = 'text',
    rows = 4,
    className,
    viewMode = false, // 默认为编辑模式
    ...restProps
}: FormInputProps) {
    const [isFocused, setIsFocused] = useState(false);
    const [isEditing, setIsEditing] = useState(!viewMode);
    const inputWrapper = useRef<HTMLDivElement>(null);
    const {
        register,
        formState: { errors },
        watch,
        setValue,
        trigger, // Add trigger from useFormContext
    } = useFormContext();
    const handleBlur = async () => {
        setIsFocused(false);
        await trigger(name); // Trigger validation for this field
        if (viewMode) {
            setIsEditing(false)
        }

    };
    const value = watch(name);
    const error = errors[name]?.message as string;
    const isValid = value && !error;
    const inputClasses = `
    w-full rounded-lg border bg-white px-4 py-2 outline-none
    transition-all duration-200 ease-out placeholder:text-gray-400
    ${error
            ? 'border-red-500 focus:border-red-500 focus:ring-2 focus:ring-red-200'
            : 'border-gray-200 hover:border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-100'
        }
    ${isFocused ? 'ring-2 ring-opacity-50' : ''}
    ${className || ''}
  `;

    const viewModeClasses = `
  w-full text-gray-700 hover:text-blue-600 min-h-[48px] 
  flex items-center gap-2 relative cursor-pointer group
  transition-all duration-200 ease-out select-none
`;

    const InputElement = type === 'textarea' ? 'textarea' : 'input';

    const renderViewMode = () => (
        <div
            className={viewModeClasses}
            onClick={() => setIsEditing(true)}
        >
            <span className="font-medium ">
                {value || <span className="text-gray-400">点击编辑</span>}
            </span>
            <Button
                onClick={(e) => {
                    e.stopPropagation();
                    setIsEditing(true);
                }}
                size='xs'
                variant='ghost'
                leftIcon={<PencilIcon />}
                className="absolute -right-10 opacity-0 group-hover:opacity-100 "
            >

            </Button>
        </div>
    );

    const renderEditMode = () => (
        <div className="relative">
            <InputElement
                {...register(name)}
                type={type !== 'textarea' ? type : undefined}
                rows={type === 'textarea' ? rows : undefined}
                {...restProps}
                onFocus={() => setIsFocused(true)}
                onBlur={handleBlur}
                className={inputClasses}
                aria-label={label}
                autoFocus
            />
            <div className="
            absolute right-3 top-1/2 -translate-y-1/2
            flex items-center space-x-2
          ">
                {value && isFocused && (
                    <button
                        type="button"
                        className="
                  p-1.5 rounded-full text-gray-400 
                  hover:text-gray-600 hover:bg-gray-100
                  transition-all duration-200 ease-out
                "
                        onMouseDown={(e) => e.preventDefault()}
                        onClick={() => setValue(name, '')}
                        aria-label={`清除${label}`}
                        tabIndex={-1}
                    >
                        <XMarkIcon className="w-4 h-4" />
                    </button>
                )}
                {isValid && (
                    <CheckIcon className="
                text-green-500 w-4 h-4
                animate-fade-in duration-200
              " />
                )}
                {error && <FormError error={error} />}
            </div>
        </div>
    );
    return (
        <div ref={inputWrapper} className="flex flex-col gap-2">
            {label && <div className="flex justify-between items-center px-0.5">
                <label className="
            text-sm font-medium text-gray-700
            transition-colors duration-200
            group-focus-within:text-blue-600
          ">
                    {label}
                </label>
                {restProps.maxLength && (
                    <span className="text-sm text-gray-500">
                        {value?.length || 0}/{restProps.maxLength}
                    </span>
                )}
            </div>}
            {viewMode && !isEditing ? renderViewMode() : renderEditMode()}
        </div>
    );
}