import { useState } from 'react'
import { ChevronRight, Search } from 'lucide-react'
import { Button, Card } from '../common'
import { t, tf, isRtl } from '../../lib/i18n'
import type { SprintArticle, SprintResult } from '../../types'
import type { GenerationConfig } from './SelectPostTypeStep'

interface ArticleReviewStepProps {
  articles: SprintArticle[]
  sprintResult: SprintResult
  config: GenerationConfig
  onApprove: (approvedArticles: SprintArticle[]) => void
  onBack: () => void
  onRequestMore: () => void
}

const confidenceStyles: Record<string, string> = {
  high: 'text-green-700 bg-green-50 border-green-200',
  medium: 'text-yellow-700 bg-yellow-50 border-yellow-200',
  low: 'text-red-700 bg-red-50 border-red-200',
}

const confidenceLabels: Record<string, string> = {
  high: 'High confidence',
  medium: 'Medium confidence',
  low: 'Low confidence',
}

export function ArticleReviewStep({
  articles,
  sprintResult,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  config: _,
  onApprove,
  onBack,
  onRequestMore,
}: ArticleReviewStepProps) {
  const [selectedArticles, setSelectedArticles] = useState<Set<number>>(
    () => new Set(articles.map((_, i) => i)),
  )

  const toggleArticle = (index: number) => {
    setSelectedArticles((prev) => {
      const next = new Set(prev)
      if (next.has(index)) {
        next.delete(index)
      } else {
        next.add(index)
      }
      return next
    })
  }

  const toggleAll = () => {
    if (selectedArticles.size === articles.length) {
      setSelectedArticles(new Set())
    } else {
      setSelectedArticles(new Set(articles.map((_, i) => i)))
    }
  }

  const handleApprove = () => {
    const approved = articles.filter((_, i) => selectedArticles.has(i))
    onApprove(approved)
  }

  return (
    <div className="max-w-4xl mx-auto">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-bc-gray-800 mb-2">
          {tf('Proposed Articles (%d)', articles.length)}
        </h2>
        <p className="text-bc-gray-500">
          {t('Review the articles found by the research sprint. Select the ones you want to generate.')}
        </p>
      </div>

      {/* Sprint summary */}
      <Card className="mb-6">
        <h4 className="font-medium text-bc-gray-800 mb-3">{t('Research Summary')}</h4>
        <div className="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
          <div>
            <span className="text-bc-gray-500">{t('Rounds')}</span>
            <div className="font-medium text-bc-gray-800">{sprintResult.rounds}</div>
          </div>
          <div>
            <span className="text-bc-gray-500">{t('Findings')}</span>
            <div className="font-medium text-bc-gray-800">{sprintResult.findings}</div>
          </div>
          <div>
            <span className="text-bc-gray-500">{t('Articles')}</span>
            <div className="font-medium text-bc-gray-800">{sprintResult.articleCount || articles.length}</div>
          </div>
          <div>
            <span className="text-bc-gray-500">{t('Cost')}</span>
            <div className="font-medium text-bc-gray-800">{sprintResult.costUsd.toFixed(3)}$</div>
          </div>
        </div>
      </Card>

      {/* Selection controls */}
      <div className="mb-4 flex items-center justify-between">
        <button
          type="button"
          onClick={toggleAll}
          className="text-sm font-medium text-bc-primary hover:text-bc-primary-dark transition-colors cursor-pointer bg-transparent border-none"
        >
          {selectedArticles.size === articles.length ? t('Deselect all') : t('Select all')}
        </button>
        <span className="text-sm text-bc-gray-500">
          {tf('%d of %d selected', selectedArticles.size, articles.length)}
        </span>
      </div>

      {/* Article cards */}
      <div className="space-y-3 mb-8">
        {articles.map((article, i) => {
          const isSelected = selectedArticles.has(i)
          return (
            <div
              key={i}
              role="button"
              tabIndex={0}
              className={`rounded-bc border p-4 cursor-pointer transition-colors ${
                isSelected
                  ? 'border-bc-primary bg-bc-primary-light/30'
                  : 'border-bc-gray-200 bg-white opacity-60'
              }`}
              onClick={() => toggleArticle(i)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault()
                  toggleArticle(i)
                }
              }}
            >
              <div className="flex items-start gap-3">
                <input
                  type="checkbox"
                  checked={isSelected}
                  onChange={() => toggleArticle(i)}
                  className="mt-1 shrink-0"
                  onClick={(e) => e.stopPropagation()}
                />

                <div className="flex-1 min-w-0">
                  <h4 className="font-medium text-bc-gray-800">{article.angle}</h4>

                  {article.hook && (
                    <p className="text-sm text-bc-gray-500 mt-1">{article.hook}</p>
                  )}

                  <div className="flex flex-wrap items-center gap-3 mt-2">
                    <span
                      className={`text-xs px-2 py-0.5 rounded-full border ${
                        confidenceStyles[article.confidence] || confidenceStyles.medium
                      }`}
                    >
                      {t(confidenceLabels[article.confidence] || 'Medium confidence')}
                    </span>

                    {article.backingFindings && article.backingFindings.length > 0 && (
                      <span className="text-xs text-bc-gray-400">
                        {tf('%d backing findings', article.backingFindings.length)}
                      </span>
                    )}

                    {article.branchName && (
                      <span className="text-xs text-bc-gray-400">
                        {article.branchName}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )
        })}
      </div>

      {articles.length === 0 && (
        <Card className="text-center py-12 mb-8">
          <p className="text-bc-gray-500">{t('No articles were proposed by the research sprint.')}</p>
          <Button variant="secondary" onClick={onRequestMore} className="mt-4" icon={<Search className="w-4 h-4" />}>
            {t('Research more')}
          </Button>
        </Card>
      )}

      {/* Actions */}
      <div className="flex flex-wrap justify-between gap-3 items-center">
        <Button
          variant="ghost"
          onClick={onBack}
          icon={<ChevronRight className="w-5 h-5 ltr:rotate-180" />}
          iconPosition={isRtl() ? 'end' : 'start'}
        >
          {t('Back')}
        </Button>

        <div className="flex flex-wrap gap-2">
          <Button variant="ghost" onClick={onRequestMore} icon={<Search className="w-4 h-4" />}>
            {t('Research more')}
          </Button>
          <Button
            onClick={handleApprove}
            disabled={selectedArticles.size === 0}
            size="lg"
          >
            {tf('Generate %d articles', selectedArticles.size)}
          </Button>
        </div>
      </div>
    </div>
  )
}
