import { ChevronDown, Copy, ExternalLink } from 'lucide-react';
import { toast } from 'sonner';

import { Fragment, useState } from 'react';

import InertiaPagination from '@/Components/Shared/InertiaPagination';
import MetricDelta from '@/Components/Shared/MetricDelta';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent } from '@/Components/ui/card';
import { InfoTooltip } from '@/Components/ui/info-tooltip';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/Components/ui/tooltip';
import { copyToClipboard } from '@/lib/clipboard';
import { formatNumber, formatPercentRaw } from '@/lib/format';
import { copied } from '@/lib/messages';
import { cn } from '@/lib/utils';
import type { RecommendationWithRoi } from '@/types/roi';

interface PaginationLink {
  url: string | null;
  label: string;
  active: boolean;
}

interface RecommendationRoiTableProps {
  /** R8PROD-003: site public_id (or integer id) for building timeline deep-links. */
  siteId: number;
  recommendations: {
    data: RecommendationWithRoi[];
    links: PaginationLink[];
    current_page: number;
    last_page: number;
  };
}

function truncateUrl(url: string, maxLength: number): string {
  try {
    const parsed = new URL(url);
    const path = parsed.pathname + parsed.search;
    return path.length > maxLength ? path.slice(0, maxLength) + '...' : path;
  } catch {
    return url.length > maxLength ? url.slice(0, maxLength) + '...' : url;
  }
}

const ACTION_TYPE_LABELS: Record<string, string> = {
  content_rewrite: 'AI Draft',
};

function formatActionType(actionType: string | null): string {
  if (actionType === null) {
    return 'Unknown';
  }
  if (ACTION_TYPE_LABELS[actionType]) {
    return ACTION_TYPE_LABELS[actionType];
  }
  return actionType
    .split('_')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}

interface HeaderWithTooltipProps {
  label: string;
  tooltip?: string;
  className?: string;
}

function HeaderWithTooltip({ label, tooltip, className }: HeaderWithTooltipProps) {
  if (!tooltip) {
    return <span className={className}>{label}</span>;
  }

  return (
    <div className="flex items-center gap-1">
      <span className={className}>{label}</span>
      <InfoTooltip content={tooltip} iconClassName="size-3" />
    </div>
  );
}

