import React, { useState } from 'react';
import { KnowledgeGroup } from '../types';
import { knowledgeGroupService } from '../services/knowledgeGroupService';
import { useLanguage } from '../contexts/LanguageContext';
import { useToast } from '../contexts/ToastContext';
import { Tag, Plus, X, FolderPlus } from 'lucide-react';

interface FileGroupTagsProps {
  fileId: string;
  groups: KnowledgeGroup[];
  assignedGroups: string[];
  onGroupsChange: (groupIds: string[]) => void;
  isAdmin?: boolean;
}

export const FileGroupTags: React.FC<FileGroupTagsProps> = ({
  fileId,
  groups,
  assignedGroups,
  onGroupsChange,
  isAdmin = false
}) => {
  const { t } = useLanguage();
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const { showToast } = useToast();

  // カスタムイベントを監視してグループセレクターを開く
  React.useEffect(() => {
    const handleOpenGroupSelector = (event: CustomEvent) => {
      if (event.detail.fileId === fileId) {
        setIsOpen(true);
      }
    };

    document.addEventListener('openGroupSelector', handleOpenGroupSelector as EventListener);
    return () => {
      document.removeEventListener('openGroupSelector', handleOpenGroupSelector as EventListener);
    };
  }, [fileId]);

  const handleAddToGroup = async (groupId: string) => {
    if (assignedGroups.includes(groupId)) return;

    setLoading(true);
    try {
      // 正しい方法：すべてのグループID（既存 + 新規）を渡す
      const newGroupIds = [...assignedGroups, groupId];
      await knowledgeGroupService.addFileToGroups(fileId, newGroupIds);
      onGroupsChange(newGroupIds);
      showToast('success', t('fileAddedToGroup'));
      setIsOpen(false);
    } catch (error) {
      showToast('error', t('failedToAddToGroup'));
    } finally {
      setLoading(false);
    }
  };

  const handleRemoveFromGroup = async (groupId: string) => {
    setLoading(true);
    try {
      await knowledgeGroupService.removeFileFromGroup(fileId, groupId);
      onGroupsChange(assignedGroups.filter(id => id !== groupId));
      showToast('success', t('fileRemovedFromGroup'));
    } catch (error) {
      showToast('error', t('failedToRemoveFromGroup'));
    } finally {
      setLoading(false);
    }
  };

  const assignedGroupsData = assignedGroups.map(id => groups.find(g => g.id === id)).filter(Boolean);
  const availableGroups = groups.filter(g => !assignedGroups.includes(g.id));

  return (
    <div className="relative">
      <div className="flex items-center flex-wrap gap-1">
        {assignedGroupsData.map((group) => (
          <div
            key={group.id}
            className="flex items-center space-x-1 px-2 py-1 rounded-full text-xs"
            style={{ backgroundColor: group.color + '20', color: group.color }}
          >
            <div
              className="w-2 h-2 rounded-full"
              style={{ backgroundColor: group.color }}
            />
            <span>{group.name}</span>
            {isAdmin && (
              <button
                onClick={() => handleRemoveFromGroup(group.id)}
                disabled={loading}
                className="hover:bg-black/10 rounded-full p-0.5"
              >
                <X size={10} />
              </button>
            )}
          </div>
        ))}

        {availableGroups.length > 0 && (
          <span></span>
        )}
      </div>

      {isOpen && availableGroups.length > 0 && (
        <>
          <div
            className="fixed inset-0 z-10"
            onClick={() => setIsOpen(false)}
          />
          <div className="absolute top-full left-0 mt-1 bg-white border border-gray-300 rounded-md shadow-lg z-20 min-w-48">
            {availableGroups.map((group) => (
              <button
                key={group.id}
                onClick={() => {
                  handleAddToGroup(group.id);
                }}
                disabled={loading}
                className="w-full flex items-center space-x-2 px-3 py-2 text-sm text-left hover:bg-gray-50 disabled:opacity-50"
              >
                <div
                  className="w-3 h-3 rounded-full"
                  style={{ backgroundColor: group.color }}
                />
                <span>{group.name}</span>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
};