import { useEffect } from 'react';

import { Head, Link, usePage } from '@inertiajs/react';

import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import InertiaPagination from '@/Components/Shared/InertiaPagination';
import { Badge } from '@/Components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { useChangelogBadge } from '@/hooks/useChangelogBadge';
import { formatDateOnly } from '@/lib/format';
import { type PageProps } from '@/types';

interface ChangelogEntry {
  id: number;
  title: string;
  body: string;
  version: string | null;
  type: 'feature' | 'improvement' | 'fix' | 'security';
  published_at: string;
}

interface PaginatedEntries {
  data: ChangelogEntry[];
  current_page: number;
  last_page: number;
  total: number;
  links: { url: string | null; label: string; active: boolean }[];
}

interface Props {
  entries: PaginatedEntries;
  can_login: boolean;
  can_register: boolean;
}

const TYPE_LABELS: Record<string, string> = {
  feature: 'New Feature',
  improvement: 'Improvement',
  fix: 'Bug Fix',
  security: 'Security',
};

const TYPE_VARIANTS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
  feature: 'default',
  improvement: 'secondary',
  fix: 'outline',
  security: 'destructive',
};

type ChangelogComponent = ((props: Props) => JSX.Element) & {
  disableGlobalUi?: boolean;
};

const Changelog: ChangelogComponent = ({ entries, can_login, can_register }) => {
  const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';
  const { app_url } = usePage<PageProps>().props;

  const latestEntryAt = entries.data[0]?.published_at;
  const { markSeen } = useChangelogBadge(latestEntryAt);

  // Mark changelog as read whenever this page is visited
  useEffect(() => {
    markSeen(latestEntryAt);
  }, [markSeen, latestEntryAt]);

  return (
    <>
      <Head title={`Changelog — ${appName}`}>
        <link rel="canonical" href={`${app_url}/changelog`} />
        <meta
          name="description"
          content={`See what's new in ${appName}. Latest features, improvements, bug fixes, and security updates.`}
        />
        <meta property="og:title" content={`Changelog — ${appName}`} />
        <meta
          property="og:description"
          content={`Latest updates and improvements to ${appName}.`}
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content={`${app_url}/changelog`} />
        <meta property="og:image" content={`${app_url}/og-image.png`} />
        <meta property="og:image:width" content="1200" />
        <meta property="og:image:height" content="630" />
        <meta name="twitter:card" content="summary_large_image" />
        <meta name="twitter:site" content="@rankwiz_ai" />
        <meta name="twitter:title" content={`Changelog — ${appName}`} />
        <meta
          name="twitter:description"
          content={`Latest updates and improvements to ${appName}.`}
        />
        <meta name="twitter:image" content={`${app_url}/og-image.png`} />
        <meta name="twitter:image:width" content="1200" />
        <meta name="twitter:image:height" content="630" />
        <script type="application/ld+json">
          {JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'BreadcrumbList',
            itemListElement: [
              {
                '@type': 'ListItem',
                position: 1,
                name: 'Home',
                item: `${app_url}/`,
              },
              {
                '@type': 'ListItem',
                position: 2,
                name: 'Changelog',
                item: `${app_url}/changelog`,
              },
            ],
          })}
        </script>
      </Head>

      <div className="min-h-screen bg-linear-to-b from-background to-muted/30">
        <MarketingNav canLogin={can_login} canRegister={can_register} />

        <main id="main-content">
          <div className="mx-auto max-w-3xl px-4 py-16">
            <div className="mb-12 text-center">
              <h1 className="text-foreground text-4xl font-bold tracking-tight">Changelog</h1>
              <p className="text-muted-foreground mt-4 text-lg">
                New updates and improvements to {appName}.
              </p>
              <p className="text-muted-foreground mt-3 text-sm">
                Missing something?{' '}
                <Link
                  href={route('feature-requests.index')}
                  className="text-primary underline underline-offset-4 hover:no-underline"
                >
                  Request a feature
                </Link>{' '}
                and vote on what gets built next.
              </p>
            </div>

            <div className="space-y-6">
              {entries.data.map((entry) => (
                <Card key={entry.id}>
                  <CardHeader className="pb-3">
                    <div className="flex flex-wrap items-start justify-between gap-2">
                      <CardTitle className="text-lg">{entry.title}</CardTitle>
                      <div className="flex items-center gap-2">
                        {entry.version && (
                          <span className="text-muted-foreground font-mono text-sm">
                            v{entry.version}
                          </span>
                        )}
                        <Badge variant={TYPE_VARIANTS[entry.type] ?? 'outline'}>
                          {TYPE_LABELS[entry.type] ?? entry.type}
                        </Badge>
                      </div>
                    </div>
                    <p className="text-muted-foreground text-sm">
                      {formatDateOnly(entry.published_at, 'long')}
                    </p>
                  </CardHeader>
                  <CardContent>
                    <div className="prose prose-sm dark:prose-invert max-w-none">
                      <p className="text-foreground whitespace-pre-wrap text-sm leading-relaxed">
                        {entry.body}
                      </p>
                    </div>
                  </CardContent>
                </Card>
              ))}

              {entries.data.length === 0 && (
                <div className="py-16 text-center">
                  <p className="text-muted-foreground">No changelog entries yet.</p>
                </div>
              )}
            </div>

            {entries.last_page > 1 && (
              <div className="mt-8">
                <InertiaPagination
                  links={entries.links}
                  currentPage={entries.current_page}
                  lastPage={entries.last_page}
                />
              </div>
            )}
          </div>
        </main>

        <MarketingFooter />
      </div>
    </>
  );
};

Changelog.disableGlobalUi = true;

export default Changelog;
