import { ChevronUp } from 'lucide-react';

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

import { MarketingFooter } from '@/Components/marketing/MarketingFooter';
import { MarketingNav } from '@/Components/marketing/MarketingNav';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { trackEvent } from '@/lib/analytics';
import { ROADMAP_VOTE_CAST } from '@/lib/event-catalog';
import type { PageProps } from '@/types';

interface RoadmapItem {
  id: number;
  title: string;
  description: string | null;
  status: 'building' | 'in_progress' | 'planned';
  vote_count: number;
}

interface Props {
  building: RoadmapItem[];
  in_progress: RoadmapItem[];
  planned: RoadmapItem[];
  can_login: boolean;
  can_register: boolean;
  voted_ids: number[];
}

const STATUS_CONFIG = {
  building: {
    label: 'Building Now',
    badgeVariant: 'default' as const,
    description: 'Actively in development',
  },
  in_progress: {
    label: 'In Progress',
    badgeVariant: 'secondary' as const,
    description: 'Work has started',
  },
  planned: {
    label: 'Planned',
    badgeVariant: 'outline' as const,
    description: 'Committed to the roadmap',
  },
} as const;

function RoadmapColumn({
  title,
  description,
  items,
  status,
  votedSet,
  canVote,
  onVote,
}: {
  title: string;
  description: string;
  items: RoadmapItem[];
  status: keyof typeof STATUS_CONFIG;
  votedSet: Set<number>;
  canVote: boolean;
  onVote: (id: number) => void;
}) {
  const config = STATUS_CONFIG[status];

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center gap-2">
        <Badge variant={config.badgeVariant}>{title}</Badge>
        <span className="text-muted-foreground text-sm">{description}</span>
      </div>
      {items.length === 0 ? (
        <p className="text-muted-foreground text-sm italic">Nothing here yet.</p>
      ) : (
        items.map((item) => (
          <Card key={item.id}>
            <CardHeader className="pb-2">
              <div className="flex items-start justify-between gap-3">
                <CardTitle className="text-base">{item.title}</CardTitle>
                {canVote ? (
                  <Button
                    variant={votedSet.has(item.id) ? 'default' : 'outline'}
                    size="sm"
                    className="flex shrink-0 flex-col items-center gap-0.5 px-2 py-1"
                    onClick={() => onVote(item.id)}
                    aria-label={`Upvote ${item.title}`}
                    aria-pressed={votedSet.has(item.id)}
                  >
                    <ChevronUp className="h-3 w-3" />
                    <span className="text-xs font-semibold">{item.vote_count}</span>
                  </Button>
                ) : (
                  <div className="text-muted-foreground flex shrink-0 flex-col items-center gap-0.5 rounded-md border px-2 py-1">
                    <ChevronUp className="h-3 w-3" />
                    <span className="text-xs font-semibold">{item.vote_count}</span>
                  </div>
                )}
              </div>
            </CardHeader>
            {item.description && (
              <CardContent>
                <p className="text-muted-foreground text-sm">{item.description}</p>
              </CardContent>
            )}
          </Card>
        ))
      )}
    </div>
  );
}

export default function Roadmap({
  building,
  in_progress,
  planned,
  can_login,
  can_register,
  voted_ids,
}: Props) {
  const { app_url, auth } = usePage<PageProps>().props;
  const isAuthenticated = !!auth?.user;
  const appName = import.meta.env.VITE_APP_NAME || 'RankWiz';
  // app_url is always provided as a non-nullable string by HandleInertiaRequests middleware
  const canonicalUrl = `${app_url.replace(/\/$/, '')}/roadmap`;

  const votedSet = new Set(voted_ids);

  function handleVote(id: number) {
    router.post(
      route('roadmap.vote', { featureRequest: id }),
      {},
      {
        preserveScroll: true,
        onSuccess: () => {
          trackEvent(ROADMAP_VOTE_CAST, { feature_request_id: id });
        },
      },
    );
  }

  return (
    <>
      <Head title="Product Roadmap">
        <link rel="canonical" href={canonicalUrl} />
        <meta property="og:title" content={`Product Roadmap — ${appName}`} />
        <meta property="og:url" content={canonicalUrl} />
        <meta
          property="og:description"
          content={`See what ${appName} is building, what's coming next, and what's in the pipeline.`}
        />
        <meta name="twitter:card" content="summary" />
        <meta name="twitter:title" content={`Product Roadmap — ${appName}`} />
      </Head>
      <MarketingNav canLogin={can_login} canRegister={can_register} />

      <main className="mx-auto max-w-6xl px-4 py-16 sm:px-6 lg:px-8">
        <div className="mb-12 text-center">
          <h1 className="text-foreground text-4xl font-bold tracking-tight">Product Roadmap</h1>
          <p className="text-muted-foreground mt-4 text-lg">
            See what we&apos;re building, what&apos;s coming next, and what&apos;s in the pipeline.
          </p>
          <p className="text-muted-foreground mt-2 text-sm">
            Want to suggest a feature?{' '}
            {isAuthenticated ? (
              <Link
                href={route('feature-requests.index')}
                className="text-primary underline-offset-4 hover:underline"
              >
                Submit or vote on ideas
              </Link>
            ) : (
              <Link
                href={route('register')}
                className="text-primary underline-offset-4 hover:underline"
              >
                Sign up to submit ideas
              </Link>
            )}
          </p>
          {!isAuthenticated && (
            <p className="text-muted-foreground mt-1 text-xs">
              <Link
                href={route('login')}
                className="text-primary underline-offset-4 hover:underline"
              >
                Sign in
              </Link>{' '}
              to vote on items below.
            </p>
          )}
        </div>

        <div className="grid grid-cols-1 gap-8 md:grid-cols-3">
          <RoadmapColumn
            title={STATUS_CONFIG.building.label}
            description={STATUS_CONFIG.building.description}
            items={building}
            status="building"
            votedSet={votedSet}
            canVote={isAuthenticated}
            onVote={handleVote}
          />
          <RoadmapColumn
            title={STATUS_CONFIG.in_progress.label}
            description={STATUS_CONFIG.in_progress.description}
            items={in_progress}
            status="in_progress"
            votedSet={votedSet}
            canVote={isAuthenticated}
            onVote={handleVote}
          />
          <RoadmapColumn
            title={STATUS_CONFIG.planned.label}
            description={STATUS_CONFIG.planned.description}
            items={planned}
            status="planned"
            votedSet={votedSet}
            canVote={isAuthenticated}
            onVote={handleVote}
          />
        </div>
      </main>

      <MarketingFooter />
    </>
  );
}