export default function RecommendationRoiTable({ siteId, recommendations }: RecommendationRoiTableProps) {
  const [hoveredRow, setHoveredRow] = useState<number | null>(null);
  const [expandedRowId, setExpandedRowId] = useState<number | null>(null);
  const items = recommendations.data;

  const handleCopyUrl = (url: string) => {
    void copyToClipboard(url).then((ok) => {
      if (ok) toast.success(copied('URL'));
    });
  };

  const toggleRow = (recommendationId: number) => {
    setExpandedRowId(expandedRowId === recommendationId ? null : recommendationId);
  };

  if (items.length === 0) {
    return (
      <div className="rounded-lg border bg-card p-8">
        <p className="text-sm text-muted-foreground text-center">
          No ROI data available. Mark recommendations as "Applied" to start tracking their impact.
        </p>
      </div>
    );
  }

  return (
    <div>
      <div className="overflow-x-auto rounded-lg border">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b bg-muted/50">
              <th scope="col" className="text-left p-3 font-medium w-8 xl:hidden"></th>
              <th scope="col" className="text-left p-3 font-medium">Page</th>
              <th scope="col" className="text-left p-3 font-medium hidden lg:table-cell">Action Type</th>
              <th scope="col" className="text-right p-3 font-medium hidden xl:table-cell">
                <HeaderWithTooltip
                  label="Baseline Clicks"
                  tooltip="The number of clicks this page received before your change was applied"
                />
              </th>
              <th scope="col" className="text-right p-3 font-medium hidden xl:table-cell">
                <HeaderWithTooltip
                  label="Current Clicks"
                  tooltip="The number of clicks this page receives now (rolling 30-day average)"
                />
              </th>
              <th scope="col" className="text-right p-3 font-medium">
                <HeaderWithTooltip
                  label="Clicks Δ"
                  tooltip="The change in clicks since applying your recommendation (positive = improvement)"
                />
              </th>
              <th scope="col" className="text-right p-3 font-medium hidden md:table-cell">
                <HeaderWithTooltip
                  label="Baseline CTR"
                  tooltip="Click-through rate before the change"
                />
              </th>
              <th scope="col" className="text-right p-3 font-medium hidden md:table-cell">
                <HeaderWithTooltip
                  label="Current CTR"
                  tooltip="Click-through rate after the change"
                />
              </th>
              <th scope="col" className="text-right p-3 font-medium">
                <HeaderWithTooltip label="CTR Δ" tooltip="The change in click-through rate" />
              </th>
              <th scope="col" className="text-right p-3 font-medium hidden lg:table-cell">
                <HeaderWithTooltip
                  label="Position Δ"
                  tooltip="Average position change in search results"
                />
              </th>
              <th scope="col" className="text-center p-3 font-medium hidden sm:table-cell">
                <HeaderWithTooltip
                  label="Days Tracked"
                  tooltip="How long ROI tracking has been active"
                />
              </th>
              <th scope="col" className="text-center p-3 font-medium hidden md:table-cell">
                <HeaderWithTooltip
                  label="Significant"
                  tooltip="Statistical significance of the results"
                />
              </th>
            </tr>
          </thead>
          <tbody>
            {items.map((recommendation) => {
              const isExpanded = expandedRowId === recommendation.id;
              return (
                <Fragment key={recommendation.id}>
                  <tr
                    className={cn(
                      'hover:bg-muted/50 transition-colors',
                      isExpanded ? '' : 'border-b last:border-0',
                    )}
                    onMouseEnter={() => setHoveredRow(recommendation.id)}
                    onMouseLeave={() => setHoveredRow(null)}
                  >
                    <td className="p-3 xl:hidden">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="size-6 p-0"
                        onClick={() => toggleRow(recommendation.id)}
                        aria-label={isExpanded ? 'Collapse details' : 'Expand details'}
                      >
                        <ChevronDown
                          className={cn(
                            'size-4 transition-transform duration-200',
                            isExpanded && 'rotate-180',
                          )}
                        />
                      </Button>
                    </td>
                    <td className="p-3">
                      <div className="inline-flex items-center gap-2">
                        {/* R8PROD-003: page URL deep-links to annotated timeline ("prove it" click) */}
                        <a
                          href={`${route('timeline.page', siteId)}?url=${encodeURIComponent(recommendation.page_url)}&days=90`}
                          className="inline-flex items-center gap-1 text-primary hover:underline"
                          title={`View metric timeline for ${recommendation.page_url}`}
                        >
                          {truncateUrl(recommendation.page_url, 40)}
                        </a>
                        {/* Keep external link icon for opening the page in a new tab */}
                        <a
                          href={recommendation.page_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="shrink-0 text-muted-foreground hover:text-primary"
                          title={recommendation.page_url}
                          aria-label="Open page in new tab"
                        >
                          <ExternalLink className="size-3" />
                        </a>
                        {hoveredRow === recommendation.id && (
                          <TooltipProvider delayDuration={0}>
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="size-6 p-0"
                                  onClick={() => handleCopyUrl(recommendation.page_url)}
                                >
                                  <Copy className="size-3" />
                                </Button>
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>Copy URL</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        )}
                      </div>
                    </td>
                    <td className="p-3 hidden lg:table-cell">
                      <span className="text-xs text-muted-foreground">
                        {formatActionType(recommendation.action_type)}
                      </span>
                    </td>
                    <td className="text-right p-3 tabular-nums hidden xl:table-cell">
                      {formatNumber(Math.round(recommendation.baseline_clicks))}
                    </td>
                    <td className="text-right p-3 tabular-nums hidden xl:table-cell">
                      {formatNumber(Math.round(recommendation.current_clicks))}
                    </td>
                    <td className="text-right p-3">
                      <div className="flex flex-col items-end gap-1">
                        <MetricDelta value={recommendation.clicks_delta} format="number" />
                        <span className="text-xs text-muted-foreground">
                          ({formatPercentRaw(recommendation.clicks_delta_pct, 1)})
                        </span>
                      </div>
                    </td>
                    <td className="text-right p-3 tabular-nums hidden md:table-cell">
                      {formatPercentRaw(recommendation.baseline_ctr, 2)}
                    </td>
                    <td className="text-right p-3 tabular-nums hidden md:table-cell">
                      {formatPercentRaw(recommendation.current_ctr, 2)}
                    </td>
                    <td className="text-right p-3">
                      <div className="flex flex-col items-end gap-1">
                        <MetricDelta value={recommendation.ctr_delta} format="decimal" />
                        <span className="text-xs text-muted-foreground">
                          ({formatPercentRaw(recommendation.ctr_delta_pct, 1)})
                        </span>
                      </div>
                    </td>
                    <td className="text-right p-3 tabular-nums hidden lg:table-cell">
                      <MetricDelta value={recommendation.position_delta} format="decimal" />
                    </td>
                    <td className="text-center p-3 tabular-nums hidden sm:table-cell">
                      <span className="text-xs text-muted-foreground">
                        {recommendation.days_tracked}d
                      </span>
                    </td>
                    <td className="text-center p-3 hidden md:table-cell">
                      {recommendation.is_significant ? (
                        <Badge variant="default" className="text-xs">
                          Yes
                        </Badge>
                      ) : (
                        <Badge variant="secondary" className="text-xs">
                          No
                        </Badge>
                      )}
                    </td>
                  </tr>
                  {isExpanded && (
                    <tr className="border-b last:border-0">
                      <td colSpan={12} className="p-3 bg-muted/20">
                        <Card className="shadow-none">
                          <CardContent className="pt-4 pb-4 px-4">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
                              <div className="lg:hidden">
                                <div className="text-xs text-muted-foreground mb-1">
                                  Action Type
                                </div>
                                <div className="font-medium">
                                  {formatActionType(recommendation.action_type)}
                                </div>
                              </div>
                              <div className="xl:hidden">
                                <div className="text-xs text-muted-foreground mb-1">
                                  Baseline Clicks
                                </div>
                                <div className="font-medium tabular-nums">
                                  {formatNumber(Math.round(recommendation.baseline_clicks))}
                                </div>
                              </div>
                              <div className="xl:hidden">
                                <div className="text-xs text-muted-foreground mb-1">
                                  Current Clicks
                                </div>
                                <div className="font-medium tabular-nums">
                                  {formatNumber(Math.round(recommendation.current_clicks))}
                                </div>
                              </div>
                              <div className="md:hidden">
                                <div className="text-xs text-muted-foreground mb-1">
                                  Baseline CTR
                                </div>
                                <div className="font-medium tabular-nums">
                                  {formatPercentRaw(recommendation.baseline_ctr, 2)}
                                </div>
                              </div>
                              <div className="md:hidden">
                                <div className="text-xs text-muted-foreground mb-1">
                                  Current CTR
                                </div>
                                <div className="font-medium tabular-nums">
                                  {formatPercentRaw(recommendation.current_ctr, 2)}
                                </div>
                              </div>
                              <div className="lg:hidden">
                                <div className="text-xs text-muted-foreground mb-1">Position Δ</div>
                                <div className="font-medium tabular-nums">
                                  <MetricDelta
                                    value={recommendation.position_delta}
                                    format="decimal"
                                  />
                                </div>
                              </div>
                              <div className="sm:hidden">
                                <div className="text-xs text-muted-foreground mb-1">
                                  Days Tracked
                                </div>
                                <div className="font-medium tabular-nums">
                                  {recommendation.days_tracked}d
                                </div>
                              </div>
                              <div className="md:hidden">
                                <div className="text-xs text-muted-foreground mb-1">
                                  Significant
                                </div>
                                <div>
                                  {recommendation.is_significant ? (
                                    <Badge variant="default" className="text-xs">
                                      Yes
                                    </Badge>
                                  ) : (
                                    <Badge variant="secondary" className="text-xs">
                                      No
                                    </Badge>
                                  )}
                                </div>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      </td>
                    </tr>
                  )}
                </Fragment>
              );
            })}
          </tbody>
        </table>
      </div>

      <InertiaPagination
        links={recommendations.links}
        currentPage={recommendations.current_page}
        lastPage={recommendations.last_page}
      />
    </div>
  );
}
