/**
 * ContentInventoryRow — F5ARCH-007
 *
 * Renders a single post row (collapsed + expanded) for the ContentInventory table.
 * Extracted from ContentInventory.tsx to reduce the page component below 300 LOC.
 *
 * Presentational component: no state, no side effects.
 * All interactions are passed as callbacks from the parent page.
 */
import { BarChart2, ChevronDown, ExternalLink, FileText, Sparkles, TrendingUp } from 'lucide-react';

import { Fragment } from 'react';

import QualityScoresCard from '@/Components/Content/QualityScoresCard';
import { Button } from '@/Components/ui/button';
import { Checkbox } from '@/Components/ui/checkbox';
import { TableCell, TableRow } from '@/Components/ui/table';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/Components/ui/tooltip';
import { formatDateOnly, formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';

export interface WpPostRow {
  id: string;
  wp_post_id: number;
  title: string;
  url: string;
  post_type: string;
  post_status: string;
  wp_modified_at: string | null;
  word_count: number | null;
  flesch_kincaid_grade: number | null;
  avg_sentence_length: number | null;
  paragraph_count: number | null;
  passive_voice_percentage: number | null;
  h1_count: number | null;
  h2_count: number | null;
  h3_count: number | null;
  h4_count: number | null;
  h5_count: number | null;
  h6_count: number | null;
  image_count: number | null;
  internal_link_count: number | null;
  external_link_count: number | null;
  click_loss: number | null;
  recent_clicks: number | null;
  prior_clicks: number | null;
  /**
   * R6UXS-011: ROI lift indicator — clicks_delta from RecommendationRoiSnapshot
   * for the most recent applied recommendation on this post.
   * Null when no recommendation has been applied and tracked for this post.
   * Positive = clicks gained; negative = decline detected after rewrite.
   */
  roi_lift?: number | null;
}

const POST_TYPE_LABELS: Record<string, string> = {
  post: 'Post',
  page: 'Page',
  attachment: 'Attachment',
  revision: 'Revision',
  'nav_menu_item': 'Menu Item',
};

const POST_STATUS_LABELS: Record<string, string> = {
  publish: 'Published',
  draft: 'Draft',
  pending: 'Pending',
  private: 'Private',
  trash: 'Trash',
  future: 'Scheduled',
  auto_draft: 'Auto Draft',
};

function humanLabel(value: string, map: Record<string, string>): string {
  return map[value] ?? (value.charAt(0).toUpperCase() + value.slice(1));
}

function statusPillClass(status: string): string {
  switch (status) {
    case 'publish':
      return 'rounded-full bg-success/15 px-2 py-1 text-xs text-success-strong';
    case 'draft':
    case 'auto_draft':
      return 'rounded-full bg-muted px-2 py-1 text-xs text-muted-foreground';
    case 'pending':
      return 'rounded-full bg-warning/15 px-2 py-1 text-xs text-warning-strong';
    case 'private':
    case 'trash':
      return 'rounded-full bg-destructive/10 px-2 py-1 text-xs text-destructive-strong';
    default:
      return 'rounded-full bg-muted px-2 py-1 text-xs';
  }
}

interface Props {
  post: WpPostRow;
  siteId: string;
  briefsHref: string;
  snapshotsHref: string;
  /** R8PROD-003: deep-link to the annotated page timeline for this post's URL. */
  timelineHref: string;
  isExpanded: boolean;
  isSelected: boolean;
  colSpan: number;
  onToggleExpand: (postId: string) => void;
  onToggleSelect: (postId: string) => void;
  onRewrite: (postId: string) => void;
  truncateUrl: (url: string, maxLength: number) => string;
}

export function ContentInventoryRow({
  post,
  briefsHref,
  snapshotsHref,
  timelineHref,
  isExpanded,
  isSelected,
  colSpan,
  onToggleExpand,
  onToggleSelect,
  onRewrite,
  truncateUrl,
}: Props) {
  return (
    <Fragment>
      <TableRow className={cn('group', isExpanded ? '' : 'border-b last:border-0', isSelected && 'bg-muted/40')}>
        <TableCell className="w-10 px-4">
          <Checkbox checked={isSelected} onCheckedChange={() => onToggleSelect(post.id)} aria-label={`Select ${post.title}`} />
        </TableCell>
        <TableCell>
          <div className="flex flex-col gap-1 min-w-0">
            <div className="flex items-center gap-2 min-w-0">
              <a href={snapshotsHref} className="block max-w-[28rem] truncate text-left font-medium hover:underline" title={post.title}>
                {post.title}
              </a>
              {/* R6UXS-011: ROI lift indicator — shown once a rewrite has been tracked */}
              {post.roi_lift != null && (
                <span
                  className={cn(
                    'inline-flex shrink-0 items-center gap-0.5 rounded-full px-1.5 py-0.5 text-[10px] font-semibold',
                    post.roi_lift > 0
                      ? 'bg-success/15 text-success-strong'
                      : 'bg-muted text-muted-foreground',
                  )}
                  title={`${post.roi_lift > 0 ? '+' : ''}${formatNumber(post.roi_lift)} clicks after rewrite`}
                >
                  <TrendingUp className="h-2.5 w-2.5" aria-hidden="true" />
                  {post.roi_lift > 0 ? `+${formatNumber(post.roi_lift)}` : formatNumber(post.roi_lift)}
                </span>
              )}
            </div>
            <a href={post.url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-primary hover:underline" title={post.url}>
              <span className="block max-w-[24rem] truncate">{truncateUrl(post.url, 50)}</span>
              <ExternalLink className="size-3 shrink-0" />
            </a>
          </div>
        </TableCell>
        <TableCell className="tabular-nums">
          {post.click_loss === null ? (
            <span className="text-muted-foreground">—</span>
          ) : post.click_loss > 0 ? (
            <span className="font-medium text-destructive-strong" title={`${formatNumber(post.prior_clicks ?? 0)} → ${formatNumber(post.recent_clicks ?? 0)} clicks`}>
              −{formatNumber(post.click_loss)}
            </span>
          ) : (
            <span className="text-muted-foreground" title={`${formatNumber(post.prior_clicks ?? 0)} → ${formatNumber(post.recent_clicks ?? 0)} clicks`}>
              {post.click_loss < 0 ? `+${formatNumber(Math.abs(post.click_loss))}` : '0'}
            </span>
          )}
        </TableCell>
        <TableCell className="tabular-nums">{post.wp_modified_at ? formatDateOnly(post.wp_modified_at) : 'N/A'}</TableCell>
        <TableCell className="hidden lg:table-cell tabular-nums">{post.word_count != null ? formatNumber(post.word_count) : 'N/A'}</TableCell>
        <TableCell className="hidden lg:table-cell tabular-nums">{post.flesch_kincaid_grade !== null ? `Grade ${post.flesch_kincaid_grade.toFixed(1)}` : 'N/A'}</TableCell>
        <TableCell className="hidden md:table-cell">
          <span className="rounded-full bg-muted px-2 py-1 text-xs">{humanLabel(post.post_type, POST_TYPE_LABELS)}</span>
        </TableCell>
        <TableCell className="hidden md:table-cell">
          <span className={statusPillClass(post.post_status)}>{humanLabel(post.post_status, POST_STATUS_LABELS)}</span>
        </TableCell>
        <TableCell className="text-right">
          <div className="flex items-center justify-end gap-1">
            <Button variant="default" size="sm" onClick={() => onRewrite(post.id)}>
              <Sparkles className="mr-1 size-3" />Rewrite
            </Button>
            <Button variant="outline" size="sm" asChild>
              <a href={briefsHref}><FileText className="mr-1 size-3" />Brief</a>
            </Button>
            {/* R8PROD-003: Timeline icon CTA — links to annotated GSC chart for this page */}
            <TooltipProvider delayDuration={300}>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button variant="ghost" size="sm" asChild>
                    <a href={timelineHref} aria-label="View metric timeline">
                      <BarChart2 className="size-3" />
                    </a>
                  </Button>
                </TooltipTrigger>
                <TooltipContent>View metric timeline</TooltipContent>
              </Tooltip>
            </TooltipProvider>
            <Button variant="ghost" size="sm" onClick={() => onToggleExpand(post.id)} aria-expanded={isExpanded} aria-controls={`post-details-${post.id}`} aria-label={isExpanded ? `Hide details for ${post.title}` : `View details for ${post.title}`}>
              {isExpanded ? 'Hide' : 'Details'}
              <ChevronDown className={cn('ml-1 size-4 transition-transform duration-200', isExpanded && 'rotate-180')} />
            </Button>
          </div>
        </TableCell>
      </TableRow>

      {isExpanded && (
        <TableRow key={`${post.id}-expanded`} className="border-b bg-muted/30 hover:bg-muted/30">
          <TableCell colSpan={colSpan} id={`post-details-${post.id}`} className="p-6">
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4 rounded-lg border bg-background p-4 sm:grid-cols-4">
                <div><p className="text-xs text-muted-foreground mb-1">Type</p><p className="font-medium">{humanLabel(post.post_type, POST_TYPE_LABELS)}</p></div>
                <div><p className="text-xs text-muted-foreground mb-1">Status</p><p className="font-medium">{humanLabel(post.post_status, POST_STATUS_LABELS)}</p></div>
                <div><p className="text-xs text-muted-foreground mb-1">Modified</p><p className="font-medium">{post.wp_modified_at ? formatDateOnly(post.wp_modified_at) : 'N/A'}</p></div>
                <div><p className="text-xs text-muted-foreground mb-1">WP Post ID</p><p className="font-medium tabular-nums">{post.wp_post_id}</p></div>
              </div>
              <QualityScoresCard scores={{
                flesch_kincaid_grade: post.flesch_kincaid_grade,
                avg_sentence_length: post.avg_sentence_length,
                paragraph_count: post.paragraph_count,
                passive_voice_percentage: post.passive_voice_percentage,
                word_count: post.word_count,
                h1_count: post.h1_count, h2_count: post.h2_count, h3_count: post.h3_count,
                h4_count: post.h4_count, h5_count: post.h5_count, h6_count: post.h6_count,
                image_count: post.image_count,
                internal_link_count: post.internal_link_count,
                external_link_count: post.external_link_count,
              }} />
              <div className="flex justify-end gap-2">
                <Button variant="default" size="sm" onClick={() => onRewrite(post.id)}>
                  <Sparkles className="mr-1 size-3.5" />Rewrite
                </Button>
                <Button variant="outline" size="sm" asChild>
                  <a href={briefsHref}><FileText className="mr-1 size-3.5" />Brief</a>
                </Button>
                {/* R8PROD-003: Timeline deep-link in expanded drawer */}
                <Button variant="outline" size="sm" asChild>
                  <a href={timelineHref}>
                    <BarChart2 className="mr-1 size-3.5" />View timeline
                  </a>
                </Button>
                <a href={post.url} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-sm text-primary hover:underline">
                  View Page<ExternalLink className="size-3" />
                </a>
              </div>
            </div>
          </TableCell>
        </TableRow>
      )}
    </Fragment>
  );
}
