'use client';

import { useControllableValue } from 'ahooks';
import { cn } from '@/lib';
import { CheckIcon, UploadImgIcon } from '@/assets/common';
import IconFont from '@/components/ui/iconFont';

type BackgroundItem = {
  item?: any;
  selected?: boolean;
  onSelect?: () => void;
  onDelete?: () => void;
};

const ItemRender = (props: BackgroundItem) => {
  const { item, selected, onSelect, onDelete } = props;

  const handleDelete = (e: React.MouseEvent<HTMLSpanElement>) => {
    e.stopPropagation();
    e.preventDefault();
    onDelete?.();
  };

  return (
    <div
      className={cn(
        'relative flex h-38 items-end justify-center rounded-[10px] pb-1 hover:cursor-pointer hover:border-2 hover:border-[rgba(0,102,255,1)]',
        selected && 'border-2 border-[rgba(0,102,255,1)]'
      )}
      onClick={onSelect}
      style={{
        backgroundImage: `url(${item.url})`,
        backgroundSize: 'cover', // 等比例缩放图片直到铺满容器
        backgroundPosition: 'center', // 图片居中显示
        backgroundRepeat: 'no-repeat', // 不重复
      }}
    >
      {selected && (
        <span className="absolute right-0 bottom-0 flex h-4 w-5 items-center justify-center rounded-tl-[5px] bg-[rgba(0,102,255,1)]">
          <CheckIcon />
        </span>
      )}
      <span onClick={handleDelete} className="hover:text-[#E2503D]">
        <IconFont type="icon-delete" size={20} />
      </span>
    </div>
  );
};

type BackgroundProps = {
  value?: string;
  onChange?: (value: string) => void;
  defaultBackgrounds?: BackgroundItem[];
} & React.HTMLAttributes<HTMLDivElement>;

export default function Background(props: BackgroundProps) {
  const { defaultBackgrounds = [], ...rest } = props;
  const [value, onChange] = useControllableValue(props);

  const handleUpload = () => {};

  const handleDelete = () => {};

  const items = [
    {
      value: '1',
      url: '/test.png',
    },
    {
      value: '2',
      url: '/test.png',
    },
    {
      value: '3',
      url: '/test.png',
    },
    {
      value: '4',
      url: '/test.png',
    },
  ];

  return (
    <div {...rest}>
      <div className="grid grid-cols-3 gap-2.5">
        {items.map((i) => (
          <ItemRender
            selected={value === i.value}
            onSelect={() => onChange(i.value)}
            onDelete={handleDelete}
            key={i.value}
            item={i}
          />
        ))}
        <div
          onClick={handleUpload}
          title="Upload Background Image"
          className={cn(
            'h-38 w-full overflow-hidden rounded-lg hover:cursor-pointer',
            'bg-text-color/10 flex items-center justify-center text-[#C3C4D5] hover:text-white'
          )}
        >
          <UploadImgIcon />
        </div>
      </div>
    </div>
  );
}
