import styled from '@emotion/styled';
import { useCallback, useEffect, useState } from 'react';

import { toast } from '@/components/toast/Toast';
// import { Tooltip } from '@/components/tooltip/Tooltip'; // TODO: Uncomment when access/permissions are restored
import { useContextSelector } from '@/hooks/useContextSelector';
import { LinkIcon } from '@/icons';
import { useApiClient } from '@/lib/apiClient';

import StudioContext from './StudioContext';
import { StudioProjectManagementContext } from './StudioProjectManagementContext';

interface StudioShareProjectModalProps {
  isOpen: boolean;
  onClose: () => void;
  projectTitle: string;
  projectId: string;
  onProjectTitleChange: (title: string) => void;
  latestVersionId?: string | null;
}

interface ShareProjectModalStage1Props {
  projectTitle: string;
  onSkip: () => void;
  onSave: (newTitle: string) => void;
}

interface ShareProjectModalStage2Props {
  projectTitle: string;
  shareUrl: string | null;
  onClose: () => void;
  isLoadingUrl?: boolean;
}

// Styled components for Figma design
const Overlay = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: var(--color-opacity-black-60);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
`;

const ModalContainer = styled.div`
  background: rgb(var(--rgb-dumbo-100));
  border-radius: 24px;
  padding: 32px;
  width: 480px;
  max-width: 90vw;
  box-shadow:
    0 20px 25px -5px var(--color-opacity-black-10),
    0 10px 10px -5px var(--color-opacity-black-4);
  display: flex;
  flex-direction: column;
  gap: 32px;
  align-items: center;
`;

const ContentWrapper = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  width: 100%;
`;

const Title = styled.h2`
  font-family: 'PP Neue Montreal', sans-serif;
  font-size: 28px;
  font-weight: 400;
  line-height: 34px;
  letter-spacing: 0.56px;
  margin: 0;
  color: rgb(var(--rgb-dumbo-900));
  text-align: center;
`;

const Description = styled.div`
  font-family: 'PP Neue Montreal', sans-serif;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0.32px;
  color: rgb(var(--rgb-dumbo-700));
  margin: 0;
  text-align: center;
  width: 290px;
`;

const Section = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
`;

const SectionLabel = styled.div`
  font-family: 'PP Neue Montreal', sans-serif;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0.32px;
  color: rgb(var(--rgb-dumbo-700));
`;

const ButtonContainer = styled.div`
  display: flex;
  gap: 8px;
  width: 100%;
`;

const StyledButton = styled.button<{ variant: 'transparent' | 'primary' }>`
  font-family: 'PP Neue Montreal', sans-serif;
  font-size: 18px;
  font-weight: 500;
  line-height: 24px;
  letter-spacing: 0.36px;
  height: 56px;
  border-radius: 100px;
  padding: 19px 24px;
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-width: 56px;
  flex: 1;

  ${(props) =>
    props.variant === 'transparent' &&
    `
    background: transparent;
    color: rgb(var(--rgb-dumbo-900));
  `}

  ${(props) =>
    props.variant === 'primary' &&
    `
    background: rgb(var(--rgb-dumbo-900));
    color: rgb(var(--rgb-dumbo-50));
  `}

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  &:hover:not(:disabled) {
    opacity: 0.9;
  }
`;

const StyledInput = styled.input`
  font-family: 'PP Neue Montreal', sans-serif;
  font-size: 14px;
  font-weight: 400;
  line-height: 20px;
  letter-spacing: 0.28px;
  color: rgb(var(--rgb-dumbo-900));
  background: transparent;
  border: 1px solid var(--color-opacity-white-15);
  border-radius: 12px;
  padding: 0 16px;
  width: 100%;
  height: 56px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;

  &:focus {
    outline: none;
    border-color: var(--color-opacity-white-30);
  }

  &::placeholder {
    color: rgb(var(--rgb-dumbo-900));
    opacity: 1;
  }
