import styled from '@emotion/styled';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { HeaderContainer } from '@/app/(root)/create/createV2/componentsQ3/CreateHeader';
import CreateFormContext from '@/app/(root)/create/v2/CreateFormContext';
import { CreateModes } from '@/app/(root)/create/v2/types';
import { useContextSelector } from '@/hooks/useContextSelector';
import { ChevronRightIcon, EditIcon } from '@/icons';
import { DEFAULT_PROJECT_ID } from '@/utils/constants';

import Button, { ButtonShape, ButtonVariant } from '../button/Button';
import { ClipBrowserContext } from './useClipBrowser';

const Group = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  flex-grow: 1;
  flex-shrink: 1;
  min-width: 80px;
`;

const WorkspaceInfo = styled.div`
  display: flex;
  align-items: center;
  flex-direction: row;
  gap: 8px;
  flex-grow: 1;
  white-space: nowrap;
  overflow: hidden;
`;

export const WorkspaceImage = styled.img`
  width: 32px;
  height: 32px;
  border-radius: 4px;
`;

const Title = styled.div`
  font-size: 16px;
  font-weight: 500;
  color: rgb(var(--rgb-foreground-tertiary));
  max-width: 300px;
  flex-shrink: 1;
  flex-grow: 0;
  text-overflow: ellipsis;
`;

const TitleInput = styled.input`
  font-size: 18px;
  font-weight: 600;
  border: none;
  outline: none;
  padding: 4px 0;
  background-color: transparent;
  flex-grow: 1;
`;

export const useWorkspace = (workspaceId?: string) => {
  const { project } = useStores();
  const queryClient = useQueryClient();
  const query = useQuery({
    queryKey: ['workspace', workspaceId],
    queryFn: async () => {
      if (!workspaceId) {
        return null;
      }
      return await project.fetchSingleProject(workspaceId);
    },
  });
  return { ...query, queryClient };
};

export default function WorkspaceClipBrowserHeader({
  onBackClick,
  rightSideContent,
  leftSideContent,
  expanded = true,
}: {
  onBackClick?: () => void;
  rightSideContent?: React.ReactNode[] | React.ReactNode;
  leftSideContent?: React.ReactNode[] | React.ReactNode;
  expanded?: boolean;
}) {
  const { project: projectStore } = useStores();
  const workspaceId = useContextSelector(
    ClipBrowserContext,
    (context) => context.filters.workspace.workspaceId ?? undefined
  );

  const { data: workspace, queryClient } = useWorkspace(workspaceId);
  const isDefaultWorkspace = workspaceId === DEFAULT_PROJECT_ID;

  const [renamingWorkspace, setRenamingWorkspace] = useState(false);
  const [workspaceName, setWorkspaceName] = useState(workspace?.name ?? '');
  const [isSaving, setIsSaving] = useState(false);

  const showEditIcon = !isDefaultWorkspace && !renamingWorkspace;
  const mode = useContextSelector(
    CreateFormContext,
    (context) => context.state.global.mode
  );

  useEffect(() => {
    // Don't reset the name while we're saving or renaming
    if (!isSaving && !renamingWorkspace) {
      setWorkspaceName(workspace?.name ?? '');
    }
  }, [workspace?.name, isSaving, renamingWorkspace]);

  const handleSaveWorkspaceName = async () => {
    if (
      !workspaceId ||
      !workspaceName.trim() ||
      workspaceName.trim() === workspace?.name ||
      isSaving
    ) {
      setRenamingWorkspace(false);
      return;
    }

    try {
      setIsSaving(true);
      await projectStore.updateProjectName(workspaceId, workspaceName.trim());
      await queryClient.invalidateQueries({
        queryKey: ['workspace', workspaceId],
      });
      setRenamingWorkspace(false);
    } catch (error) {
      console.error('Failed to update workspace name:', error);
      // Reset to original name on error
      setWorkspaceName(workspace?.name ?? '');
      setRenamingWorkspace(false);
    } finally {
      setIsSaving(false);
    }
  };

  if (!workspace) {
    return <HeaderContainer />;
  }

  if (!expanded) {
    return <HeaderContainer borderBottom>{rightSideContent}</HeaderContainer>;
  }

  return (
    <HeaderContainer center>
      <Group>
        {leftSideContent}
        {onBackClick && (
          <>
            <Button
              variant={ButtonVariant.Glass}
              onClick={onBackClick}
              className='p-0 text-base font-medium'
            >
              {mode === CreateModes.CHAT ? 'Chats' : 'Workspaces'}
            </Button>
            <ChevronRightIcon className='h-4 w-4' />
          </>
        )}
        <WorkspaceInfo>
          {renamingWorkspace ? (
            <TitleInput
              autoFocus
              disabled={isSaving}
              onFocus={(e) => {
                e.target.select();
              }}
              value={workspaceName}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  handleSaveWorkspaceName();
                } else if (e.key === 'Escape') {
                  setWorkspaceName(workspace.name);
                  setRenamingWorkspace(false);
                }
              }}
              onBlur={() => {
                handleSaveWorkspaceName();
              }}
              onChange={(e) => {
                setWorkspaceName(e.target.value);
              }}
              style={{
                opacity: isSaving ? 0.6 : 1,
                cursor: isSaving ? 'not-allowed' : 'text',
              }}
            />
          ) : (
            <Title className='line-clamp-1'>{workspace.name}</Title>
          )}
          {showEditIcon && (
            <Button
              variant={ButtonVariant.Tertiary}
              shape={ButtonShape.Pill}
              icon={
                <EditIcon className='h-4 w-4 opacity-50 hover:opacity-100' />
              }
              className='-ml-1 px-0'
              onClick={() => {
                setRenamingWorkspace(true);
              }}
            />
          )}
        </WorkspaceInfo>
      </Group>
      <Group style={{ marginLeft: 'auto' }} className='flex flex-row-reverse'>
        {rightSideContent}
      </Group>
    </HeaderContainer>
  );
}
