import { mdiChartTimelineVariant } from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import { useRouter } from 'next/router';
import React, { ReactElement, useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import CardBox from '../../components/CardBox';
import LoadingSpinner from '../../components/LoadingSpinner';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import dataFormatter from '../../helpers/dataFormatter';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import { logger } from '../../lib/logger';

type PublishEvent = {
  id: string;
  title?: string;
  description?: string;
  started_at?: string;
  finished_at?: string;
  createdAt?: string;
};

const PublishEventsHistoryPage = () => {
  const router = useRouter();
  const [items, setItems] = useState<PublishEvent[]>([]);
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  // Check if projects exist and redirect if not
  useEffect(() => {
    const checkProjects = async () => {
      try {
        const response = await axios.get('/projects/autocomplete?limit=1');
        const projects = Array.isArray(response?.data) ? response.data : [];
        if (projects.length === 0) {
          toast('Please create a project first', {
            type: 'info',
            position: 'bottom-center',
          });
          router.replace('/projects/projects-new');
        }
      } catch (error) {
        logger.error(
          'Failed to check projects:',
          error instanceof Error ? error : { error },
        );
      }
    };
    checkProjects();
  }, [router]);

  useEffect(() => {
    const loadHistory = async () => {
      setLoading(true);
      setErrorMessage('');

      try {
        const response = await axios.get(
          '/publish_events?limit=100&sort=desc&field=started_at',
        );
        const rows = Array.isArray(response?.data?.rows)
          ? response.data.rows
          : [];
        setItems(rows);
      } catch (error: any) {
        logger.error(
          'Failed to load publish history:',
          error instanceof Error ? error : { error },
        );
        setErrorMessage(
          error?.response?.data?.message ||
            error?.message ||
            'Failed to load publish history',
        );
      } finally {
        setLoading(false);
      }
    };

    loadHistory();
  }, []);

  return (
    <>
      <Head>
        <title>{getPageTitle('Publish History')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Publish History'
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <CardBox>
          {loading ? <LoadingSpinner /> : null}

          {!loading && errorMessage ? (
            <p className='text-sm text-red-600'>{errorMessage}</p>
          ) : null}

          {!loading && !errorMessage && items.length === 0 ? (
            <p className='text-sm text-gray-500'>No publishing history yet.</p>
          ) : null}

          {!loading && !errorMessage && items.length > 0 ? (
            <div className='space-y-3'>
              {items.map((item) => {
                const publishDate =
                  item.started_at || item.finished_at || item.createdAt;

                return (
                  <details
                    key={item.id}
                    className='rounded border border-gray-200 dark:border-dark-700'
                  >
                    <summary className='list-none cursor-pointer px-4 py-3 flex items-center justify-between gap-3'>
                      <span className='font-medium'>
                        {item.title || 'Untitled publish event'}
                      </span>
                      <span className='text-xs text-gray-500 whitespace-nowrap'>
                        {publishDate
                          ? dataFormatter.dateTimeFormatter(publishDate)
                          : 'No date'}
                      </span>
                    </summary>
                    <div className='px-4 pb-4 text-sm text-gray-600 dark:text-gray-300'>
                      {item.description || 'No description'}
                    </div>
                  </details>
                );
              })}
            </div>
          ) : null}
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default PublishEventsHistoryPage;
