import { ExternalLink } from 'lucide-react';

import { formatNumber } from '@/lib/format';

interface HeadingStructure {
  h1: number;
  h2: number;
  h3: number;
  h4: number;
  h5: number;
  h6: number;
}

interface SerpResult {
  position: number;
  domain: string;
  title: string;
  description: string;
  url: string;
  word_count: number;
  heading_structure: HeadingStructure;
}

interface Props {
  result: SerpResult;
}

export default function SerpResultRow({ result }: Props) {
  const headingCount = Object.values(result.heading_structure).reduce((a, b) => a + b, 0);

  return (
    <div className="border rounded-lg p-3 bg-card hover:bg-accent/50 transition-colors">
      {/* Position and Domain */}
      <div className="flex items-start justify-between gap-2 mb-2">
        <div className="flex items-center gap-2 flex-1 min-w-0">
          <span className="inline-flex items-center justify-center h-6 w-6 rounded bg-primary text-primary-foreground text-xs font-bold flex-shrink-0">
            {result.position}
          </span>
          <div className="min-w-0 flex-1">
            <p className="text-sm font-medium truncate text-foreground">{result.domain}</p>
            <p className="text-xs text-muted-foreground truncate">{result.url}</p>
          </div>
        </div>
        <a
          href={result.url}
          target="_blank"
          rel="noopener noreferrer"
          className="flex-shrink-0 text-muted-foreground hover:text-foreground transition-colors"
          title="Open result"
        >
          <ExternalLink className="h-4 w-4" />
        </a>
      </div>

      {/* Title */}
      <p className="text-sm font-semibold mb-2 line-clamp-2">{result.title}</p>

      {/* Description */}
      <p className="text-xs text-muted-foreground mb-3 line-clamp-2">{result.description}</p>

      {/* Metrics Footer */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-1 sm:gap-2 text-xs border-t pt-2">
        <div className="flex items-center gap-4">
          <div>
            <span className="text-muted-foreground">Words: </span>
            <span className="font-semibold">{formatNumber(result.word_count)}</span>
          </div>
          <div>
            <span className="text-muted-foreground">Headings: </span>
            <span className="font-semibold">{headingCount}</span>
          </div>
        </div>
        <div className="text-muted-foreground">
          H1:{result.heading_structure.h1} H2:{result.heading_structure.h2} H3:
          {result.heading_structure.h3}
        </div>
      </div>
    </div>
  );
}
