'use client';

import { useState, useCallback } from 'react';
import { Button, IconButton } from '@/components/ui/button';
import { AvatarCropModal } from '@/components/ui/avatar-crop-modal';
import Image from 'next/image';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { useTranslations } from 'next-intl';

interface AvatarSettingProps {
  isOpen: boolean;
  onClose: () => void;
  currentAvatar?: string;
  className?: string;
}

const AvatarSetting = ({ isOpen, onClose, currentAvatar, className }: AvatarSettingProps) => {
  const t = useTranslations('profile.avatarSetting');
  const [showCropModal, setShowCropModal] = useState(false);
  const [tempImageUrl, setTempImageUrl] = useState<string>('');

  // 处理文件上传
  const handleFileUpload = useCallback(
    (files: File[]) => {
      if (files.length > 0) {
        const file = files[0];

        // 验证文件类型
        if (!file.type.startsWith('image/')) {
          toast.error(t('selectImageFile'));
          return;
        }

        // 排除 GIF 格式
        if (file.type === 'image/gif') {
          toast.error(t('gifNotSupported'));
          return;
        }

        // 验证文件大小 (5MB)
        if (file.size > 10 * 1024 * 1024) {
          toast.error(t('imageSizeLimit'));
          return;
        }

        // 创建预览URL
        const url = URL.createObjectURL(file);
        setTempImageUrl(url);
        setShowCropModal(true);
      }
    },
    [t]
  );

  // 处理文件选择
  const handleFileSelect = useCallback(() => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/jpeg,image/jpg,image/png';

    input.onchange = (e) => {
      const target = e.target as HTMLInputElement;
      if (target.files && target.files.length > 0) {
        handleFileUpload(Array.from(target.files));
      }
    };

    input.click();
  }, [handleFileUpload]);

  // 处理裁剪确认
  const handleCropConfirm = useCallback(() => {
    setShowCropModal(false);
    setTempImageUrl('');
    onClose();
  }, [onClose]);

  // 处理裁剪取消
  const handleCropCancel = useCallback(() => {
    setShowCropModal(false);
    if (tempImageUrl && tempImageUrl !== currentAvatar) {
      URL.revokeObjectURL(tempImageUrl);
    }
    setTempImageUrl('');
  }, [tempImageUrl, currentAvatar]);

  // 处理关闭按钮点击
  const handleClose = useCallback(() => {
    onClose();
  }, [onClose]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-40 flex items-center justify-center">
      {/* 背景遮罩 */}
      <div className="bg-background-default shadow-s absolute inset-0" />

      {/* 头像设置内容 */}
      <div
        className={cn('relative flex size-full flex-col items-center justify-center', className)}
      >
        {/* 关闭按钮 */}
        <div className="absolute top-6 left-6 z-20">
          <IconButton variant="tertiaryDark" size="large" onClick={handleClose}>
            <i className="iconfont icon-close text-white" />
          </IconButton>
        </div>

        <div className="-mt-16 flex flex-col items-center justify-center">
          {/* 头像预览区域 */}
          <div
            className="size-[300px] rounded-[999px] bg-cover bg-center bg-no-repeat"
            style={{
              ...(currentAvatar && { backgroundImage: `url('${currentAvatar}')` }),
              backgroundColor: currentAvatar ? 'transparent' : '#352e3e',
            }}
          >
            {!currentAvatar && (
              <div className="flex h-full w-full items-center justify-center">
                <i className="iconfont icon-user text-6xl text-white opacity-50" />
              </div>
            )}
          </div>

          {/* 文件格式提示 */}
          <div className="txt-body-l mt-8 text-center">
            <p>{t('uploadPrompt')}</p>
          </div>

          {/* 底部操作按钮 */}
          <div className="mt-8">
            {/* 上传按钮 */}
            <Button onClick={handleFileSelect}>{t('upload')}</Button>
          </div>
        </div>
      </div>

      {/* 头像裁剪弹窗 - 更高层级 */}
      {tempImageUrl && showCropModal && (
        <AvatarCropModal
          isOpen={true}
          shouldUpdateUser
          onClose={handleCropCancel}
          image={tempImageUrl}
          onConfirm={handleCropConfirm}
          onCancel={handleCropCancel}
          needCheck
        />
      )}
    </div>
  );
};

export default AvatarSetting;
