import {
  mdiChartTimelineVariant,
  mdiCog,
  mdiFileDocumentMultiple,
  mdiFolderMultipleImage,
  mdiPencil,
  mdiPublish,
  mdiViewDashboard,
  mdiWidgets,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import { useRouter } from 'next/router';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import { toast, ToastContainer } from 'react-toastify';
import BaseButton from '../../components/BaseButton';
import BaseButtons from '../../components/BaseButtons';
import CardBox from '../../components/CardBox';
import CardBoxModal from '../../components/CardBoxModal';
import FormField from '../../components/FormField';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { logger } from '../../lib/logger';

type ProjectData = {
  id: string;
  name?: string;
  slug?: string;
  phase?: string;
  description?: string | null;
};

const ProjectWorkspacePage = () => {
  const router = useRouter();
  const { projectsId } = router.query;

  const projectId = useMemo(() => {
    if (Array.isArray(projectsId)) return projectsId[0] || '';
    return String(projectsId || '');
  }, [projectsId]);

  const [project, setProject] = useState<ProjectData | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isPublishing, setIsPublishing] = useState(false);
  const [isPublishModalActive, setIsPublishModalActive] = useState(false);
  const [publishTitle, setPublishTitle] = useState('');
  const [publishDescription, setPublishDescription] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  useEffect(() => {
    if (!projectId) return;

    const loadProject = async () => {
      setIsLoading(true);
      setErrorMessage('');
      try {
        const response = await axios.get(`/projects/${projectId}`);
        setProject(response?.data || null);
      } catch (error: any) {
        setErrorMessage(
          error?.response?.data?.message ||
            error?.message ||
            'Failed to load project',
        );
        logger.error(
          'Failed to load selected project page:',
          error instanceof Error ? error : { error },
        );
      } finally {
        setIsLoading(false);
      }
    };

    loadProject();
  }, [projectId]);

  const handlePublish = async () => {
    if (!projectId) {
      toast('Project is required', {
        type: 'warning',
        position: 'bottom-center',
      });
      return;
    }

    const title = publishTitle.trim();
    const description = publishDescription.trim();

    if (!title || !description) {
      toast('Title and description are required', {
        type: 'warning',
        position: 'bottom-center',
      });
      return;
    }

    setIsPublishing(true);
    try {
      const response = await axios.post('/publish', {
        projectId,
        title,
        description,
      });
      const summary = response?.data?.summary;
      toast(
        summary
          ? `Published: ${summary.pages_copied} pages`
          : 'Publish completed successfully',
        { type: 'success', position: 'bottom-center' },
      );
      setIsPublishModalActive(false);
      setPublishTitle('');
      setPublishDescription('');
    } catch (error: any) {
      logger.error(
        'Publish failed:',
        error instanceof Error
          ? error
          : { error: error?.message || 'Unknown error' },
      );
      const message =
        error?.response?.data || error?.message || 'Publish failed';
      toast(typeof message === 'string' ? message : 'Publish failed', {
        type: 'error',
        position: 'bottom-center',
      });
    } finally {
      setIsPublishing(false);
    }
  };

  const presentationLinks = useMemo(() => {
    const projectSlug = project?.slug?.trim();

    if (!projectSlug) {
      return { production: '', stage: '' };
    }

    // Use path-based URLs that work without DNS configuration
    return {
      production: `/p/${projectSlug}`,
      stage: `/p/${projectSlug}/stage`,
    };
  }, [project?.slug]);

  const openPresentation = (url: string, label: string) => {
    if (!url) {
      toast(
        `Unable to open ${label}: project slug or runtime domain is missing`,
        {
          type: 'warning',
          position: 'bottom-center',
        },
      );
      return;
    }

    window.open(url, '_blank', 'noopener,noreferrer');
  };

  return (
    <>
      <Head>
        <title>
          {getPageTitle(
            project?.name ? `Project: ${project.name}` : 'Selected Project',
          )}
        </title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Selected Project'
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <CardBox className='mb-6'>
          {isLoading ? (
            <p className='text-sm text-gray-500'>Loading project...</p>
          ) : errorMessage ? (
            <p className='text-sm text-red-600'>{errorMessage}</p>
          ) : project ? (
            <div className='space-y-1'>
              <h2 className='text-xl font-semibold'>{project.name}</h2>
              <p className='text-sm text-gray-500'>Slug: {project.slug}</p>
              {project.description ? (
                <p className='text-sm text-gray-600 mt-2'>
                  {project.description}
                </p>
              ) : null}
              <div className='pt-2'>
                <BaseButton
                  color='lightDark'
                  icon={mdiPencil}
                  href={`/projects/projects-edit?id=${projectId}`}
                  label='Edit Project Settings'
                />
              </div>
            </div>
          ) : (
            <p className='text-sm text-gray-500'>Project not found.</p>
          )}
        </CardBox>

        <div className='grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4'>
          <CardBox>
            <h3 className='text-lg font-semibold mb-2'>Constructor</h3>
            <p className='text-sm text-gray-500 mb-3'>
              Build and publish project runtime.
            </p>
            <BaseButton
              href={`/constructor?projectId=${projectId}`}
              icon={mdiViewDashboard}
              color='info'
              label='Open Constructor'
              disabled={!projectId}
            />
          </CardBox>

          <CardBox>
            <h3 className='text-lg font-semibold mb-2'>Assets</h3>
            <p className='text-sm text-gray-500 mb-3'>
              Manage project branding and media.
            </p>
            <BaseButton
              href={`/assets/assets-list?projectId=${projectId}`}
              icon={mdiFolderMultipleImage}
              color='info'
              label='Open Assets'
              disabled={!projectId}
            />
          </CardBox>

          <CardBox>
            <h3 className='text-lg font-semibold mb-2'>Pages & Transitions</h3>
            <p className='text-sm text-gray-500 mb-3'>
              Manage project routes and transitions.
            </p>
            <BaseButton
              href={`/tour_pages/tour_pages-list?projectId=${projectId}`}
              icon={mdiFileDocumentMultiple}
              color='info'
              label='Open Pages & Transitions'
              disabled={!projectId}
            />
          </CardBox>

          <CardBox>
            <h3 className='text-lg font-semibold mb-2'>Element Defaults</h3>
            <p className='text-sm text-gray-500 mb-3'>
              Default settings for new elements in this project.
            </p>
            <BaseButton
              href={`/project-element-defaults?projectId=${projectId}`}
              icon={mdiCog}
              color='info'
              label='Open Element Defaults'
              disabled={!projectId}
            />
          </CardBox>
        </div>

        <CardBox className='mt-6'>
          <h3 className='text-lg font-semibold mb-2'>Publish</h3>
          <p className='text-sm text-gray-500 mb-3'>
            Promote stage data to production for this project.
          </p>
          <BaseButtons>
            <BaseButton
              icon={mdiPublish}
              label={isPublishing ? 'Publishing...' : 'Publish to Production'}
              color='success'
              onClick={() => setIsPublishModalActive(true)}
              disabled={isPublishing || !projectId}
            />
            <BaseButton
              label='To Production Presentation'
              color='info'
              onClick={() =>
                openPresentation(
                  presentationLinks.production,
                  'production presentation',
                )
              }
              disabled={!projectId || !project?.slug}
            />
            <BaseButton
              label='To Stage Presentation'
              color='lightDark'
              onClick={() =>
                openPresentation(presentationLinks.stage, 'stage presentation')
              }
              disabled={!projectId || !project?.slug}
            />
            <BaseButton
              href='/publish_events/publish_events-list'
              label='History'
              color='lightDark'
            />
          </BaseButtons>
        </CardBox>

        <CardBoxModal
          title='Publish to production'
          buttonColor='success'
          buttonLabel={isPublishing ? 'Publishing...' : 'Confirm publish'}
          isConfirmDisabled={
            isPublishing || !publishTitle.trim() || !publishDescription.trim()
          }
          isActive={isPublishModalActive}
          onConfirm={handlePublish}
          onCancel={() => {
            if (isPublishing) return;
            setIsPublishModalActive(false);
          }}
        >
          <p className='text-sm text-gray-500'>
            Add title and description for this publish event.
          </p>
          <FormField label='Event title'>
            <input
              className='px-2 py-2 max-w-full w-full border-gray-300 rounded border'
              value={publishTitle}
              onChange={(event) => setPublishTitle(event.target.value)}
              placeholder='e.g. Release 1.0.3'
            />
          </FormField>
          <FormField label='Event description'>
            <textarea
              className='px-2 py-2 max-w-full w-full border-gray-300 rounded border h-24'
              value={publishDescription}
              onChange={(event) => setPublishDescription(event.target.value)}
              placeholder='Describe what was published'
            />
          </FormField>
        </CardBoxModal>

        <ToastContainer />
      </SectionMain>
    </>
  );
};

ProjectWorkspacePage.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission='READ_PROJECTS'>{page}</LayoutAuthenticated>
  );
};

export default ProjectWorkspacePage;
