import { type FC, useCallback, useMemo, useState } from "react";
import { useEditorStore, type ToolType } from "@/pages/editor/store/editorStore";
import { useSingleUpload } from "@/pages/uploader/hooks/useUploaderData";
import { CloseCircle } from "iconsax-react";
import { useDropzone } from "react-dropzone";
import VideoUploadZone from "@/components/VideoUploadZone";

const VideoInput: FC = () => {
    const { objects, addObject, setSelectedObjectId, setTool, deleteObject } =
        useEditorStore();
    const { mutateAsync: uploadFile } = useSingleUpload();
    const [isUploading, setIsUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);

    const onDrop = useCallback(
        async (acceptedFiles: File[]) => {
            if (acceptedFiles.length === 0) return;

            setIsUploading(true);
            setUploadProgress(0);
            try {
                for (let i = 0; i < acceptedFiles.length; i++) {
                    const file = acceptedFiles[i];
                    try {
                        const result = await uploadFile({
                            file,
                            onProgress: (fileProgress) => {
                                const overall = Math.round(
                                    ((i + fileProgress / 100) / acceptedFiles.length) * 100
                                );
                                setUploadProgress(overall);
                            },
                        });
                        const videoUrl = result?.data?.url;
                        if (!videoUrl) continue;
                        const videoId = `video-${Date.now()}-${Math.random()}`;
                        const newVideo = {
                            id: videoId,
                            type: "video" as ToolType,
                            x: 100,
                            y: 100,
                            width: 400,
                            height: 300,
                            videoUrl,
                        };
                        addObject(newVideo);
                        setSelectedObjectId(newVideo.id);
                        setTool("select");
                    } catch {
                        // TODO: show error toast
                    }
                }
            } finally {
                setIsUploading(false);
                setUploadProgress(0);
            }
        },
        [addObject, setSelectedObjectId, setTool, uploadFile]
    );

    const { getRootProps, getInputProps } = useDropzone({
        onDrop,
        accept: {
            'video/*': ['.mp4', '.webm', '.ogg', '.mov', '.avi']
        },
        multiple: true,
        disabled: isUploading,
    });

    const videoObjects = useMemo(() => {
        return objects.filter((obj) => obj.type === "video");
    }, [objects]);

    const handleDeleteVideo = (videoId: string) => {
        deleteObject(videoId);
    };

    return (
        <div className="space-y-4">
            <div className="text-base font-bold">ویدیو</div>

            <VideoUploadZone
                getRootProps={getRootProps}
                getInputProps={getInputProps}
                isLoading={isUploading}
                uploadProgress={isUploading ? uploadProgress : undefined}
            />

            {videoObjects.length > 0 && (
                <div className="space-y-2">
                    <div className="text-xs font-bold">ویدیو های آپلود شده</div>
                    <div className="flex flex-col gap-2">
                        {videoObjects.map((videoObject) => (
                            <div
                                key={videoObject.id}
                                className=" relative"
                            >
                                <video
                                    src={videoObject.videoUrl}
                                    className="w-full rounded-lg"
                                    muted
                                />
                                <button
                                    onClick={() => handleDeleteVideo(videoObject.id)}
                                    className="absolute -right-1 -top-2 shadow-md bg-white size-5 rounded-full flex justify-center items-center hover:bg-gray-100 transition-colors"
                                >
                                    <CloseCircle size={16} color="red" />
                                </button>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
};

export default VideoInput;

