import { useFormContext } from "react-hook-form";
import React, { useState } from "react";
import { motion } from "framer-motion";
import { CheckIcon } from "@heroicons/react/24/outline";

export interface FormCheckboxProps
	extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "type"> {
	name: string;
	label?: string;
	viewMode?: boolean;
}

export function FormCheckbox({
	name,
	label,
	className,
	viewMode = false,
	...restProps
}: FormCheckboxProps) {
	const [isHovered, setIsHovered] = useState(false);
	const {
		register,
		formState: { errors },
		watch,
		setValue,
	} = useFormContext();

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

	const handleToggle = () => {
		setValue(name, !value);
	};

	const checkboxClasses = `
    w-6 h-6 rounded border 
    transition-all duration-200 ease-out
    flex items-center justify-center
    cursor-pointer
    ${
		value
			? "bg-[#00308F] border-[#00308F]"
			: "bg-white border-gray-200 hover:border-gray-300"
	}
    ${error ? "border-red-500" : ""}
    ${className || ""}
  `;

	const labelClasses = `
    text-sm font-medium 
    ${error ? "text-red-500" : "text-gray-700"}
    ${value ? "text-[#00308F]" : ""}
    transition-colors duration-200
  `;

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

	const renderViewMode = () => (
		<div className={viewModeClasses}>
			<div className={checkboxClasses}>
				{value && <CheckIcon className="w-4 h-4 text-white" />}
			</div>
			<span className="font-medium">{label}</span>
		</div>
	);

	const renderEditMode = () => (
		<motion.div
			onHoverStart={() => setIsHovered(true)}
			onHoverEnd={() => setIsHovered(false)}
			className="relative inline-flex items-center gap-3">
			<input
				type="checkbox"
				className="sr-only"
				{...register(name)}
				{...restProps}
			/>

			<motion.div
				onClick={handleToggle}
				className={checkboxClasses}
				whileTap={{ scale: 0.95 }}
				whileHover={{ scale: 1.05 }}>
				{value && (
					<motion.div
						initial={{ opacity: 0, scale: 0.5 }}
						animate={{ opacity: 1, scale: 1 }}
						exit={{ opacity: 0, scale: 0.5 }}
						transition={{
							duration: 0.2,
							ease: [0.4, 0, 0.2, 1], // 添加缓动函数使动画更流畅
						}}>
						<CheckIcon className="w-4 h-4 text-white" />
					</motion.div>
				)}
			</motion.div>

			{label && (
				<motion.label
					onClick={handleToggle}
					className={`${labelClasses} cursor-pointer`}
					whileHover={{ x: 2 }}>
					{label}
				</motion.label>
			)}

			{error && (
				<motion.span
					initial={{ opacity: 0, y: -10 }}
					animate={{ opacity: 1, y: 0 }}
					className="absolute left-0 top-full mt-1 text-xs text-red-500">
					{error}
				</motion.span>
			)}
		</motion.div>
	);

	return (
		<div className="flex flex-col gap-2">
			{viewMode ? renderViewMode() : renderEditMode()}
		</div>
	);
}
