import React, { useState } from "react";
import { useFormContext } from "react-hook-form";
import { PencilIcon } from "@heroicons/react/24/outline";
import { Button } from "../element/Button";
import FormError from "./FormError";

interface FormFieldProps {
    name: string;
    label?: string;
    children: React.ReactElement;
    viewMode?: boolean;
    maxLength?: number;
}

export function FormField({
    name,
    label,
    children,
    viewMode = false,
    maxLength,
}: FormFieldProps) {
    const [isEditing, setIsEditing] = useState(!viewMode);
    const {
        formState: { errors },
        watch,
        setValue,
        trigger,
    } = useFormContext();

    const value = watch(name);
    const error = errors[name]?.message as string;

    const handleChange = (newValue: any) => {
        setValue(name, newValue);
    };

    const handleEditEnd = async () => {
        await trigger(name);
        if (viewMode) {
            setIsEditing(false);
        }
    };

    const startEditing = () => {
        setIsEditing(true);
    };

    const renderViewMode = () => (
        <div
            className="w-full text-gray-700 hover:text-primary-600 min-h-[48px] flex items-center gap-2 relative cursor-pointer group transition-all duration-200 ease-out select-none"
            onClick={startEditing}
        >
            <span className="font-medium">
                {value || <span className="text-tertiary-400">点击编辑</span>}
            </span>
            <Button
                onClick={(e) => {
                    e.stopPropagation();
                    startEditing();
                }}
                size="xs"
                variant="ghost"
                leftIcon={<PencilIcon />}
                className="absolute -right-10 opacity-0 group-hover:opacity-100"
            />
        </div>
    );

    const enhancedChild = React.cloneElement(children, {
        value,
        onChange: (e: any) => {
            const newValue = e?.target?.value ?? e;
            handleChange(newValue);
        },
        onBlur: handleEditEnd,
        error,
    });

    return (
        <div 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-primary-600">
                        {label}
                    </label>
                    {maxLength && typeof value === "string" && (
                        <span className="text-sm text-tertiary-400">
                            {value.length || 0}/{maxLength}
                        </span>
                    )}
                </div>
            )}
            {viewMode && !isEditing ? renderViewMode() : enhancedChild}
            {error && !viewMode && <FormError error={error} />}
        </div>
    );
}