import { BackendImage, ImageProp, ImageSelect, UploadFolderType } from "@/types/dashboard/image"
import ImageStatus from "./ImageStatus"
import { useEffect, useState } from "react"
import ImagePicker from "./ImagePicker"
import { ImagePlus, X } from "lucide-react"
import { Label } from "../ui/label"
import { Input } from "../ui/input"
import { cn } from "@/lib/utils"


type SectionProp = {
    data: BackendImage[],
    edit?: boolean,
    processing: boolean,
    max?: number,
    onChange: (value: ImageSelect[]) => void,
    errors?: any,
    room_catagories?: { id: number, name: string }[],
    uploadFolderType?: UploadFolderType,
    itemName?: string;   // for filename + alt
    itemId?: number;     // optional (for folder structure)
}

const ImageBox = ({ image, disabled, onDelete, className }: { image: ImageProp, disabled?: boolean, onDelete?: () => void, className?: string }) => {

    const { url } = image

    return <div className={cn(`relative border h-full  p-1 ${disabled ? '' : 'border-blue-300 border-dashed bg-blue-50'} dark:bg-secondary dark:border-blue-800 flex justify-center items-center rounded-sm overflow-hidden group`, className)}   >
        {url ? (
            <>
                <img
                    src={url ?? ''}
                    width={460}
                    height={300}
                    className="object-cover w-full h-full rounded-sm"
                    alt="Desktop Banner"
                />

                <ImageStatus status={'loading'} className="bottom-1.5 left-1.5" />
                {/* {title && <Label className="text-xs font-medium bg-black/30 px-2 text-white absolute top-1 h-6 left-1 rounded-tl-sm rounded-br-sm">  {title} </Label>} */}

                <button
                    type="button"
                    className={`absolute top-2 right-2 bg-white/40 text-red-600 border cursor-pointer border-red-600 p-0.5 rounded-full hover:bg-red-600 hover:text-white  z-2 opacity-100 group-hover:opacity-100 transition-opacity ${disabled && 'hidden'}`}
                    onClick={onDelete}
                    disabled={disabled}
                >
                    <X className="w-3 h-3" />
                </button>
            </>
        ) : (
            <Label className={`text-blue-400 h-full dark:text-blue-700 ${!disabled && 'cursor-pointer'} w-full h-full flex flex-col gap-2 items-center justify-center`}>
                <ImagePlus className="w-6 h-6" />
                <span className="text-sm">Upload Banner</span>
                <Input
                    className="hidden"
                    type="file"
                    disabled={disabled}
                    accept="image/png, image/jpeg, image/webp"
                // onChange={(e) => {
                //     const file = e.target.files?.[0];
                //     if (file && onChange) onChange(file);
                // }}
                />
            </Label>
        )}
    </div>
}

export default function ImageSectionCard({ data, edit, processing, max = 1, onChange, uploadFolderType, itemName, itemId }: SectionProp) {

    const [images, setImages] = useState<ImageProp[]>(data || [])

    const updateImages = (selected: ImageProp[]) => {

        const formattedImages = selected.map((img, index) => ({
            id: img.id,
            role: index === 0 ? 'thumbnail' : 'gallery',
            sort_order: index,
        }))

        onChange(formattedImages)
    }

    useEffect(() => {
        setImages(data || [])
    }, [data])

    return <div className={`space-y-4  ${edit && 'p-2 rounded-sm  border-2  border-dashed bg-card'}`}>
        {/* <SectionTitle icon='Image' title='Room Images' /> */}

        <div className="grid grid-cols-4 gap-2 w-full  ">
            {
                images.map((img, index) => {
                    return <ImageBox disabled={!edit || processing} key={index} image={img} onDelete={() => setImages(prev => {
                        const updated = prev.filter((_, i) => i !== index)
                        updateImages(updated)
                        return updated
                    })} className='bg-white h-34' />
                })
            }

            {images.length < max && edit &&
                <ImagePicker
                    selected={images}
                    onSelect={(selectedImages) => setImages(prev => {
                        const updated = [...prev, ...selectedImages]
                        updateImages(updated)
                        return updated
                    })}
                    max={max}
                    uploadFolderType={uploadFolderType}
                    itemName={itemName}
                    itemId={itemId}
                    className={`text-blue-400 border rounded-sm dark:text-blue-700 w-full  flex flex-col gap-2 items-center justify-center py-6  bg-background h-34`}
                >
                    <ImagePlus className="w-10 h-10" />
                    <span className="text-sm text-muted-foreground font-medium">Add new image</span>
                    <span className="text-xs text-muted-foreground">JPG, PNG, WebP | Max size: 2MB</span>
                </ImagePicker>
            }
        </div>
    </div>
}