/**
 * React Router Setup Generator
 *
 * Generates router.tsx with routes based on spec views
 */

import type { TemplateContext } from '@specverse/types';

/**
 * Generate router.tsx with React Router v6 setup
 */
export default function generateRouter(context: TemplateContext): string {
  const { spec, models = [], views = [] } = context;

  // Extract views from spec if not provided
  const specViews = views.length > 0 ? views : (spec?.views ? Object.entries(spec.views) : []);

  // Generate imports
  const imports: string[] = [];
  const routes: string[] = [];

  // Add home route
  routes.push(`  {
    path: '/',
    element: <div className="home-page">
      <h1>Welcome</h1>
      <nav>
        <ul>
${generateHomeLinks(specViews, models)}
        </ul>
      </nav>
    </div>
  }`);

  // Track used paths to ensure uniqueness
  const usedPaths = new Set<string>();

  // Generate routes for each view
  specViews.forEach((viewEntry: any) => {
    const [viewName, viewDef] = Array.isArray(viewEntry) ? viewEntry : [viewEntry.name, viewEntry];

    // Determine route pattern based on view type
    const viewType = viewDef?.type || 'list';
    const model = Array.isArray(viewDef?.model) ? viewDef.model[0] : viewDef?.model;

    if (!model) return;

    const modelLower = model.toLowerCase();
    const modelPlural = modelLower + 's'; // Simple pluralization

    imports.push(`import ${viewName} from './components/${viewName}';`);

    // Generate unique path based on view name and type
    const basePath = `/${modelPlural}`;

    switch (viewType) {
      case 'list':
        // Use view name to create unique path if multiple list views
        const listPath = usedPaths.has(basePath)
          ? `${basePath}/${viewName.toLowerCase().replace(/view$/, '')}`
          : basePath;

        if (!usedPaths.has(listPath)) {
          routes.push(`  {
    path: '${listPath}',
    element: <${viewName} />
  }`);
          usedPaths.add(listPath);
        }
        break;

      case 'detail':
        const detailPath = `${basePath}/:id`;
        if (!usedPaths.has(detailPath)) {
          routes.push(`  {
    path: '${detailPath}',
    element: <${viewName} />
  }`);
          usedPaths.add(detailPath);
        }
        break;

      case 'form':
        const newPath = `${basePath}/new`;
        const editPath = `${basePath}/:id/edit`;

        if (!usedPaths.has(newPath)) {
          routes.push(`  {
    path: '${newPath}',
    element: <${viewName} />
  }`);
          usedPaths.add(newPath);
        }

        if (!usedPaths.has(editPath)) {
          routes.push(`  {
    path: '${editPath}',
    element: <${viewName} />
  }`);
          usedPaths.add(editPath);
        }
        break;

      case 'dashboard':
        // Use model name in dashboard path for uniqueness
        const dashPath = modelLower === 'author' || modelLower === 'user'
          ? '/dashboard'
          : `/dashboard/${modelLower}`;

        if (!usedPaths.has(dashPath)) {
          routes.push(`  {
    path: '${dashPath}',
    element: <${viewName} />
  }`);
          usedPaths.add(dashPath);
        }
        break;
    }
  });

  return `/**
 * React Router Configuration
 * Auto-generated by SpecVerse
 */

import { createBrowserRouter } from 'react-router-dom';
${imports.join('\n')}

/**
 * Application Router
 */
export const router = createBrowserRouter([
${routes.join(',\n')}
]);
`;
}

/**
 * Generate navigation links for home page
 */
function generateHomeLinks(views: any[], models: any[]): string {
  const links: string[] = [];
  const usedPaths = new Set<string>();

  views.forEach((viewEntry: any) => {
    const [viewName, viewDef] = Array.isArray(viewEntry) ? viewEntry : [viewEntry.name, viewEntry];
    const viewType = viewDef?.type || 'list';
    const model = Array.isArray(viewDef?.model) ? viewDef.model[0] : viewDef?.model;

    if (!model) return;

    const modelLower = model.toLowerCase();
    const modelPlural = modelLower + 's';
    const basePath = `/${modelPlural}`;

    // Generate descriptive label from view name
    const viewLabel = viewName.replace(/View$/, '').replace(/([A-Z])/g, ' $1').trim();

    switch (viewType) {
      case 'list':
        const listPath = usedPaths.has(basePath)
          ? `${basePath}/${viewName.toLowerCase().replace(/view$/, '')}`
          : basePath;

        if (!usedPaths.has(listPath)) {
          links.push(`          <li><a href="${listPath}">${viewLabel}</a></li>`);
          usedPaths.add(listPath);
        }
        break;

      case 'form':
        const formPath = `${basePath}/new`;
        if (!usedPaths.has(formPath)) {
          links.push(`          <li><a href="${formPath}">Create ${model}</a></li>`);
          usedPaths.add(formPath);
        }
        break;

      case 'dashboard':
        const dashPath = modelLower === 'author' || modelLower === 'user'
          ? '/dashboard'
          : `/dashboard/${modelLower}`;

        if (!usedPaths.has(dashPath)) {
          links.push(`          <li><a href="${dashPath}">${viewLabel}</a></li>`);
          usedPaths.add(dashPath);
        }
        break;

      case 'detail':
        // Don't add detail views to home links (they require IDs)
        break;
    }
  });

  return links.join('\n');
}
