'use client';

import { useStatsigClient } from '@statsig/react-bindings';
import React, { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { useStores } from '@/app/(root)/AppProviders';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { useDialogModal } from '@/components/modal/DialogModal';
import { SONGIFY_CONFIG } from '@/config/songify';
import { getStatusText } from '@/hooks/songify/adapters';
import { useSongify } from '@/hooks/songify/useSongify';
import { UploadState } from '@/hooks/songify/useUploadState';
import { PlusIcon, TrashIcon } from '@/icons';
import { SongifyProject, SongifyProjectStatus } from '@/types/songify';

import './songify.css';
import { CreateView } from './views/CreateView';
import { ProjectHeader } from './views/ProjectHeader';
import { QuickActionsBar } from './views/QuickActionsBar';

type ViewType = 'create' | 'working' | 'done' | 'error';

export function SongifyPageClient() {
  const { t } = useTranslation();
  const { launchDialog } = useDialogModal();
  const songify = useSongify();

  // Check feature flag using Statsig
  const statsigClient = useStatsigClient();
  const isStatsigReady = statsigClient?.client?.loadingStatus === 'Ready';

  // Local state for form and UI
  const [currentView, setCurrentView] = useState<ViewType>('create');
  const [isSongifyEnabled, setIsSongifyEnabled] = useState(true);
  const [s3FileName, setS3FileName] = useState('');
  const [genre, setGenre] = useState('pop');
  const [numGenerations, setNumGenerations] = useState(2);
  const [enableLyricOverlay, setEnableLyricOverlay] = useState(false);
  const { session } = useStores();

  // Edit state
  const [editingProjectRequestId, setEditingProjectRequestId] = useState<
    string | null
  >(null);
  const [editingProjectName, setEditingProjectName] = useState('');

  // Upload state
  const uploadState = useMemo(
    () =>
      new UploadState({
        setS3FileName: setS3FileName,
        maxFileSizeMb: SONGIFY_CONFIG.MAX_FILE_SIZE_MB,
        maxFileSize: SONGIFY_CONFIG.MAX_FILE_SIZE,
      }),
    []
  );

  // Navigation functions
  const navigateToCreateView = () => {
    setCurrentView('create');
    songify.selectProject(null);
  };

  const navigateToWorkingView = (project: SongifyProject) => {
    setCurrentView('working');
    songify.selectProject(project);
  };

  const navigateToDoneView = (project: SongifyProject) => {
    setCurrentView('done');
    songify.selectProject(project);
  };

  const navigateToErrorView = (project: SongifyProject) => {
    setCurrentView('error');
    songify.selectProject(project);
  };

  // Auto-navigate based on project status changes
  useEffect(() => {
    if (currentView === 'working' && songify.selectedProject?.status) {
      if (songify.selectedProject.status === SongifyProjectStatus.COMPLETED) {
        navigateToDoneView(songify.selectedProject);
      } else if (
        [
          SongifyProjectStatus.FAILED_EXPECTED,
          SongifyProjectStatus.FAILED_SYSTEM,
          SongifyProjectStatus.CANCELLED,
          SongifyProjectStatus.ERROR,
        ].includes(songify.selectedProject.status)
      ) {
        navigateToErrorView(songify.selectedProject);
      }
    }
  }, [songify.selectedProject?.status, currentView]);

  useEffect(() => {
    if (isStatsigReady) {
      setIsSongifyEnabled(statsigClient.checkGate('songify-web-ui'));
    }
  }, [isStatsigReady, statsigClient]);

  // Handlers
  const handleNewProject = () => {
    navigateToCreateView();
    setS3FileName('');
    setGenre('pop');
    setEnableLyricOverlay(false);
    setNumGenerations(2);
    uploadState.reset();
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!uploadState.uploadSuccess || !uploadState.uploadedFilename) {
      alert('Please wait for the video upload to complete before submitting.');
      return;
    }

    try {
      const result = await songify.createProject({
        name: `${genre} Project`,
        s3FileName: uploadState.uploadedFilename,
        genre,
        numGenerations,
        enableLyricOverlay,
      });

      // Navigate to working view
      if (result.project) {
        navigateToWorkingView(result.project);
      }

      // Reset upload state after successful submission
      uploadState.reset();
    } catch (error) {
      console.error('Failed to create project:', error);
      alert(
        'Request failed, but videos may still generate in the background. Check back in a few minutes.'
      );
    }
  };

  const handleDeleteAllProjects = async () => {
    const action = await launchDialog<boolean>(
      'Are you sure you want to delete all projects? This action cannot be undone.',
      [
        { label: t('cta.confirm', 'Confirm'), action: true },
        { label: t('cta.cancel', 'Cancel'), action: false },
      ]
    );

    if (action === true) {
      songify.deleteAllProjects();
      navigateToCreateView();
    }
  };

  const handleEditProject = (project: SongifyProject) => {
    setEditingProjectRequestId(project.requestId);
    setEditingProjectName(project.name);
  };

  const handleSaveProjectName = async () => {
    if (editingProjectName.trim() && editingProjectRequestId) {
      try {
        await songify.updateProject(editingProjectRequestId, {
          name: editingProjectName.trim(),
        });
      } catch (error) {
        console.error('Failed to update project:', error);
      }
    }
    setEditingProjectRequestId(null);
    setEditingProjectName('');
  };

  const handleCancelEdit = () => {
    setEditingProjectRequestId(null);
    setEditingProjectName('');
  };

  const handleDeleteProject = async (requestId: string) => {
    const projectToDelete = songify.projects.find(
      (p: SongifyProject) => p.requestId === requestId
    );
    if (!projectToDelete) return;

    const action = await launchDialog<boolean>(
      `Are you sure you want to delete "${projectToDelete.name}"? This action cannot be undone.`,
      [
        { label: t('cta.confirm', 'Confirm'), action: true },
        { label: t('cta.cancel', 'Cancel'), action: false },
      ]
    );

    if (action === true) {
      try {
        await songify.deleteProject(requestId);
        if (songify.selectedProject?.requestId === requestId) {
          navigateToCreateView();
        }
      } catch (error) {
        console.error('Failed to delete project:', error);
      }
    }
  };

  const handleRegenerate = async () => {
    if (!songify.selectedProject) return;

    try {
      const result = await songify.regenerateProject(songify.selectedProject);
      if (result.project) {
        navigateToWorkingView(result.project);
      }
    } catch (error) {
      console.error('Failed to regenerate project:', error);
      alert(
        'Regenerate failed, but videos may still generate in the background. Check back in a few minutes.'
      );
    }
  };

  const handleReusePrompt = () => {
    if (!songify.selectedProject) return;

    // Prefill fields from selected project
    setS3FileName(songify.selectedProject.s3FileName || '');
    setGenre(songify.selectedProject.genre || 'pop');
    setNumGenerations(songify.selectedProject.numGenerations || 2);
    // Navigate to create view with prefilled state
    navigateToCreateView();
  };

  // Show access denied if feature flag is not enabled
  // Show loading state while Statsig or Songify data is loading
  if (
    !isStatsigReady ||
    songify.isLoading ||
    !session.user ||
    !isSongifyEnabled
  ) {
    return (
      <div className='flex h-screen w-full bg-background-primary'>
        <div className='flex flex-1 items-center justify-center'>
          <div className='text-center'>
            <div className='mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2 border-accent-brand'></div>
            <p className='text-foreground-secondary'>Loading...</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className='flex h-screen w-full bg-background-primary'>
      {/* Sidebar */}
      <div className='hidden w-64 flex-col border-r border-border-primary bg-background-secondary md:flex'>
        <div className='border-b border-border-primary p-4'>
          <Button
            onClick={handleNewProject}
            variant={ButtonVariant.Primary}
            size={ButtonSize.Small}
            shape={ButtonShape.Pill}
            iconStart={PlusIcon}
            className='w-full bg-accent-pink text-foreground-primary hover:bg-accent-pink/90'
          >
            New Project
          </Button>
        </div>

        <div className='flex-1 overflow-y-auto p-4'>
          <div className='space-y-2'>
            {songify.projects.map((project: SongifyProject) => (
              <div
                key={project.requestId}
                className={`group relative w-full cursor-pointer rounded-lg p-3 text-left transition-colors hover:bg-background-tertiary ${
                  songify.selectedProject?.requestId === project.requestId
                    ? 'border border-border-primary bg-background-tertiary'
                    : ''
                }`}
                role='button'
                tabIndex={0}
                onClick={() => {
                  if (project.status === SongifyProjectStatus.COMPLETED) {
                    navigateToDoneView(project);
                  } else if (
                    [
                      SongifyProjectStatus.FAILED_EXPECTED,
                      SongifyProjectStatus.FAILED_SYSTEM,
                      SongifyProjectStatus.CANCELLED,
                      SongifyProjectStatus.ERROR,
                    ].includes(project.status)
                  ) {
                    navigateToErrorView(project);
                  } else {
                    navigateToWorkingView(project);
                  }
                }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    if (project.status === SongifyProjectStatus.COMPLETED) {
                      navigateToDoneView(project);
                    } else if (
                      [
                        SongifyProjectStatus.FAILED_EXPECTED,
                        SongifyProjectStatus.FAILED_SYSTEM,
                        SongifyProjectStatus.CANCELLED,
                        SongifyProjectStatus.ERROR,
                      ].includes(project.status)
                    ) {
                      navigateToErrorView(project);
                    } else {
                      navigateToWorkingView(project);
                    }
                  }
                }}
              >
                <div className='font-medium text-foreground-primary'>
                  {project.name}
                </div>
                <div className='text-sm text-foreground-secondary'>
                  {project.genre} • {project.videos.length} videos
                </div>
                <div className='text-xs text-foreground-tertiary'>
                  {new Date(project.createdAt).toLocaleDateString()} •{' '}
                  {getStatusText(project.status)}
                </div>

                <Button
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDeleteProject(project.requestId);
                  }}
                  variant={ButtonVariant.Tertiary}
                  size={ButtonSize.Mini}
                  icon={TrashIcon}
                  className='absolute top-3 right-3 opacity-0 transition-opacity group-hover:opacity-100 hover:text-accent-error'
                  title='Delete project'
                />
              </div>
            ))}
          </div>
        </div>

        {songify.projects.length > 1 && (
          <div className='border-t border-border-primary p-4'>
            <Button
              onClick={handleDeleteAllProjects}
              variant={ButtonVariant.Primary}
              size={ButtonSize.Medium}
              iconStart={TrashIcon}
              className='w-full border border-accent-error bg-transparent text-foreground-primary hover:border-accent-error/90'
            >
              Delete All Videos
            </Button>
          </div>
        )}
      </div>

      {/* Main Content */}
      <div className='flex-1 overflow-y-auto'>
        <div className='mx-auto p-8'>
          {currentView === 'create' && (
            <CreateView
              uploadState={uploadState}
              handleSubmit={handleSubmit}
              s3FileName={s3FileName}
              genre={genre}
              musicStyles={SONGIFY_CONFIG.MUSIC_STYLES}
              setGenre={setGenre}
              enableLyricOverlay={enableLyricOverlay}
              setEnableLyricOverlay={setEnableLyricOverlay}
              isSubmitting={songify.isCreating}
            />
          )}

          {(currentView === 'working' ||
            currentView === 'done' ||
            currentView === 'error') && (
            <>
              <ProjectHeader
                selectedProject={songify.selectedProject}
                editingProjectRequestId={editingProjectRequestId}
                editingProjectName={editingProjectName}
                setEditingProjectName={setEditingProjectName}
                handleSaveProjectName={handleSaveProjectName}
                handleCancelEdit={handleCancelEdit}
                handleEditProject={handleEditProject}
              />

              <QuickActionsBar
                onRegenerate={handleRegenerate}
                onReusePrompt={handleReusePrompt}
                disabled={!songify.selectedProject || songify.isRegenerating}
              />

              {currentView === 'working' && (
                <div className='flex min-h-[400px] flex-col items-center justify-center'>
                  <div className='mb-6 h-16 w-16 animate-spin rounded-full border-b-2 border-accent-brand'></div>
                  <h2 className='mb-4 text-2xl font-semibold text-foreground-primary'>
                    {songify.selectedProject?.status ===
                      SongifyProjectStatus.PROCESSING_UPLOAD &&
                      'Processing Upload'}
                    {songify.selectedProject?.status ===
                      SongifyProjectStatus.GENERATING_REMIXES &&
                      'Generating Remixes'}
                    {songify.selectedProject?.status ===
                      SongifyProjectStatus.GENERATING_VIDEOS &&
                      'Creating Videos'}
                    {!songify.selectedProject?.status && 'Processing...'}
                  </h2>
                  <p className='max-w-md text-center text-foreground-secondary'>
                    We're working on your songified videos! This usually takes
                    1-2 minutes.
                  </p>
                </div>
              )}

              {currentView === 'done' && (
                <div className='grid grid-cols-2 gap-6'>
                  {songify.selectedProject?.videos.map((video, index) => (
                    <div
                      key={video.id}
                      className='overflow-hidden rounded-lg border border-border-primary bg-background-secondary'
                    >
                      <div
                        className='relative bg-background-tertiary'
                        style={{ aspectRatio: '9/16' }}
                      >
                        <video
                          src={video.url}
                          className='h-full w-full object-contain'
                          controls
                        />
                      </div>
                      <div className='flex items-center justify-between p-4'>
                        <p className='text-foreground-secondary'>
                          {video.genre}
                        </p>
                        <Button
                          onClick={() => {
                            const link = document.createElement('a');
                            link.href = video.url;
                            link.download = `songify_video_${index + 1}.mp4`;
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                          }}
                          variant={ButtonVariant.Tertiary}
                          size={ButtonSize.Small}
                        >
                          Download
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {currentView === 'error' && (
                <div className='rounded-lg border border-accent-error/20 bg-accent-error/10 p-4 text-accent-error'>
                  <h2 className='mb-1 font-semibold'>
                    We hit a snag generating your videos
                  </h2>
                  <p className='mb-2 text-sm text-foreground-primary'>
                    Something went wrong while processing this project. You can
                    try again later, or start a new project.
                  </p>
                  {songify.selectedProject?.statusDetails?.message && (
                    <p className='text-sm'>
                      {songify.selectedProject.statusDetails.message}
                    </p>
                  )}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
