import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { uiFonts } from '../../constants/uiFonts';
import { InternalTabs } from '../InternalTabs/InternalTabs';

import { ICharacter } from '@rpg-engine/shared';
import { debounce } from 'lodash';
import {
  ActionButtons,
  Table,
  TableCell,
  TableHeader,
  TableRow,
  UserActionLink,
} from '../Table/Table';
export type IFriend = Pick<ICharacter, 'name' | '_id' | 'isOnline'>;
interface IFriendListProps {
  scale?: number;
  friends: IFriend[];
  friendRequests: IFriend[];
  searchedCharacters: IFriend[];
  onFocus?: () => void;
  onBlur?: () => void;
  onClose: () => void;
  onOpenPrivateMessage: (character: IFriend) => void;
  onRemoveFriend: (character: IFriend) => void;
  onSendFriendRequest: (character: IFriend) => void;
  onSearch: (characterName: string) => void;
  onAcceptRequest: (character: IFriend) => void;
  onRejectRequest: (character: IFriend) => void;
  onAddFriend?: () => void;
  onBackFriendList?: () => void;
}

export const FriendList: React.FC<IFriendListProps> = ({
  friends,
  friendRequests,
  searchedCharacters,
  onFocus,
  onBlur,
  onSearch,
  onAcceptRequest,
  onSendFriendRequest,
  onRemoveFriend,
  onOpenPrivateMessage,
  onRejectRequest,
  onAddFriend,
  onBackFriendList,
}) => {
  const [characterName, setCharacterName] = useState('');
  const [activeTab, setActiveTab] = useState('friends');

  useEffect(() => {
    if (activeTab === 'search') {
      onAddFriend?.();
    } else {
      onBackFriendList?.();
    }
  }, [activeTab]);

  const debouncedSearch = useCallback(
    debounce((name: string) => {
      onSearch(name);
    }, 300),
    []
  );

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const name = e.target.value;
    setCharacterName(name);
    debouncedSearch(name);
  };

  const handleSubmit = (event: React.SyntheticEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (characterName.trim()) {
      onSearch(characterName);
    }
  };

  const friendsTabContent = (
    <ScrollableArea>
      <Table>
        <thead>
          <TableRow>
            <TableHeader>Online</TableHeader>
            <TableHeader>Name</TableHeader>
            <TableHeader>Actions</TableHeader>
          </TableRow>
        </thead>
        <tbody>
          {friends.map(friend => (
            <TableRow key={friend._id}>
              <TableCell>
                <IsOnlineBadge $isOnline={friend.isOnline} />
              </TableCell>
              <TableCell>{friend.name}</TableCell>
              <TableCell>
                <ActionButtons>
                  <UserActionLink
                    color={uiColors.white}
                    onClick={() => onOpenPrivateMessage(friend)}
                  >
                    Chat
                  </UserActionLink>
                  <UserActionLink
                    color={uiColors.red}
                    onClick={() => onRemoveFriend(friend)}
                  >
                    Remove
                  </UserActionLink>
                </ActionButtons>
              </TableCell>
            </TableRow>
          ))}
        </tbody>
      </Table>
    </ScrollableArea>
  );

  const searchTabContent = (
    <ListContainer>
      <SearchForm onSubmit={handleSubmit}>
        <SearchInput
          value={characterName}
          id="characterName"
          name="characterName"
          onChange={handleInputChange}
          type="text"
          autoComplete="off"
          onFocus={onFocus}
          onBlur={onBlur}
          onPointerDown={onFocus}
          placeholder="Search for a character..."
        />
      </SearchForm>
      <CharacterList
        characters={searchedCharacters}
        onAction={onSendFriendRequest}
        actionLabel="Add Friend"
      />
    </ListContainer>
  );

  const requestsTabContent = (
    <ListContainer>
      <FriendRequestSection
        friendRequests={friendRequests}
        onAccept={onAcceptRequest}
        onReject={onRejectRequest}
      />
    </ListContainer>
  );

  const tabs = [
    { id: 'friends', title: `Friends (${friends.length})`, content: friendsTabContent },
    { id: 'search', title: 'Search', content: searchTabContent },
    {
      id: 'requests',
      title: `Requests (${friendRequests.length})`,
      content: requestsTabContent,
    },
  ];

  return (
    <ListWrapper>
      <InternalTabs
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        activeTextColor="#000"
        inactiveColor="#777"
        borderColor="#f59e0b"
      />
    </ListWrapper>
  );
};

const CharacterList: React.FC<{
  characters: IFriend[];
  onAction: (character: IFriend) => void;
  actionLabel: string;
}> = ({ characters, onAction, actionLabel }) => (
  <ListContainer>
    {characters.map(character => (
      <ListItem key={character._id}>
        <CharacterName>{character.name}</CharacterName>
        <UserActionLink
          color={uiColors.lightGreen}
          onClick={() => onAction(character)}
        >
          {actionLabel}
        </UserActionLink>
      </ListItem>
    ))}
  </ListContainer>
);

const FriendRequestSection: React.FC<{
  friendRequests: IFriend[];
  onAccept: (character: IFriend) => void;
  onReject: (character: IFriend) => void;
}> = ({ friendRequests, onAccept, onReject }) => (
  <>
    {friendRequests.length > 0 ? (
      <ListContainer>
        {friendRequests.map(character => (
          <ListItem key={character._id}>
            <CharacterName>{character.name}</CharacterName>
            <AcceptRejectActions>
              <UserActionLink
                color={uiColors.lightGreen}
                onClick={() => onAccept(character)}
              >
                Accept
              </UserActionLink>
              <UserActionLink
                color={uiColors.red}
                onClick={() => onReject(character)}
              >
                Reject
              </UserActionLink>
            </AcceptRejectActions>
          </ListItem>
        ))}
      </ListContainer>
    ) : (
      <EmptyMessage>No pending friend requests</EmptyMessage>
    )}
  </>
);

// Styled components for FriendList UI
const ListWrapper = styled.div`
  margin-top: 1rem;
  max-height: 350px;
  display: flex;
  flex-direction: column;
`;

const ScrollableArea = styled.div`
  overflow-y: auto;
  max-height: 300px;
`;

const IsOnlineBadge = styled.div<{ $isOnline: boolean }>`
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: ${({ $isOnline }) =>
    $isOnline ? uiColors.lightGreen : uiColors.red};
  margin-right: 1rem;
`;

const SearchForm = styled.form`
  display: flex;
  align-items: center;
  width: 100%;
  margin-top: 1rem;
`;

const SearchInput = styled.input`
  width: 100%;
  background-color: rgba(0, 0, 0, 0.25);
  border: none;
  padding: 0.5rem;
  font-size: ${uiFonts.size.small};
`;

const ListContainer = styled.ul`
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
  max-height: 50vh;
  overflow-y: auto;

  @media (max-width: 768px) {
    max-height: 90vh;
  }
`;

const ListItem = styled.li`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
`;

const CharacterName = styled.p`
  font-size: ${uiFonts.size.small};
  margin: 0;
`;

const AcceptRejectActions = styled.div`
  display: flex;
  gap: 0.5rem;
`;

const EmptyMessage = styled.p`
  text-align: center;
  color: #888;
  padding: 1rem;
  font-size: ${uiFonts.size.small};
`;
