import { mdiPaletteSwatch } from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React, { ReactElement, useCallback, useEffect, useState } from 'react';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { logger } from '../lib/logger';
import type { UiElementDefault } from '../types/constructor';

type ElementTypeDefault = UiElementDefault & {
  element_type: string;
  name?: string;
  sort_order?: number;
};

const toHumanLabel = (value: string) =>
  String(value || '')
    .split('_')
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ');

const ElementTypeDefaultsPage = () => {
  const [rows, setRows] = useState<ElementTypeDefault[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const loadRows = useCallback(async () => {
    try {
      setIsLoading(true);
      setErrorMessage('');

      const response = await axios.get(
        '/element-type-defaults?limit=1000&page=0&sort=asc&field=sort_order',
      );

      const nextRows: ElementTypeDefault[] = Array.isArray(response?.data?.rows)
        ? response.data.rows
        : [];
      setRows(nextRows);
    } catch (error: any) {
      const message =
        error?.response?.data?.message ||
        error?.message ||
        'Failed to load element type defaults.';
      logger.error(
        'Failed to load element type defaults:',
        error instanceof Error ? error : { error },
      );
      setErrorMessage(message);
      setRows([]);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadRows();
  }, [loadRows]);

  return (
    <>
      <Head>
        <title>{getPageTitle('Element Type Defaults')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiPaletteSwatch}
          title='Element Type Defaults'
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <CardBox>
          {isLoading ? (
            <p className='text-sm text-gray-500'>
              Loading element type defaults...
            </p>
          ) : errorMessage ? (
            <p className='text-sm text-red-600'>{errorMessage}</p>
          ) : rows.length === 0 ? (
            <p className='text-sm text-gray-500'>
              No element type defaults found.
            </p>
          ) : (
            <div className='space-y-2'>
              {rows.map((item) => (
                <Link
                  key={item.id}
                  href={`/element-type-defaults/${item.id}`}
                  className='block rounded border border-gray-200 px-3 py-2 hover:bg-gray-50 dark:border-dark-700 dark:hover:bg-dark-800'
                >
                  <p className='text-sm font-semibold'>
                    {item.name || toHumanLabel(item.element_type)}
                  </p>
                  <p className='text-xs text-gray-500'>
                    {toHumanLabel(item.element_type)} • Order{' '}
                    {Number(item.sort_order || 0)} •{' '}
                    {item.is_active ? 'Active' : 'Inactive'}
                  </p>
                </Link>
              ))}
            </div>
          )}
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default ElementTypeDefaultsPage;
