'use client';

import styled from '@emotion/styled';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { observer } from 'mobx-react-lite';
import { useState } from 'react';
import { useDebounceValue } from 'usehooks-ts';

import IntersectionTrigger from '@/components/IntersectionTrigger';
import {
  SearchInput,
  SearchInputWrapper,
} from '@/components/clipBrowser/FilterElements';
import {
  ContextMenuItem,
  RightClickMenuTrigger,
} from '@/components/contextMenu/ContextMenu';
import { useStudioProjectsListQuery } from '@/components/studio/StudioProjectListView';
import getStudioProjectAura from '@/components/studio/getStudioProjectAura';
import SpinnerSVG from '@/components/svg/SpinnerSVG';
import { ProjectIcon, SearchIcon, TrashIcon } from '@/icons';
import { useApiClient } from '@/lib/apiClient';
import logWebUserEvent from '@/logging/logWebUserEvent';

const Container = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
`;

const SearchContainer = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
  padding: 16px;
  flex-shrink: 0;
`;

const SearchWrapper = styled.div`
  flex: 1;
`;

const ProjectCardsWrapper = styled.div`
  min-height: 0;
  flex: 1;
  overflow-y: auto;
  overscroll-behavior: contain;
  padding: 0 16px 16px 16px;
`;

const ProjectCards = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
`;

const EmptyState = styled.div`
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 64px 0;
  text-align: center;
`;

const EmptyStateTitle = styled.h3`
  margin-bottom: 8px;
  font-size: 18px;
  font-weight: 500;
  color: var(--color-foreground-primary);
`;

const EmptyStateDescription = styled.p`
  max-width: 384px;
  color: var(--color-foreground-secondary);
`;

const SpinnerWrapper = styled.div`
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  padding: 32px 0;
`;

const ProjectCard = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  aspect-ratio: 1 / 1;
  border-radius: 16px;
  padding: 16px;
  position: relative;
  overflow: hidden;
  cursor: pointer;
  background-size: 130%;
  transition: background-size 0.2s ease-in-out;
  background-position: center;
  background-repeat: no-repeat;

  > * {
    position: relative;
    z-index: 1;
  }

  &:after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 50%;
    opacity: 1;
    transition: opacity 0.2s ease-in-out;
    background-image: linear-gradient(
      to bottom,
      transparent,
      rgba(0, 0, 0, 0.4)
    );
  }
`;

const ProjectCardText = styled.div``;

const ProjectCardTitle = styled.h4`
  font-size: 16px;
  font-weight: 500;
  line-height: 1.2;
  color: var(--color-foreground-primary);
  margin: 0;
  padding: 0;
`;

const ProjectCardDate = styled.p`
  margin: 0;
  padding: 0;
  font-size: 12px;
  color: var(--color-foreground-primary);
  opacity: 0.5;
`;

export default observer(function LibraryV2StudioProjects() {
  const [localSearchText, setLocalSearchText] = useState('');
  const [debouncedSearchText] = useDebounceValue(localSearchText, 150);
  const queryClient = useQueryClient();
  const studioProjects = useStudioProjectsListQuery(debouncedSearchText);

  const apiClient = useApiClient();
  const archiveProjectMutation = useMutation({
    mutationFn: (projectId: string) => {
      return apiClient.POST('/api/studio/project/{project_id}/archive', {
        params: {
          path: {
            project_id: projectId,
          },
        },
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['studioProjects'] });
    },
  });

  const [justArchivedProjects, setJustArchivedProjects] = useState<string[]>(
    []
  );

  return (
    <Container>
      <SearchContainer>
        <SearchWrapper>
          <SearchInputWrapper>
            <SearchIcon className='h-6 w-6' />
            <SearchInput
              placeholder='Search'
              value={localSearchText}
              onChange={(e) => {
                setLocalSearchText(e.target.value);
              }}
            />
          </SearchInputWrapper>
        </SearchWrapper>
      </SearchContainer>

      <ProjectCardsWrapper>
        <ProjectCards>
          {studioProjects.isPending ? (
            <SpinnerWrapper>
              <SpinnerSVG />
            </SpinnerWrapper>
          ) : studioProjects.data?.pages
              .flatMap((page) => page.projects)
              .filter((project) => !!project?.id)
              .filter(
                (project) =>
                  !project!.id || !justArchivedProjects.includes(project!.id)
              ).length === 0 ? (
            <EmptyState>
              <ProjectIcon className='mb-4 h-12 w-12 text-foreground-tertiary' />
              <EmptyStateTitle>No studio projects found</EmptyStateTitle>
              <EmptyStateDescription>
                {localSearchText
                  ? `No projects match "${localSearchText}". Try adjusting your search.`
                  : 'Create your first studio project to get started.'}
              </EmptyStateDescription>
            </EmptyState>
          ) : (
            studioProjects.data?.pages
              .flatMap((page) => page.projects)
              .filter((project) => !!project?.id)
              .filter(
                (project) =>
                  !project!.id || !justArchivedProjects.includes(project!.id)
              )
              .map((project) => (
                <RightClickMenuTrigger
                  key={project!.id}
                  ContentsComponent={() => (
                    <>
                      <ContextMenuItem
                        className='text-accent-error-on-primary'
                        icon={TrashIcon}
                        onClick={() => {
                          const projectId = project!.id;
                          if (!projectId) return;

                          archiveProjectMutation.mutate(projectId);
                          setJustArchivedProjects((prev) => [
                            ...prev,
                            projectId,
                          ]);
                        }}
                      >
                        Delete
                      </ContextMenuItem>
                    </>
                  )}
                >
                  <ProjectCard
                    onClick={() => {
                      if (project!.id) {
                        window.location.href = `/studio?initial_project_id=${project!.id}`;
                        logWebUserEvent({
                          actionName: 'NavigatedToStudio',
                          context: {
                            trigger: 'library_v2_studio_projects',
                          },
                        });
                        logWebUserEvent({
                          actionName: 'LoadedStudioProject',
                          context: {
                            studioProjectId: project!.id,
                            trigger: 'library_v2_studio_projects',
                          },
                        });
                      }
                    }}
                    style={{
                      backgroundImage: `url(${getStudioProjectAura(project!.id!)})`,
                    }}
                  >
                    <ProjectIcon className='h-6 w-6' />
                    <ProjectCardText>
                      <ProjectCardTitle>{project!.title}</ProjectCardTitle>
                      <ProjectCardDate>
                        {format(new Date(project!.updated_at), 'MMMM d, yyyy')}
                      </ProjectCardDate>
                    </ProjectCardText>
                  </ProjectCard>
                </RightClickMenuTrigger>
              ))
          )}
          <IntersectionTrigger onTrigger={() => studioProjects.fetchNextPage()}>
            <div className='h-1 w-1' />
          </IntersectionTrigger>
        </ProjectCards>
      </ProjectCardsWrapper>
    </Container>
  );
});
