import React, { useState, useRef, useEffect, forwardRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { ImageUp, Library, Play, Pause, RefreshCw, Wand2, Users, CircleX, ReplaceAll, X, TriangleAlert, Loader2 } from 'lucide-react';
import { cn } from '@/public/lib/utils';
import { CharacterEditor } from './character-editor';
import ImageBlurTransition from './ImageBlurTransition';
import FloatingGlassPanel from './FloatingGlassPanel';
import { ReplaceCharacterPanel } from './replace-character-panel';
import { CharacterLibrarySelector } from './character-library-selector';
import HorizontalScroller from './HorizontalScroller';
import { useEditData } from '@/components/pages/work-flow/use-edit-data';
import { useSearchParams } from 'next/navigation';
import { RoleEntity } from '@/app/service/domain/Entities';
import { Role } from '@/api/DTO/movieEdit';

interface CharacterTabContentProps {
  originalRoles: Role[];
  onClose: () => void;
  onApply: () => void;
  setActiveTab: (tabId: string) => void;
}


export const CharacterTabContent = forwardRef<
  { switchBefore: (tabId: string) => boolean, saveOrCloseBefore: () => void },
CharacterTabContentProps
>((props, ref) => {
  const { onClose, onApply, setActiveTab, originalRoles } = props;
  const [isReplacePanelOpen, setIsReplacePanelOpen] = useState(false);
  const [replacePanelKey, setReplacePanelKey] = useState(0);
  const [ignoreReplace, setIgnoreReplace] = useState(false);
  const [isReplaceLibraryOpen, setIsReplaceLibraryOpen] = useState(false);
  const [isRemindReplacePanelOpen, setIsRemindReplacePanelOpen] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [enableAnimation, setEnableAnimation] = useState(true);
  const [showAddToLibrary, setShowAddToLibrary] = useState(true);
  const characterEditorRef = useRef<any>(null);
  const [isInitialized, setIsInitialized] = useState(false);
  const [isRegenerate, setIsRegenerate] = useState(false);
  const [isLoadingShots, setIsLoadingShots] = useState(false);
  const [isLoadingLibrary, setIsLoadingLibrary] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [isUpdate, setIsUpdate] = useState(false);
  const [triggerType, setTriggerType] = useState<'tab' | 'apply' | 'user'>('tab');
  const [nextToTabId, setNextToTabId] = useState<string>('');
  const [nextToUserIndex, setNextToUserIndex] = useState<number>(-1);

  const {
    loading,
    roleData,
    selectRole,
    selectedRole,
    userRoleLibrary,
    optimizeRoleText,
    updateRoleText,
    regenerateRole,
    fetchUserRoleLibrary,
    uploadImageAndUpdateRole,
    // role shot
    shotSelectionList,
    fetchRoleShots,
    applyRoleToSelectedShots,
    saveRoleToLibrary
  } = useEditData('role');
  const searchParams = useSearchParams();
  const episodeId = searchParams.get('episodeId');

  // 暴露方法给父组件
  React.useImperativeHandle(ref, () => ({
    switchBefore: (tabId: string) => {
      setNextToTabId(tabId);
      // 判断 角色是否修改
      const currentIndex = getCurrentIndex();
      const isChange = currentIndex !== -1 && isRoleChange(originalRoles[currentIndex]);
      console.log('switchBefore', isChange);
      if (isChange) {
        setTriggerType('tab');
        setIsRemindReplacePanelOpen(true);
      }
      return isChange;
    },
    saveOrCloseBefore: () => {
      console.log('saveOrCloseBefore');
      // 判断 角色是否修改
      const currentIndex = getCurrentIndex();
      if (currentIndex !== -1 && isRoleChange(originalRoles[currentIndex])) {
        setTriggerType('apply');
        handleStartReplaceCharacter();
      } else {
        onClose();
      }
    }
  }));


  useEffect(() => {
    console.log('-==========roleData===========-', roleData);
    // 只在初始化且有角色数据时执行
    if (!isInitialized && (roleData?.length || 0) > 0) {
      selectRole(roleData[0]);
      setIsInitialized(true);
    }
  }, [roleData, isInitialized]);

  useEffect(() => {
    console.log('获取shotSelectionList数据', shotSelectionList);
  }, [shotSelectionList]);

  useEffect(() => {
    console.log('获取角色库数据', userRoleLibrary);
  }, [userRoleLibrary]);

  const handleSmartPolish = (text: string) => {
    // 然后调用优化角色文本
    window.msg.error('No permission!');
    return;
    optimizeRoleText(text);
  };

  const handleStartReplaceCharacter = async () => {
    setIsLoadingShots(true);
    setIsReplacePanelOpen(true);
    // 获取当前角色对应的视频片段
    await fetchRoleShots(selectedRole?.name || '');
    // 打开替换角色面板
    setIsLoadingShots(false);
  };

  const handleConfirmGotoReplace = () => {
    setIsRemindReplacePanelOpen(false);
    handleStartReplaceCharacter();
  };

  const handleCloseRemindReplacePanel = () => {
    setIsRemindReplacePanelOpen(false);
    console.log('忽略替换', triggerType, nextToTabId, nextToUserIndex);
    if (triggerType === 'apply') {
      onClose();
    } else if (triggerType === 'tab') {
      setActiveTab(nextToTabId);
    } else {
      selectRole(roleData[nextToUserIndex]);
    }
  };

  // President Alfred King  Samuel Ryan
  const handleConfirmReplace = async (selectedShots: string[], addToLibrary: boolean) => {
    // 处理替换确认逻辑
    console.log('Selected shots:', selectedShots);
    console.log('Add to library:', addToLibrary);
    setIsReplacePanelOpen(false);
    onClose();
    await applyRoleToSelectedShots(selectedRole || {} as RoleEntity);
    if(addToLibrary){
     await saveRoleToLibrary();
    }
    onApply();
  };

  // 取消替换
  const handleCloseReplacePanel = () => {
    setIsReplacePanelOpen(false);
  };

  // 对比角色是否修改
  const isRoleChange = (role: Role) => {
    console.log('对比角色是否修改', role, selectedRole);
    return role.name !== selectedRole?.name || role.url !== selectedRole?.imageUrl;
  };
  // 获取当前选中下标
  const getCurrentIndex = () => {
    return originalRoles.findIndex(role => role.name === selectedRole?.name);
  };

  const handleChangeRole = (index: number) => {
    console.log('切换角色前对比');
    const currentIndex = getCurrentIndex();
    if (currentIndex === index) return;
    if (currentIndex !== -1 && isRoleChange(originalRoles[currentIndex])) {
      setTriggerType('user');
      setIsRemindReplacePanelOpen(true);
      setNextToUserIndex(index);
      return;
    }

    // 重置替换规则
    setEnableAnimation(false);
    setIgnoreReplace(false);
    setIsRegenerate(false);
    console.log('roleData', roleData)
    selectRole(roleData[index]);
  };

  // 从角色库中选择角色
  const handleSelectCharacter = (index: number) => {
    console.log('选择的角色索引:', index);
    console.log('选择的角色数据:', userRoleLibrary[index]);

    setIsReplaceLibraryOpen(false);
    setShowAddToLibrary(false);

    // 使用真实的角色数据
    const role = userRoleLibrary[index];
    if (role) {
      selectRole({
        ...role,
        name: selectedRole?.name || ''
      });
      // handleStartReplaceCharacter();
    }
  };

  const handleOpenReplaceLibrary = async () => {
    window.msg.error('No permission!');
    return;
    setIsLoadingLibrary(true);
    setIsReplaceLibraryOpen(true);
    setShowAddToLibrary(true);
    await fetchUserRoleLibrary();
    setIsLoadingLibrary(false);
  };

  const handleRegenerate = async () => {
    window.msg.error('No permission!');
    return;
    console.log('Regenerate');
    setIsRegenerate(true);
    // const text = characterEditorRef.current.getRoleText();
    // console.log('-==========text===========-', text);
    // // 重生前 更新 当前项 generateText
    // updateRoleText(text);
    // 然后调用重新生成角色
    await regenerateRole();
    setIsRegenerate(false);
    // handleStartReplaceCharacter();
  };

  const handleUploadClick = () => {
    window.msg.error('No permission!');
    return;
    fileInputRef.current?.click();
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) {
      setIsUploading(false);
      return;
    };

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('Please select an image file');
      setIsUploading(false);
      return;
    }
    setIsUploading(true);

    uploadImageAndUpdateRole(file).then((data) => {
      console.log('上传图片成功', data);
      // 清空input的值，这样同一个文件可以重复选择
      event.target.value = '';
      setIsUploading(false);
    });
  };

  // 如果没有角色数据，显示占位内容
  if (originalRoles.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px] text-white/50">
        <Users className="w-16 h-16 mb-4" />
        <p>No role data</p>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-6">
      {/* 隐藏的文件输入框 */}
      <input
        type="file"
        ref={fileInputRef}
        className="hidden"
        accept="image/*"
        onChange={handleFileChange}
      />
      {/* 上部分：角色缩略图 */}
      <motion.div
        className="space-y-6"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <div className="relative">
          <HorizontalScroller
            itemWidth={96}
            gap={0}
            selectedIndex={originalRoles?.findIndex(role => role.name === selectedRole?.name)}
            onItemClick={(i: number) => handleChangeRole(i)}
          >
            {originalRoles.map((role, index) => (
              <motion.div
                key={`role-${index}`}
                className={cn(
                  'relative flex-shrink-0 w-24 rounded-lg overflow-hidden cursor-pointer',
                  'aspect-[9/16]',
                  role.name === selectedRole?.name ? 'ring-2 ring-blue-500' : 'hover:ring-2 hover:ring-blue-500/50'
                )}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                <img
                  src={role.url}
                  alt={role.name}
                  className="w-full h-full object-cover"
                />
                <div className="absolute bottom-0 left-0 right-0 p-1 bg-gradient-to-t from-black/60 to-transparent">
                  <span className="text-xs text-white/90 line-clamp-1">{role.name}</span>
                </div>
              </motion.div>
            ))}
          </HorizontalScroller>
        </div>
      </motion.div>

      {/* 下部分：角色详情 */}
      { loading ? (
        <div className="flex flex-col items-center justify-center min-h-[300px] text-white/50">
          <Loader2 className="w-12 h-12 mb-4 animate-spin" />
          <p>Loading...</p>
        </div>
      ) : (
        <motion.div
          className="grid grid-cols-2 gap-6"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
        >

          {/* 左列：角色预览 */}
          <div className="space-y-4">
            {/* 角色预览图 */}
            <div className="w-full h-full mx-auto rounded-lg relative group">
              <ImageBlurTransition
                src={selectedRole?.imageUrl || ''}
                alt={selectedRole?.name || ''}
                width='100%'
                height='100%'
                enableAnimation={enableAnimation}
              />
              {/* 应用角色按钮  暂时注释需要权限控制 */}
              <div className='absolute top-3 right-3 flex gap-2'>
                <motion.button
                  className="p-2 bg-black/50 hover:bg-black/70
                    text-white rounded-full backdrop-blur-sm transition-colors z-10"
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={handleUploadClick}
                  disabled={isUploading}
                >
                  {isUploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <ImageUp className="w-4 h-4" />}
                </motion.button>
                <motion.button
                  className="p-2 bg-black/50 hover:bg-black/70
                    text-white rounded-full backdrop-blur-sm transition-colors z-10"
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => handleOpenReplaceLibrary()}
                >
                  <Library className="w-4 h-4" />
                </motion.button>
              </div>
            </div>

          </div>
          {/* 右列：角色信息 */}
          <div className="space-y-4">
            <CharacterEditor
              ref={characterEditorRef}
              className="min-h-[calc(100%-4rem)]"
              description={selectedRole?.generateText || ''}
              highlight={selectedRole?.tags || []}
              onSmartPolish={handleSmartPolish}
              onUpdateText={(text: string) => updateRoleText(text)}
              disabled={true}
            />
            {/* 重新生成按钮、替换形象按钮 */}
            <div className="grid grid-cols-1 gap-2">
              <motion.button
                onClick={() => handleRegenerate()}
                className="flex items-center justify-center gap-2 px-4 py-3 bg-blue-500/10 hover:bg-blue-500/20
                  text-blue-500 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
                disabled={isRegenerate}
              >
                <RefreshCw className="w-4 h-4" />
                <span>{isRegenerate ? 'Regenerating...' : 'Regenerate'}</span>
              </motion.button>
            </div>
          </div>
        </motion.div>
      )}


      <FloatingGlassPanel
        open={isReplacePanelOpen}
        width='66vw'
        r_key={replacePanelKey}
        onClose={() => handleCloseReplacePanel()}
      >
        <ReplaceCharacterPanel
          isLoading={isLoadingShots}
          shots={shotSelectionList}
          role={selectedRole}
          showAddToLibrary={showAddToLibrary}
          onClose={() => handleCloseReplacePanel()}
          onConfirm={handleConfirmReplace}
        />
      </FloatingGlassPanel>

      {/* 从角色库中选择角色 */}
      <CharacterLibrarySelector
        isLoading={isLoadingLibrary}
        isReplaceLibraryOpen={isReplaceLibraryOpen}
        setIsReplaceLibraryOpen={setIsReplaceLibraryOpen}
        onSelect={handleSelectCharacter}
        userRoleLibrary={userRoleLibrary}
      />

      {/* 提醒用户角色已修改 是否需要替换 */}
      <FloatingGlassPanel
        open={isRemindReplacePanelOpen}
        width='500px'
        clickMaskClose={false}
      >
        <div className="flex flex-col items-center gap-4 text-white py-4">
          <div className="flex items-center gap-3">
            <TriangleAlert className="w-6 h-6 text-yellow-400" />
            <p className="text-lg font-medium">The role has been modified, if you do not replace it, the modification will be lost, do you need to replace it?</p>
          </div>

          <div className="flex gap-3 mt-2">
            <button
              onClick={() => handleConfirmGotoReplace()}
              data-alt="confirm-replace-button"
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-md transition-colors duration-200 flex items-center gap-2"
            >
              <ReplaceAll className="w-4 h-4" />
              Go to replace
            </button>

            <button
              onClick={() => handleCloseRemindReplacePanel()}
              data-alt="ignore-button"
              className="px-4 py-2 bg-gray-600 hover:bg-gray-700 rounded-md transition-colors duration-200 flex items-center gap-2"
            >
              <X className="w-4 h-4" />
              Ignore
            </button>
          </div>
        </div>
      </FloatingGlassPanel>
    </div>
  );
});

CharacterTabContent.displayName = 'CharacterTabContent';
