/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import { observer } from 'mobx-react-lite';
import { useCallback, useEffect, useRef, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { USER } from '@/app/(root)/search/utils';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import { toast } from '@/components/toast/Toast';
import { CloseIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { ProjectStore } from '@/state/projectStore';
import { QueryParams } from '@/state/searchStore';
import {
  MAX_COLLABORATORS_PER_PROJECT,
  SEARCH_OPTION_TRENDING,
} from '@/utils/constants';

import Button, { ButtonVariant } from '../button/Button';
import Modal from './Modal';

interface UserSearchResult {
  display_name: string;
  avatar_image_url: string;
  handle: string;
  stats: {
    followers_count: number;
  };
  entity_type?: string;
  external_user_id?: string;
  user_id?: number;
  is_following?: boolean;
}

interface CollaboratorProfile {
  user_id: string;
  user_invite_status: 'accepted' | 'pending';
  user_handle?: string | null;
  user_display_name?: string | null;
  user_avatar_url?: string | null;
}

const ShareProjectModal = observer(
  ({
    project,
    isOpen,
    onClose,
    onKickSelf = () => {},
  }: {
    project: ProjectStore;
    isOpen: boolean;
    onClose: () => void;
    onKickSelf?: () => void;
  }) => {
    const { session, search } = useStores();
    const [usernameInput, setUsernameInput] = useState('');
    const [usernames, setUsernames] = useState<string[]>([]);
    const [isSharing, setIsSharing] = useState(false);
    const [copied, setCopied] = useState(false);
    const [owner, setOwner] = useState<CollaboratorProfile>();
    const [showDropdown, setShowDropdown] = useState(false);
    const [searchResults, setSearchResults] = useState<UserSearchResult[]>([]);
    const [isSearching, setIsSearching] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);

    const [collaborators, setCollaborators] = useState<CollaboratorProfile[]>(
      []
    );

    // Fetch profiles for all collaborators
    const fetchCollaboratorProfiles = useCallback(async () => {
      const updatedCollaborators =
        await project.getCurrentProjectCollaborators();
      if (updatedCollaborators) {
        setCollaborators(updatedCollaborators);
      }
    }, [project]);

    useEffect(() => {
      fetchCollaboratorProfiles();
      setOwner(project.currentProjectOwner || undefined);
    }, [
      project.userSelectedProjectId,
      project.currentProjectId,
      project.currentProjectOwner,
      fetchCollaboratorProfiles,
    ]);

    // Handle click outside to close dropdown
    useEffect(() => {
      const handleClickOutside = (event: MouseEvent) => {
        if (
          dropdownRef.current &&
          !dropdownRef.current.contains(event.target as Node)
        ) {
          setShowDropdown(false);
        }
      };

      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }, []);

    // Search users when input changes
    useEffect(() => {
      const searchUsers = async () => {
        if (usernameInput.trim().length < 2) {
          setSearchResults([]);
          setShowDropdown(false);
          return;
        }

        setIsSearching(true);
        setShowDropdown(true);

        const queryParams = new QueryParams({
          searchType: USER,
          query: usernameInput.trim(),
          isPublic: true,
          rankBy: SEARCH_OPTION_TRENDING,
          fromIndex: 0,
          pageSize: 5, // Limit to top 5 results
        });

        try {
          await search.searchData(
            usernameInput.trim(),
            false,
            USER,
            SEARCH_OPTION_TRENDING,
            undefined,
            undefined,
            5
          );

          const searchResult =
            search.searchResultCache[queryParams.getSearchCacheKey()];
          if (searchResult?.result) {
            setSearchResults(searchResult.result as UserSearchResult[]);
          } else {
            setSearchResults([]);
          }
        } catch (error) {
          console.error('Failed to search users:', error);
          setSearchResults([]);
        } finally {
          setIsSearching(false);
        }
      };

      const timeoutId = setTimeout(searchUsers, 300); // Debounce search
      return () => clearTimeout(timeoutId);
    }, [usernameInput, search]);

    if (!isOpen) return null;

    const handleSelectUser = (user: UserSearchResult) => {
      if (!usernames.includes(user.handle)) {
        setUsernames([...usernames, user.handle]);
      }
      setUsernameInput('');
      setShowDropdown(false);
    };

    const handleCollaboratorRemove = async (userID: string) => {
      if (userID === session.user?.id) {
        await project.removeSelfFromProject(
          project.userSelectedProjectId || ''
        );
        onClose();
        project.setUserSelectedProjectId(null, null);
        await project.loadAllProjects();
        onKickSelf();
      } else {
        await project.removeCollaboratorFromProject(
          project.userSelectedProjectId || '',
          userID
        );
      }
      fetchCollaboratorProfiles();
    };

    const handleAddUsername = () => {
      const trimmedUsername = usernameInput.trim();
      if (trimmedUsername && !usernames.includes(trimmedUsername)) {
        setUsernames([...usernames, trimmedUsername]);
        setUsernameInput('');
        setShowDropdown(false);
      }
    };

    const handleRemoveUsername = (usernameToRemove: string) => {
      setUsernames(
        usernames.filter((username) => username !== usernameToRemove)
      );
    };

    const handleShare = async () => {
      if (usernames.length === 0) return;

      setIsSharing(true);
      try {
        logWebUserEvent({
          actionName: 'ShareProjectButtonClicked',
          context: {
            state: 'clicked',
            projectId: project.userSelectedProjectId || '',
            usernames: usernames,
          },
        });

        let successCount = 0;
        for (const username of usernames) {
          // Fetch user profile by handle to get their user_id
          const { data } = await session.apiClient.GET(
            '/api/profiles/{handle}',
            {
              params: {
                path: {
                  handle: username,
                },
                query: {
                  page: 1,
                  playlists_sort_by: 'created_at',
                  clips_sort_by: 'created_at',
                },
              },
            }
          );
          if (data && data.user_id) {
            const response = await project.sendInviteToProject(
              project.userSelectedProjectId || '',
              String(data.user_id)
            );
            if (response && !('error' in response)) {
              successCount++;
            } else {
              const errorMessage =
                response && 'error' in response
                  ? response.error
                  : 'Unknown error occurred';
              toast({
                title: 'Failed to share project',
                description: `Failed to share project with user: ${username} (${errorMessage})`,
                status: 'error',
                duration: 4000,
                isClosable: true,
              });
            }
          } else {
            toast({
              title: 'Failed to share project',
              description: `Failed to fetch profile for user: ${username}`,
              status: 'error',
              duration: 4000,
              isClosable: true,
            });
          }
        }

        setUsernames([]);
        if (successCount > 0) {
          toast({
            title: 'Project shared successfully',
            description: `Shared with ${successCount} user${successCount > 1 ? 's' : ''}`,
            status: 'success',
            duration: 4000,
            isClosable: true,
          });
        }
        onClose();
      } catch (error) {
        console.error('Failed to share project:', error);
        toast({
          title: 'Failed to share project',
          description: 'An unexpected error occurred while sharing the project',
          status: 'error',
          duration: 4000,
          isClosable: true,
        });
      } finally {
        setIsSharing(false);
        fetchCollaboratorProfiles();
      }
    };

    const handleCopyLink = async () => {
      try {
        // Generate shareable link - you'll need to implement this based on your backend
        const shareableLink = `${window.location.origin}/project/${project.currentProjectId}`;
        await navigator.clipboard.writeText(shareableLink);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);

        logWebUserEvent({
          actionName: 'ShareProjectCopyLinkClicked',
          context: {
            projectId: project.userSelectedProjectId || '',
          },
        });
      } catch (error) {
        console.error('Failed to copy link:', error);
      }
    };

    const handleKeyPress = (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        handleAddUsername();
      }
    };

    const canAddCollaborators =
      collaborators.length + usernames.length < MAX_COLLABORATORS_PER_PROJECT;

    return (
      <Modal
        title='Share Workspace'
        onClose={() => {
          logWebUserEvent({
            actionName: 'ShareProjectModalClicked',
            context: { state: 'closed' },
          });
          setUsernames([]);
          onClose();
        }}
        wrapperClasses='mb-4'
        withHorizontalPadding
        width={600}
      >
        <div className='space-y-6'>
          {/* Project Info */}
          <div className='flex items-center space-x-3 rounded-lg bg-background-primary p-3'>
            <div className='flex h-10 w-10 items-center justify-center rounded-lg bg-primary'>
              <ImageWithFallback
                src={project.getAuraImageForProject(
                  project.userSelectedProjectId || ''
                )}
                alt={`Cover image for ${project.currentProjectName}`}
                className='h-full w-full object-cover'
                fallbackSrc='https://cdn-o.suno.com/auras/Aura-01.png'
              />
            </div>
            <div>
              <h3 className='font-medium text-foreground-primary'>
                {project.currentProjectName || 'Untitled Workspace'}
              </h3>
            </div>
          </div>

          {/* People with Access Section */}
          <div className='space-y-3'>
            <h4 className='font-medium text-foreground-primary'>
              People with access
            </h4>
            <div className='space-y-1'>
              {/* Owner/Current User */}
              <div className='flex items-center justify-between rounded-lg border border-border-primary bg-background-primary p-3'>
                <div className='flex items-center space-x-3'>
                  <div className='h-8 w-8 shrink-0 overflow-hidden rounded-full'>
                    <ImageWithFallback
                      src={owner?.user_avatar_url}
                      alt={`Profile picture for ${owner?.user_display_name || owner?.user_handle}`}
                      className='h-full w-full object-cover'
                      fallbackSrc='https://cdn-o.suno.com/auras/Aura-01.png'
                    />
                  </div>
                  <div>
                    <div className='font-medium text-foreground-primary'>
                      @{owner?.user_handle}{' '}
                      {owner?.user_handle === session.user?.handle && '(you)'}
                    </div>
                  </div>
                </div>
                <div className='text-sm font-medium text-foreground-secondary'>
                  Owner
                </div>
              </div>

              {/* Collaborators */}
              {collaborators.map((collaborator) => (
                <div
                  key={collaborator.user_handle}
                  className='flex items-center justify-between rounded-lg border border-border-primary bg-background-primary p-3'
                >
                  <div className='flex items-center space-x-3'>
                    <div className='h-8 w-8 shrink-0 overflow-hidden rounded-full'>
                      {collaborator.user_avatar_url ? (
                        <ImageWithFallback
                          src={collaborator.user_avatar_url}
                          alt={`Profile picture for ${collaborator.user_display_name || collaborator.user_handle}`}
                          className='h-full w-full object-cover'
                          fallbackSrc='https://cdn-o.suno.com/auras/Aura-01.png'
                        />
                      ) : (
                        <div className='flex h-full w-full items-center justify-center rounded-full bg-primary/20 text-sm font-medium text-foreground-primary'>
                          {collaborator.user_handle?.charAt(0).toUpperCase()}
                        </div>
                      )}
                    </div>
                    <div className='font-medium text-foreground-primary'>
                      @{collaborator.user_handle}{' '}
                      {collaborator.user_handle === session.user?.handle &&
                        '(you)'}
                    </div>
                  </div>
                  {collaborator.user_invite_status === 'pending' && (
                    <div className='ml-auto text-sm font-medium text-foreground-secondary'>
                      (Pending)
                    </div>
                  )}
                  {(owner?.user_handle == session.user?.handle ||
                    collaborator.user_handle === session.user?.handle) && (
                    <div className='flex items-center space-x-2'>
                      <button
                        onClick={() => {
                          handleCollaboratorRemove(collaborator.user_id);
                        }}
                        className='cursor-pointer rounded p-1 text-foreground-secondary hover:bg-background-secondary hover:text-accent-red-on-primary'
                        title='Remove access'
                      >
                        <CloseIcon className='h-4 w-4' />
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Share with people section */}
          {owner?.user_handle === session.user?.handle && (
            <div className='space-y-2'>
              {/* Username Input Section */}
              <div className='space-y-3'>
                <h4 className='font-medium text-foreground-primary'>
                  Share with people
                </h4>
                <div className='space-y-2'>
                  <div className='relative flex space-x-2'>
                    <div className='relative flex-1'>
                      {canAddCollaborators ? (
                        <input
                          ref={inputRef}
                          type='text'
                          placeholder='Add people by username (handle, not display name)'
                          className='w-full rounded-md border border-border-primary bg-transparent px-3 py-2 text-sm focus-within:outline-white'
                          value={usernameInput}
                          onChange={(e) => setUsernameInput(e.target.value)}
                          onKeyDown={handleKeyPress}
                          onFocus={() => {
                            if (
                              usernameInput.trim().length >= 2 &&
                              searchResults.length > 0
                            ) {
                              setShowDropdown(true);
                            }
                          }}
                        />
                      ) : (
                        <div className='text-accent-error-on-primary'>
                          Cannot have more than {MAX_COLLABORATORS_PER_PROJECT}{' '}
                          collaborators invited to a workspace
                        </div>
                      )}

                      {/* Search Dropdown */}
                      {showDropdown && (
                        <div
                          ref={dropdownRef}
                          className='absolute top-full right-0 left-0 z-50 mt-1 max-h-60 overflow-y-auto rounded-md border border-border-primary bg-background-primary shadow-lg'
                        >
                          {isSearching ? (
                            <div className='p-3 text-center text-foreground-secondary'>
                              Searching...
                            </div>
                          ) : searchResults.length > 0 ? (
                            searchResults.map((user) => (
                              <div
                                key={user.handle}
                                onClick={() => handleSelectUser(user)}
                                className='flex cursor-pointer items-center space-x-3 border-b border-border-primary p-3 last:border-b-0 hover:bg-background-secondary'
                              >
                                <div className='h-8 w-8 shrink-0 overflow-hidden rounded-full'>
                                  <ImageWithFallback
                                    src={user.avatar_image_url}
                                    alt={user.display_name || `@${user.handle}`}
                                    className='h-full w-full object-cover'
                                    fallbackSrc='https://cdn-o.suno.com/auras/Aura-01.png'
                                  />
                                </div>
                                <div className='min-w-0 flex-1'>
                                  <div className='truncate font-medium text-foreground-primary'>
                                    {user.display_name || `@${user.handle}`}
                                  </div>
                                  <div className='truncate text-sm text-foreground-secondary'>
                                    @{user.handle}
                                  </div>
                                </div>
                              </div>
                            ))
                          ) : usernameInput.trim().length >= 2 ? (
                            <div className='p-3 text-center text-foreground-secondary'>
                              No users found
                            </div>
                          ) : null}
                        </div>
                      )}
                    </div>
                    {/* <Button
                      variant={ButtonVariant.Primary}
                      onClick={handleAddUsername}
                      disabled={!usernameInput.trim()}
                    >
                      <PlusIcon className='w-4 h-4' />
                    </Button> */}
                  </div>

                  {/* Username Tags */}
                  {usernames.length > 0 && (
                    <div className='flex flex-wrap gap-1'>
                      {usernames.map((username, index) => (
                        <div
                          key={index}
                          className='flex items-center space-x-1 rounded-full bg-background-primary px-2 py-1 text-sm text-foreground-primary'
                        >
                          <span>@{username}</span>
                          <button
                            onClick={() => handleRemoveUsername(username)}
                            className='flex h-4 w-4 cursor-pointer items-center justify-center rounded-full hover:bg-background-tertiary hover:text-accent-red-on-primary'
                          >
                            <CloseIcon />
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Action Buttons */}
          <div className='flex items-center justify-between border-t border-secondary/20 pt-4'>
            <Button
              variant={ButtonVariant.Secondary}
              onClick={handleCopyLink}
              className='whitespace-nowrap'
            >
              {copied ? 'Copied!' : 'Copy link'}
            </Button>
            {owner?.user_handle === session.user?.handle && (
              <div className='flex space-x-3'>
                <Button
                  variant={ButtonVariant.Primary}
                  onClick={handleShare}
                  disabled={usernames.length === 0 || isSharing}
                >
                  {isSharing ? 'Sharing...' : 'Share'}
                </Button>
              </div>
            )}
          </div>
        </div>
      </Modal>
    );
  }
);

export default ShareProjectModal;