`;

const ShareProjectModalStage1: React.FC<ShareProjectModalStage1Props> = ({
  projectTitle,
  onSkip,
  onSave,
}) => {
  const [inputTitle, setInputTitle] = useState(
    projectTitle.startsWith('Untitled Project') ? '' : projectTitle
  );

  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onSkip();
    }
  };

  return (
    <Overlay onClick={handleOverlayClick}>
      <ModalContainer>
        <ContentWrapper>
          <Title>Name project before sharing</Title>
          <Description>
            Give your project a name before it's shared with others
          </Description>
        </ContentWrapper>

        <StyledInput
          type='text'
          value={inputTitle}
          onChange={(e) => setInputTitle(e.target.value)}
          placeholder='Untitled Project'
          autoFocus
        />

        <ButtonContainer>
          <StyledButton variant='transparent' onClick={onSkip}>
            Skip
          </StyledButton>
          <StyledButton
            variant='primary'
            onClick={() => onSave(inputTitle || projectTitle)}
          >
            Save
          </StyledButton>
        </ButtonContainer>
      </ModalContainer>
    </Overlay>
  );
};

const ShareProjectModalStage2: React.FC<ShareProjectModalStage2Props> = ({
  projectTitle,
  shareUrl,
  onClose,
  isLoadingUrl = false,
}) => {
  const [copySuccess, setCopySuccess] = useState(false);

  useEffect(() => {
    if (copySuccess === true) {
      const timeout = setTimeout(() => {
        setCopySuccess(false);
      }, 2000);
      return () => {
        clearTimeout(timeout);
      };
    }
  }, [copySuccess]);

  const handleCopyLink = useCallback(async () => {
    if (!shareUrl) return; // Don't copy if no URL available

    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard
        .writeText(shareUrl)
        .then(() => {
          setCopySuccess(true);
          toast({
            title: 'Copied to clipboard',
            status: 'success',
          });
        })
        .catch((err) => {
          console.error('Failed to copy: ', err);
          toast({
            title: 'Failed to copy to clipboard',
            status: 'error',
          });
        });
    }
  }, [shareUrl]);

  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  return (
    <Overlay onClick={handleOverlayClick}>
      <ModalContainer>
        <ContentWrapper>
          <Title>Share "{projectTitle}"</Title>
        </ContentWrapper>

        <Section>
          <SectionLabel>
            <strong>
              Anyone with the link can view this project and create their own
              editable copy.
            </strong>
          </SectionLabel>
          <SectionLabel>
            Your original project will remain unchanged — others can’t edit or
            affect your version.
          </SectionLabel>
        </Section>

        <ButtonContainer>
          <StyledButton variant='transparent' onClick={onClose}>
            Done
          </StyledButton>
          <StyledButton
            variant='primary'
            onClick={handleCopyLink}
            disabled={!shareUrl || isLoadingUrl}
          >
            <LinkIcon className='h-4 w-4' />
            {isLoadingUrl ? 'Generating Link...' : 'Copy Link'}
          </StyledButton>
        </ButtonContainer>
      </ModalContainer>
    </Overlay>
  );
};

export default function StudioShareProjectModal({
  isOpen,
  onClose,
  projectTitle,
  projectId,
  onProjectTitleChange,
  latestVersionId,
}: StudioShareProjectModalProps) {
  const [stage, setStage] = useState<1 | 2>(1);
  const [finalTitle, setFinalTitle] = useState(projectTitle);

  const stateRef = useContextSelector(
    StudioContext,
    (context) => context.stateRef
  );

  const saveProject = useContextSelector(
    StudioProjectManagementContext,
    (context) => context.saveProject
  );

  const apiClient = useApiClient();
  const [fetchedVersionId, setFetchedVersionId] = useState<string | null>(null);
  const [isFetchingVersion, setIsFetchingVersion] = useState(false);

  // Fetch latest version ID if not provided and modal is open
  useEffect(() => {
    if (isOpen && !latestVersionId && !fetchedVersionId && !isFetchingVersion) {
      setIsFetchingVersion(true);
      apiClient
        .GET('/api/studio/{project_id}/versions', {
          params: {
            path: { project_id: projectId },
            query: { return_days_only: false },
          },
        })
        .then((response) => {
          const latestVersion = response.data?.aggregated_versions
            ?.flatMap((hour) => hour.versions)
            ?.sort(
              (a, b) =>
                new Date(b.created_at).getTime() -
                new Date(a.created_at).getTime()
            )?.[0];

          if (latestVersion?.version_id) {
            setFetchedVersionId(latestVersion.version_id);
          }
        })
        .catch((error) => {
          console.error('Failed to fetch latest version:', error);
          toast({
            title: 'Failed to generate share link',
            description: 'Could not fetch the latest version of your project.',
            status: 'error',
          });
        })
        .finally(() => {
          setIsFetchingVersion(false);
        });
    }
  }, [
    isOpen,
    latestVersionId,
    fetchedVersionId,
    isFetchingVersion,
    projectId,
    apiClient,
  ]);

  // Reset fetched version when modal closes
  useEffect(() => {
    if (!isOpen) {
      setFetchedVersionId(null);
      setIsFetchingVersion(false);
    }
  }, [isOpen]);

  // Get host and determine protocol (http for localhost, https for everything else)
  const host =
    typeof window !== 'undefined'
      ? window.location.host
      : process.env.VERCEL_URL
        ? process.env.VERCEL_URL
        : 'suno.com';
  const protocol = host.includes('localhost') ? 'http' : 'https';
  const baseUrl = `${protocol}://${host}`;

  // Generate share URL: always use project_version_id with latest version
  const actualVersionId = latestVersionId || fetchedVersionId;
  const shareUrl = actualVersionId
    ? `${baseUrl}/studio?project_version_id=${actualVersionId}`
    : null; // No share URL until we have a version ID

  // Reset stage when modal opens
  useEffect(() => {
    if (isOpen) {
      setStage(projectTitle.startsWith('Untitled Project') ? 1 : 2);
      setFinalTitle(projectTitle);
    }
  }, [isOpen, projectTitle]);

  const handleSkipRename = useCallback(() => {
    setStage(2);
  }, []);

  const handleSaveAndContinue = useCallback(
    async (newTitle: string) => {
      try {
        // Save the project with new title
        await saveProject(stateRef.current, newTitle);
        onProjectTitleChange(newTitle);
        setFinalTitle(newTitle);
        setStage(2);

        toast({
          title: 'Project renamed successfully',
          status: 'success',
        });
      } catch (error) {
        console.error('Failed to save project:', error);
        toast({
          title: 'Failed to rename project',
          status: 'error',
        });
      }
    },
    [saveProject, stateRef, onProjectTitleChange]
  );

  if (!isOpen) {
    return null;
  }

  if (stage === 1) {
    return (
      <ShareProjectModalStage1
        projectTitle={projectTitle}
        onSkip={handleSkipRename}
        onSave={handleSaveAndContinue}
      />
    );
  }

  return (
    <ShareProjectModalStage2
      projectTitle={finalTitle}
      shareUrl={shareUrl}
      onClose={onClose}
      isLoadingUrl={isFetchingVersion}
    />
  );
}
