import {
  BarChart2,
  BookOpen,
  CheckCircle2,
  Clock,
  ExternalLink,
  Eye,
  FileText,
  Layers,
  Lightbulb,
  PencilLine,
  TrendingUp,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';

import { useEffect } from 'react';

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

import PageHeader from '@/Components/layout/PageHeader';
import SiteNav from '@/Components/Navigation/SiteNav';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { EmptyState } from '@/Components/ui/empty-state';
import { ScrollArea } from '@/Components/ui/scroll-area';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { FEATURE_USED, PIPELINE_CARD_CLICKED, PIPELINE_VIEWED } from '@/lib/event-catalog';
import { formatRelativeTime } from '@/lib/format';
import { cn } from '@/lib/utils';
import type { SiteBasic } from '@/types';

// ─── Types ────────────────────────────────────────────────────────────────────

type Stage = 'opportunity' | 'brief' | 'draft' | 'editing' | 'review' | 'published' | 'tracking';

type CardType =
  | 'keyword_opportunity'
  | 'cannibalization_case'
  | 'freshness_recommendation'
  | 'content_brief'
  | 'ai_draft'
  | 'wp_publish_log'
  | 'roi_snapshot';

interface PipelineCard {
  id: string;
  type: CardType;
  stage: Stage;
  title: string;
  page_url: string | null;
  created_at: string | null;
  days_in_stage: number;
  action_label: string;
  action_url: string;
}

interface Stages {
  opportunity: PipelineCard[];
  brief: PipelineCard[];
  draft: PipelineCard[];
  editing: PipelineCard[];
  review: PipelineCard[];
  published: PipelineCard[];
  tracking: PipelineCard[];
}

interface Counts {
  opportunity: number;
  brief: number;
  draft: number;
  editing: number;
  review: number;
  published: number;
  tracking: number;
}

interface Props {
  site: SiteBasic;
  stages: Stages;
  counts: Counts;
}

// ─── Stage config ─────────────────────────────────────────────────────────────

interface StageConfig {
  key: Stage;
  label: string;
  description: string;
  icon: LucideIcon;
  colorClass: string;
}

const STAGE_CONFIG: StageConfig[] = [
  {
    key: 'opportunity',
    label: 'Opportunity',
    description: 'Keyword gaps, cannibalization issues, freshness signals',
    icon: Lightbulb,
    colorClass: 'text-amber-500 dark:text-amber-400',
  },
  {
    key: 'brief',
    label: 'Brief',
    description: 'Content briefs ready to develop',
    icon: FileText,
    colorClass: 'text-blue-500 dark:text-blue-400',
  },
  {
    key: 'draft',
    label: 'Draft',
    description: 'AI drafts currently generating',
    icon: BookOpen,
    colorClass: 'text-violet-500 dark:text-violet-400',
  },
  {
    key: 'editing',
    label: 'Editing',
    description: 'Completed drafts awaiting review',
    icon: PencilLine,
    colorClass: 'text-indigo-500 dark:text-indigo-400',
  },
  {
    key: 'review',
    label: 'Review',
    description: 'Content queued for WordPress publish',
    icon: Eye,
    colorClass: 'text-orange-500 dark:text-orange-400',
  },
  {
    key: 'published',
    label: 'Published',
    description: 'Successfully published to WordPress',
    icon: CheckCircle2,
    colorClass: 'text-green-500 dark:text-green-400',
  },
  {
    key: 'tracking',
    label: 'Tracking',
    description: 'Measuring impact on search performance',
    icon: TrendingUp,
    colorClass: 'text-emerald-600 dark:text-emerald-400',
  },
];

// ─── Card type label ──────────────────────────────────────────────────────────

const TYPE_LABELS: Record<CardType, string> = {
  keyword_opportunity: 'Keyword',
  cannibalization_case: 'Cannibalization',
  freshness_recommendation: 'Freshness',
  content_brief: 'Brief',
  ai_draft: 'Draft',
  wp_publish_log: 'Publish',
  roi_snapshot: 'ROI',
};

// ─── Components ───────────────────────────────────────────────────────────────

function StageSummaryBar({ counts }: { counts: Counts }) {
  const total = Object.values(counts).reduce((a, b) => a + b, 0);

  return (
    <div className="rounded-xl border bg-card px-5 py-4">
      <div className="mb-3 flex items-center gap-2">
        <Layers aria-hidden="true" className="h-4 w-4 text-muted-foreground" />
        <span className="text-sm font-medium text-muted-foreground">
          {total} item{total !== 1 ? 's' : ''} across all stages
        </span>
      </div>
      <div className="grid grid-cols-7 gap-2">
        {STAGE_CONFIG.map((stage) => {
          const count = counts[stage.key];
          const Icon = stage.icon;
          return (
            <div
              key={stage.key}
              className="flex flex-col items-center gap-1 rounded-lg bg-muted/40 px-2 py-2.5 text-center"
            >
              <Icon className={cn('h-4 w-4', stage.colorClass)} />
              <span className="text-xl font-bold leading-none">{count}</span>
              <span className="text-xs leading-tight text-muted-foreground">{stage.label}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DaysInStagePill({ days }: { days: number }) {
  const isNew = days === 0;
  const isStale = days > 14;

  return (
    <span
      className={cn(
        'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium',
        isNew && 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
        !isNew && !isStale && 'bg-muted text-muted-foreground',
        isStale && 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
      )}
    >
      <Clock aria-hidden="true" className="h-2.5 w-2.5" />
      {isNew ? 'Today' : `${days}d`}
    </span>
  );
}

function PipelineCardItem({ card, siteId }: { card: PipelineCard; siteId: number }) {
  const isExternalUrl =
    card.stage === 'published' &&
    card.action_url.startsWith('http') &&
    !card.action_url.includes(window.location.hostname);

  function handleActionClick() {
    trackProductEvent(PIPELINE_CARD_CLICKED, {
      card_type: card.type,
      stage: card.stage,
      site_id: siteId,
    });
  }

  return (
    <div className="group rounded-lg border bg-card p-3 shadow-sm transition-all duration-200 hover:shadow-md hover:border-primary/40">
      {/* Type badge + days in stage */}
      <div className="mb-2 flex items-center justify-between gap-2">
        <Badge variant="outline" className="px-1.5 py-0 text-xs font-medium">
          {TYPE_LABELS[card.type]}
        </Badge>
        <DaysInStagePill days={card.days_in_stage} />
      </div>

      {/* Title */}
      <p className="mb-1.5 line-clamp-2 text-sm font-medium leading-snug text-foreground">
        {card.title}
      </p>

      {/* Page URL */}
      {card.page_url && (
        <p className="mb-2.5 truncate text-xs text-muted-foreground" title={card.page_url}>
          {card.page_url.replace(/^https?:\/\/(www\.)?/, '')}
        </p>
      )}

      {/* Created at */}
      {card.created_at && (
        <p className="mb-2.5 text-xs text-muted-foreground/70">
          {formatRelativeTime(card.created_at)}
        </p>
      )}

      {/* CTA */}
      {isExternalUrl ? (
        <a
          href={card.action_url}
          target="_blank"
          rel="noopener noreferrer"
          onClick={handleActionClick}
          className="inline-flex w-full items-center justify-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
        >
          {card.action_label}
          <ExternalLink className="h-3 w-3" />
        </a>
      ) : (
        <Link
          href={card.action_url}
          onClick={handleActionClick}
          className="inline-flex w-full items-center justify-center rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
        >
          {card.action_label}
        </Link>
      )}
    </div>
  );
}

function KanbanColumn({
  config,
  cards,
  count,
  shortcutKey,
  siteId,
}: {
  config: StageConfig;
  cards: PipelineCard[];
  count: number;
  shortcutKey: number;
  siteId: number;
}) {
  const Icon = config.icon;
  const isEmpty = cards.length === 0;

  return (
    <div
      id={`pipeline-stage-${config.key}`}
      className="flex w-72 shrink-0 flex-col rounded-xl border bg-muted/30"
    >
      {/* Column header */}
      <div className="flex items-center gap-2.5 rounded-t-xl border-b bg-card/60 px-4 py-3">
        <Icon className={cn('h-4 w-4', config.colorClass)} />
        <span className="flex-1 text-sm font-semibold">{config.label}</span>
        <kbd className="rounded border border-border px-1 font-mono text-xs text-muted-foreground/40">
          {shortcutKey}
        </kbd>
        <span
          className={cn(
            'flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-xs font-bold',
            count > 0 ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground',
          )}
        >
          {count}
        </span>
      </div>

      {/* Cards */}
      <ScrollArea className="flex-1 max-h-[calc(100vh-340px)]">
        <div className="space-y-2 p-3">
          {isEmpty ? (
            <div className="flex flex-col items-center gap-1.5 py-8 text-center">
              <Icon className="h-6 w-6 text-muted-foreground/30" />
              <p className="text-xs text-muted-foreground/60">No items in this stage</p>
            </div>
          ) : (
            cards.map((card) => <PipelineCardItem key={card.id} card={card} siteId={siteId} />)
          )}
        </div>
      </ScrollArea>
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function PipelineIndex({ site, stages, counts }: Props) {
  const totalItems = Object.values(counts).reduce((a, b) => a + b, 0);
  const hasAnyItems = totalItems > 0;

  // Track page view on mount
  useEffect(() => {
    trackProductEvent(PIPELINE_VIEWED, { site_id: String(site.id), total_items: totalItems });
    trackProductEvent(FEATURE_USED, { feature: 'pipeline' });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Keys 1–7 scroll to the corresponding stage column
  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      const active = document.activeElement;
      if (
        active?.tagName === 'INPUT' ||
        active?.tagName === 'TEXTAREA' ||
        (active as HTMLElement)?.isContentEditable
      ) {
        return;
      }
      const index = parseInt(e.key, 10);
      if (index >= 1 && index <= STAGE_CONFIG.length) {
        document
          .getElementById(`pipeline-stage-${STAGE_CONFIG[index - 1].key}`)
          ?.scrollIntoView({ behavior: 'smooth', inline: 'start', block: 'nearest' });
      }
    }
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  return (
    <DashboardLayout>
      <Head title={`Content Pipeline — ${site.name}`} />

      <PageHeader
        title="Content Pipeline"
        subtitle="Track every piece of content from opportunity to live post and ROI"
        actions={
          <Button variant="outline" size="sm" asChild>
            <Link href={route('opportunity-map.index', site.id)}>
              <BarChart2 aria-hidden="true" className="mr-1.5 h-4 w-4" />
              Opportunity Map
            </Link>
          </Button>
        }
      />

      <div className="space-y-6">
        <SiteNav
          siteId={site.id}
          canAnalyze
          canRecommend
          canCannibalization
          canOpportunityMap
          canGeographic
          canDevice
        />

        {/* Summary bar */}
        <StageSummaryBar counts={counts} />

        {/* Kanban board */}
        {!hasAnyItems ? (
          <EmptyState
            title="No content in your pipeline yet"
            description="Start by running a keyword opportunity analysis or analyzing your site's traffic patterns."
            action={
              <Button asChild>
                <Link href={route('analyze.index', site.id)}>Start Analysis</Link>
              </Button>
            }
          />
        ) : (
          <div className="overflow-x-auto pb-4">
            <div className="flex gap-4 min-w-max">
              {STAGE_CONFIG.map((config, i) => (
                <KanbanColumn
                  key={config.key}
                  config={config}
                  cards={stages[config.key]}
                  count={counts[config.key]}
                  shortcutKey={i + 1}
                  siteId={site.id}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
