'use client';
import { Button, IconButton } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import Image from 'next/image';
import { Checkbox } from '@/components/ui/checkbox';
import React, { useState } from 'react';
import { Tag } from '@/components/ui/tag';
import { ImageViewer } from '@/components/ui/image-viewer';
import { useImageViewer } from '@/hooks/useImageViewer';
import { useTranslations } from 'next-intl';

type BackgroundItem = {
  backgroundId: number;
  imgUrl: string;
  isDefault: boolean;
  inUse?: boolean;
};

const BackgroundImageViewerAction = ({
  datas,
  backgroundId,
  isSelected,
  onChange,
}: {
  datas: BackgroundItem[];
  backgroundId: number;
  isSelected: boolean;
  onChange: (backgroundId: number) => void;
}) => {
  const tCommon = useTranslations('common');
  const handleSelect = () => {
    // 如果只有一张背景且当前已选中，不允许取消选中
    if (datas.length === 1 && isSelected) {
      return;
    }
    onChange(backgroundId);
  };

  return (
    <>
      <div className="bg-outline-normal h-6 w-px" />
      <div
        className="bg-surface-element-light-normal flex h-8 cursor-pointer items-center justify-center gap-2 rounded-full px-3 backdrop-blur-lg"
        onClick={() => handleSelect()}
      >
        <Checkbox shape="round" checked={isSelected} />
        <div className="txt-label-s">{tCommon('select')}</div>
      </div>
    </>
  );
};

const BackgroundItemCard = ({
  item,
  selected,
  inUse,
  onClick,
  onImagePreview,
  totalCount,
}: {
  item: BackgroundItem;
  selected: boolean;
  inUse: boolean;
  onClick: () => void;
  onImagePreview: () => void;
  totalCount: number;
}) => {
  const tCommon = useTranslations('common');
  const handleClick = () => {
    // 如果只有一张背景且当前已选中，不允许取消选中
    if (totalCount === 1 && selected) {
      return;
    }
    onClick();
  };

  return (
    <div className="group relative cursor-pointer" onClick={handleClick}>
      <div
        className={cn(
          'bg-surface-element-normal relative aspect-[3/4] overflow-hidden rounded-lg',
          selected && 'border-primary-normal border-2 border-solid'
        )}
      >
        <Image src={item.imgUrl || ''} alt={''} fill className="object-cover" />
      </div>
      {item.isDefault && (
        <Tag className="absolute top-2 left-2" variant="dark" size="small">
          {tCommon('default')}
        </Tag>
      )}
      {inUse && <Checkbox shape="round" checked className="absolute top-2 right-2" />}
      <IconButton
        className="absolute right-2 bottom-2 opacity-0 transition-opacity group-hover:opacity-100"
        size="xs"
        variant="contrast"
        onClick={(e) => {
          e.stopPropagation();
          onImagePreview();
        }}
      >
        <i className="iconfont icon-icon-fullImage" />
      </IconButton>
    </div>
  );
};

export default function Background() {
  const [selectId, setSelectId] = useState<number | undefined>(1);

  // 静态数据：模拟背景图片列表
  const backgroundList: BackgroundItem[] = [
    {
      backgroundId: 0,
      imgUrl: 'https://picsum.photos/400/600?random=1',
      isDefault: true,
      inUse: true,
    },
    {
      backgroundId: 1,
      imgUrl: 'https://picsum.photos/400/600?random=2',
      isDefault: false,
    },
    {
      backgroundId: 2,
      imgUrl: 'https://picsum.photos/400/600?random=3',
      isDefault: false,
    },
    {
      backgroundId: 3,
      imgUrl: 'https://picsum.photos/400/600?random=4',
      isDefault: false,
    },
  ];

  // 当前使用的背景
  const currentBackgroundImg = backgroundList.find((item) => item.inUse)?.imgUrl;

  // 静态数据：是否解锁生成图片功能
  const isUnlock = true;

  // 图片查看器
  const {
    isOpen: isViewerOpen,
    currentIndex: viewerIndex,
    openViewer,
    closeViewer,
    handleIndexChange,
  } = useImageViewer();

  const handleConfirm = async () => {};

  const handleImagePreview = (index: number) => {
    openViewer(backgroundList?.map((item) => item.imgUrl || '') || [], index);
  };

  return (
    <>
      <div className="flex h-full flex-col">
        <div className="flex-1 overflow-y-auto">
          <div className="grid grid-cols-2 gap-4">
            {backgroundList?.map((item, index) => (
              <BackgroundItemCard
                key={item.backgroundId}
                selected={selectId === item.backgroundId}
                inUse={item.imgUrl === currentBackgroundImg}
                item={item}
                onClick={() => setSelectId(item.backgroundId)}
                onImagePreview={() => handleImagePreview(index)}
                totalCount={backgroundList?.length || 0}
              />
            ))}
          </div>
        </div>
      </div>

      <ImageViewer
        images={backgroundList?.map((item) => item.imgUrl || '') || []}
        currentIndex={viewerIndex}
        open={isViewerOpen}
        onClose={closeViewer}
        onIndexChange={handleIndexChange}
        showChooseButton={false}
        ActionComponent={() => {
          return (
            <BackgroundImageViewerAction
              datas={backgroundList || []}
              backgroundId={backgroundList?.[viewerIndex]?.backgroundId || 0}
              isSelected={selectId === backgroundList?.[viewerIndex]?.backgroundId}
              onChange={setSelectId}
            />
          );
        }}
      />
    </>
  );
}
