import React, { lazy, useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import type { LocationData, ServiceData, BlogPostData } from '../data/seoData';

const LazyLocationPage = lazy(() => import('../pages/LocationPage'));
const LazyServicePage = lazy(() => import('../pages/ServicePage'));
const LazyBlogPostPage = lazy(() => import('../pages/BlogPostPage'));

type SeoRouteState<T> = {
  data: T | null;
  error: string | null;
};

const routeFallback = (
  <div className="min-h-[40vh] flex items-center justify-center px-6 text-sm text-gray-500 dark:text-gray-400">
    Loading page...
  </div>
);

function createSeoRoute<T extends { slug: string }>(
  loadData: () => Promise<{
    locationData?: LocationData[];
    serviceData?: ServiceData[];
    blogPostData?: BlogPostData[];
  }>,
  selectData: (module: Awaited<ReturnType<typeof loadData>>, slug: string) => T | undefined,
  Page: React.LazyExoticComponent<React.ComponentType<{ data: T }>>,
) {
  return function SeoRoute({ slug }: { slug: string }) {
    const [state, setState] = useState<SeoRouteState<T>>({
      data: null,
      error: null,
    });

    useEffect(() => {
      let active = true;

      setState({ data: null, error: null });

      loadData()
        .then((module) => {
          if (!active) return;

          const nextData = selectData(module, slug);
          setState({
            data: nextData ?? null,
            error: nextData ? null : `No SEO data found for ${slug}`,
          });
        })
        .catch((error: unknown) => {
          if (!active) return;

          setState({
            data: null,
            error: error instanceof Error ? error.message : 'Failed to load route data',
          });
        });

      return () => {
        active = false;
      };
    }, [slug]);

    if (state.error) {
      return (
        <div className="min-h-[40vh] flex items-center justify-center px-6 text-center">
          <div>
            <p className="text-sm uppercase tracking-widest text-gray-500 dark:text-gray-400 mb-2">
              Route unavailable
            </p>
            <p className="text-lg text-gray-900 dark:text-white">{state.error}</p>
          </div>
        </div>
      );
    }

    if (!state.data) {
      return routeFallback;
    }

    return <Page data={state.data} />;
  };
}

const loadSeoData = () => import('../data/seoData');

// Location pages — city IT support pages under /locations/
export const locationRoutes = [
  { path: '/locations/it-support-corpus-christi', slug: 'locations/it-support-corpus-christi' },
  { path: '/locations/it-support-portland-tx', slug: 'locations/it-support-portland-tx' },
  { path: '/locations/it-support-rockport-tx', slug: 'locations/it-support-rockport-tx' },
  { path: '/locations/it-support-aransas-pass-tx', slug: 'locations/it-support-aransas-pass-tx' },
  { path: '/locations/it-support-kingsville-tx', slug: 'locations/it-support-kingsville-tx' },
  // Service+location hybrid pages (stored in locationData, rendered via LocationPage)
  { path: '/services/web-design-corpus-christi', slug: 'services/web-design-corpus-christi' },
  { path: '/services/business-email-corpus-christi', slug: 'services/business-email-corpus-christi' },
];

// Service pages — all under /services/
export const serviceRoutes = [
  { path: '/services/it-help-desk', slug: 'services/it-help-desk' },
  { path: '/services/computer-support', slug: 'services/computer-support' },
  { path: '/services/business-email-services', slug: 'services/business-email-services' },
  { path: '/services/domain-registration-dns-support', slug: 'services/domain-registration-dns-support' },
  { path: '/services/printer-scanner-installation', slug: 'services/printer-scanner-installation' },
  { path: '/services/shared-drive', slug: 'services/shared-drive' },
  { path: '/services/network-infrastructure-support', slug: 'services/network-infrastructure-support' },
];

// Authority blog posts only — location posts redirect to their location pages
export const blogRoutes = [
  { path: '/blog/it-support-small-business-corpus-christi', slug: 'blog/it-support-small-business-corpus-christi' },
  { path: '/blog/outsourced-it-support-corpus-christi', slug: 'blog/outsourced-it-support-corpus-christi' },
  { path: '/blog/it-service-vs-inhouse-it', slug: 'blog/it-service-vs-inhouse-it' },
  { path: '/blog/common-it-problems-businesses-corpus-christi', slug: 'blog/common-it-problems-businesses-corpus-christi' },
  { path: '/blog/business-email-vs-google-workspace-vs-microsoft-365', slug: 'blog/business-email-vs-google-workspace-vs-microsoft-365' },
];

// Old flat-URL redirects — 301-equivalent for any links pointing to old paths
export const legacyRedirects = [
  { from: '/it-support-corpus-christi', to: '/locations/it-support-corpus-christi' },
  { from: '/it-support-portland-tx', to: '/locations/it-support-portland-tx' },
  { from: '/it-support-rockport-tx', to: '/locations/it-support-rockport-tx' },
  { from: '/it-support-aransas-pass-tx', to: '/locations/it-support-aransas-pass-tx' },
  { from: '/it-support-kingsville-tx', to: '/locations/it-support-kingsville-tx' },
  { from: '/it-help-desk', to: '/services/it-help-desk' },
  { from: '/computer-support', to: '/services/computer-support' },
  { from: '/business-email-services', to: '/services/business-email-services' },
  { from: '/domain-registration-dns-support', to: '/services/domain-registration-dns-support' },
  { from: '/printer-scanner-installation', to: '/services/printer-scanner-installation' },
  { from: '/shared-drive', to: '/services/shared-drive' },
  { from: '/network-infrastructure-support', to: '/services/network-infrastructure-support' },
  { from: '/web-design-corpus-christi', to: '/services/web-design-corpus-christi' },
  { from: '/business-email-corpus-christi', to: '/services/business-email-corpus-christi' },
  { from: '/blog/it-support-cost-corpus-christi', to: '/locations/it-support-corpus-christi' },
  // Location blog posts → their canonical location pages
  { from: '/blog/it-support-corpus-christi-blog', to: '/locations/it-support-corpus-christi' },
  { from: '/blog/it-support-portland-tx-blog', to: '/locations/it-support-portland-tx' },
  { from: '/blog/it-support-rockport-tx-blog', to: '/locations/it-support-rockport-tx' },
  { from: '/blog/it-support-aransas-pass-blog', to: '/locations/it-support-aransas-pass-tx' },
  { from: '/blog/it-support-kingsville-tx-blog', to: '/locations/it-support-kingsville-tx' },
];

export const LocationSeoRoute = createSeoRoute<LocationData>(
  loadSeoData,
  (module, slug) => module.locationData.find((item) => item.slug === slug),
  LazyLocationPage,
);

export const ServiceSeoRoute = createSeoRoute<ServiceData>(
  loadSeoData,
  (module, slug) => module.serviceData.find((item) => item.slug === slug),
  LazyServicePage,
);

export const BlogSeoRoute = createSeoRoute<BlogPostData>(
  loadSeoData,
  (module, slug) => module.blogPostData.find((item) => item.slug === slug),
  LazyBlogPostPage,
);
