'use client';

import { useState, useEffect, useMemo } from 'react';
import {
  X,
  Star,
  ExternalLink,
  Calendar,
  User,
  MapPin,
  Loader2,
  AlertCircle,
} from 'lucide-react';
import type { FullReview, ReviewSpan } from '../types';
import {
  VALENCE_COLORS,
  VALENCE_LABELS,
  INTENSITY_LABELS,
  DOMAIN_LABELS,
  DOMAIN_COLORS,
} from '../types';

interface ReviewModalProps {
  reviewId: string | null;
  source?: string;
  highlightSpanId?: string | null;
  onClose: () => void;
}

/**
 * Modal showing a full review with classified spans highlighted.
 * Enables drill-down from any aggregate metric to the raw source data.
 */
export function ReviewModal({
  reviewId,
  source = 'google',
  highlightSpanId,
  onClose,
}: ReviewModalProps) {
  const [review, setReview] = useState<FullReview | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch review when reviewId changes
  useEffect(() => {
    if (!reviewId) {
      setReview(null);
      return;
    }

    const fetchReview = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await fetch(
          `/api/pipelines/reviewiq/reviews/${encodeURIComponent(reviewId)}?source=${encodeURIComponent(source)}`
        );

        if (!response.ok) {
          throw new Error(`Failed to fetch review: ${response.statusText}`);
        }

        const data = await response.json();
        setReview(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to fetch review');
      } finally {
        setLoading(false);
      }
    };

    fetchReview();
  }, [reviewId, source]);

  // Build highlighted text with spans marked using text-based matching
  // (offsets in DB are unreliable, so we find spans by searching for their text)
  const highlightedText = useMemo(() => {
    if (!review?.review_text || !review.spans.length) {
      return review?.review_text || '';
    }

    const text = review.review_text;

    // Find all span positions using text search
    const spanPositions: Array<{
      start: number;
      end: number;
      span: ReviewSpan;
    }> = [];

    for (const span of review.spans) {
      if (!span.span_text) continue;

      // Try exact match first
      let idx = text.indexOf(span.span_text);

      // If not found, try case-insensitive
      if (idx === -1) {
        idx = text.toLowerCase().indexOf(span.span_text.toLowerCase());
      }

      if (idx !== -1) {
        spanPositions.push({
          start: idx,
          end: idx + span.span_text.length,
          span,
        });
      }
    }

    if (spanPositions.length === 0) {
      // No matches found, return plain text
      return review.review_text;
    }

    // Sort by position and remove overlaps (keep first occurrence)
    spanPositions.sort((a, b) => a.start - b.start);
    const nonOverlapping: typeof spanPositions = [];
    let lastEnd = 0;

    for (const pos of spanPositions) {
      if (pos.start >= lastEnd) {
        nonOverlapping.push(pos);
        lastEnd = pos.end;
      }
    }

    // Build segments
    const segments: Array<{ text: string; span: ReviewSpan | null }> = [];
    let currentPos = 0;

    for (const pos of nonOverlapping) {
      // Add text before this span
      if (pos.start > currentPos) {
        segments.push({ text: text.slice(currentPos, pos.start), span: null });
      }

      // Add the span (use actual text from review, not span_text, to preserve case)
      segments.push({ text: text.slice(pos.start, pos.end), span: pos.span });
      currentPos = pos.end;
    }

    // Add remaining text
    if (currentPos < text.length) {
      segments.push({ text: text.slice(currentPos), span: null });
    }

    return segments;
  }, [review]);

  if (!reviewId) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b-2 border-gray-200">
          <h2 className="text-xl font-bold text-gray-900">Full Review</h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <X className="w-5 h-5 text-gray-600" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
            </div>
          ) : error ? (
            <div className="flex flex-col items-center justify-center h-64 text-red-600">
              <AlertCircle className="w-12 h-12 mb-4" />
              <p className="font-semibold">{error}</p>
            </div>
          ) : review ? (
            <div className="space-y-6">
              {/* Review Metadata */}
              <div className="flex items-start justify-between">
                <div className="space-y-2">
                  {/* Author */}
                  {review.author_name && (
                    <div className="flex items-center gap-2 text-gray-700">
                      <User className="w-4 h-4" />
                      <span className="font-semibold">{review.author_name}</span>
                    </div>
                  )}
                  {/* Business */}
                  {review.business_name && (
                    <div className="flex items-center gap-2 text-gray-600 text-sm">
                      <MapPin className="w-4 h-4" />
                      <span>{review.business_name}</span>
                    </div>
                  )}
                  {/* Date */}
                  {review.review_time && (
                    <div className="flex items-center gap-2 text-gray-500 text-sm">
                      <Calendar className="w-4 h-4" />
                      <span>{new Date(review.review_time).toLocaleDateString()}</span>
                    </div>
                  )}
                </div>

                {/* Rating */}
                {review.rating !== null && (
                  <div className="flex items-center gap-1">
                    {Array.from({ length: 5 }).map((_, i) => (
                      <Star
                        key={i}
                        className={`w-5 h-5 ${
                          i < review.rating!
                            ? 'text-yellow-400 fill-yellow-400'
                            : 'text-gray-300'
                        }`}
                      />
                    ))}
                  </div>
                )}
              </div>

              {/* Review Text with Highlighted Spans */}
              <div className="bg-gray-50 rounded-lg p-4 border-2 border-gray-200">
                <p className="text-gray-800 leading-relaxed whitespace-pre-wrap">
                  {Array.isArray(highlightedText) ? (
                    highlightedText.map((segment, idx) =>
                      segment.span ? (
                        <span
                          key={idx}
                          className={`relative inline px-1 py-0.5 rounded ${
                            highlightSpanId === segment.span.span_id
                              ? 'ring-2 ring-blue-500 ring-offset-1'
                              : ''
                          }`}
                          style={{
                            backgroundColor: segment.span.valence
                              ? `${VALENCE_COLORS[segment.span.valence]}30`
                              : '#e5e7eb',
                            borderBottom: segment.span.urt_primary
                              ? `3px solid ${DOMAIN_COLORS[segment.span.urt_primary[0]] || '#6b7280'}`
                              : 'none',
                          }}
                          title={`${segment.span.urt_primary || 'Unknown'} | ${
                            VALENCE_LABELS[segment.span.valence || ''] || 'N/A'
                          } | ${INTENSITY_LABELS[segment.span.intensity || ''] || 'N/A'}`}
                        >
                          {segment.text}
                        </span>
                      ) : (
                        <span key={idx}>{segment.text}</span>
                      )
                    )
                  ) : (
                    highlightedText
                  )}
                </p>
              </div>

              {/* Legend */}
              <div className="flex flex-wrap gap-4 text-xs">
                <div className="flex items-center gap-1">
                  <span
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: `${VALENCE_COLORS['V+']}30` }}
                  />
                  <span>Positive</span>
                </div>
                <div className="flex items-center gap-1">
                  <span
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: `${VALENCE_COLORS['V0']}30` }}
                  />
                  <span>Neutral</span>
                </div>
                <div className="flex items-center gap-1">
                  <span
                    className="w-4 h-4 rounded"
                    style={{ backgroundColor: `${VALENCE_COLORS['V-']}30` }}
                  />
                  <span>Negative</span>
                </div>
                <span className="text-gray-400">|</span>
                <span className="text-gray-600">Underline = URT Domain</span>
              </div>

              {/* Classified Spans List */}
              <div>
                <h3 className="text-lg font-bold text-gray-900 mb-3">
                  Classified Spans ({review.spans.length})
                </h3>
                <div className="space-y-2">
                  {review.spans.map((span) => (
                    <div
                      key={span.span_id}
                      className={`p-3 rounded-lg border-2 transition-all ${
                        highlightSpanId === span.span_id
                          ? 'border-blue-500 bg-blue-50'
                          : 'border-gray-200 bg-white hover:border-gray-300'
                      }`}
                    >
                      <div className="flex items-start justify-between gap-4">
                        <p className="text-sm text-gray-700 flex-1 italic">
                          &ldquo;{span.span_text}&rdquo;
                        </p>
                        <div className="flex items-center gap-2 flex-shrink-0">
                          {/* URT Code */}
                          {span.urt_primary && (
                            <span
                              className="px-2 py-1 text-xs font-mono font-bold rounded"
                              style={{
                                backgroundColor: `${DOMAIN_COLORS[span.urt_primary[0]] || '#6b7280'}20`,
                                color: DOMAIN_COLORS[span.urt_primary[0]] || '#6b7280',
                              }}
                            >
                              {span.urt_primary}
                            </span>
                          )}
                          {/* Valence */}
                          {span.valence && (
                            <span
                              className="px-2 py-1 text-xs font-bold rounded"
                              style={{
                                backgroundColor: `${VALENCE_COLORS[span.valence]}20`,
                                color: VALENCE_COLORS[span.valence],
                              }}
                            >
                              {VALENCE_LABELS[span.valence]}
                            </span>
                          )}
                          {/* Intensity */}
                          {span.intensity && (
                            <span className="px-2 py-1 text-xs font-medium bg-gray-100 text-gray-700 rounded">
                              {INTENSITY_LABELS[span.intensity]}
                            </span>
                          )}
                        </div>
                      </div>
                      {/* Domain label */}
                      {span.urt_primary && (
                        <div className="mt-2 text-xs text-gray-500">
                          {DOMAIN_LABELS[span.urt_primary[0]]} Domain
                          {span.entity && ` · Entity: ${span.entity}`}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              {/* External Link */}
              {review.review_url && (
                <div className="pt-4 border-t-2 border-gray-200">
                  <a
                    href={review.review_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-colors"
                  >
                    <ExternalLink className="w-4 h-4" />
                    View on Google Maps
                  </a>
                </div>
              )}
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}
