import React, { useState, useEffect, Fragment } from 'react';

import { fetchAgentJourneyDetail } from '../../service/agent-analytics/agent-analytics.service';
import type { IJourneyDetail } from '../../service/agent-analytics/agent-analytics.interface';

import { formatNumber, formatIntentScore } from './helpers';
import {
  getSentimentLabel,
  getSentimentBadgeTone,
} from './journeyDetailModal.utils';

interface JourneyDetailModalProps {
  fingerprint: string | null;
  onClose: () => void;
}

const BADGE_TONE_CLASSES: Record<string, string> = {
  success: 'bg-green-100 text-green-800',
  critical: 'bg-red-100 text-red-800',
  info: 'bg-blue-100 text-blue-800',
  attention: 'bg-yellow-100 text-yellow-800',
};

const JourneyDetailModal = ({
  fingerprint,
  onClose,
}: JourneyDetailModalProps): JSX.Element | null => {
  const [detail, setDetail] = useState<IJourneyDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!fingerprint) return;
    setLoading(true);
    setError(null);
    fetchAgentJourneyDetail(fingerprint)
      .then(d => {
        setDetail(d);
        setLoading(false);
      })
      .catch(e => {
        setError(e.message);
        setLoading(false);
      });
  }, [fingerprint]);

  if (!fingerprint) return null;

  return (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      {/* Modal */}
      <div className="relative bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto mx-4">
        {/* Header */}
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between rounded-t-xl z-10">
          <h2 className="text-lg font-semibold text-gray-900">
            Conversation Detail
          </h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 text-2xl leading-none"
          >
            &times;
          </button>
        </div>

        <div className="px-6 py-4">
          <p className="text-sm text-gray-500 mb-4">
            {fingerprint.length > 40
              ? fingerprint.slice(0, 40) + '...'
              : fingerprint}
          </p>

          {loading && (
            <div className="flex flex-col items-center justify-center py-12 gap-4">
              <div className="w-8 h-8 border-4 border-gray-200 border-t-[#B7007C] rounded-full animate-spin" />
              <p className="text-gray-500">Loading conversation...</p>
            </div>
          )}

          {error && (
            <div className="rounded-lg border border-red-200 bg-red-50 p-4 mb-4">
              <p className="text-sm font-medium text-red-800">{error}</p>
            </div>
          )}

          {detail && !loading && (
            <div className="space-y-6">
              {/* Metadata */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                <div className="bg-white rounded-lg border border-gray-200 p-3">
                  <p className="text-sm text-gray-500">Duration</p>
                  <p className="text-base font-semibold text-gray-900">
                    {formatNumber(detail.duration_minutes, 1)} min
                  </p>
                </div>
                <div className="bg-white rounded-lg border border-gray-200 p-3">
                  <p className="text-sm text-gray-500">Language</p>
                  <p className="text-base font-semibold text-gray-900">
                    {detail.language || '-'}
                  </p>
                </div>
                <div className="bg-white rounded-lg border border-gray-200 p-3">
                  <p className="text-sm text-gray-500">Outcome</p>
                  <p className="text-base font-semibold text-gray-900">
                    {detail.outcome || '-'}
                  </p>
                </div>
                <div className="bg-white rounded-lg border border-gray-200 p-3">
                  <p className="text-sm text-gray-500">Intent Score</p>
                  <p className="text-base font-semibold text-gray-900">
                    {formatIntentScore(detail.purchase_intent_score)}
                  </p>
                </div>
              </div>

              {/* Summary */}
              {detail.summary && (
                <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
                  <p className="text-sm font-medium text-blue-900 mb-1">
                    Summary
                  </p>
                  <p className="text-sm text-blue-800">{detail.summary}</p>
                </div>
              )}

              {/* Messages Timeline */}
              <div className="space-y-3">
                <p className="text-sm font-semibold text-gray-900">
                  Messages ({(detail.messages || []).length})
                </p>
                <div className="max-h-96 overflow-y-auto space-y-3">
                  {(detail.messages || []).map((m, i) => (
                    <div key={i} className="space-y-2">
                      {m.user_message && (
                        <div className="flex justify-end">
                          <div className="max-w-[80%] rounded-xl px-4 py-2.5 text-sm bg-[#B7007C] text-white">
                            <p>{m.user_message}</p>
                          </div>
                        </div>
                      )}
                      {m.ai_response && (
                        <div className="flex justify-start">
                          <div className="max-w-[80%] rounded-xl px-4 py-2.5 text-sm bg-gray-100 text-gray-800">
                            <p>{m.ai_response}</p>
                            {(m.products_shown || []).length > 0 && (
                              <div className="flex flex-wrap gap-1 mt-1">
                                {m.products_shown.map((p, j) => (
                                  <a
                                    key={j}
                                    href={p.product_url || '#'}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="flex items-center gap-1.5 rounded-md border border-gray-200 bg-white px-2 py-1 text-xs text-gray-600 hover:border-[#B7007C] hover:text-[#B7007C] transition-colors no-underline"
                                  >
                                    {p.image_url && (
                                      <img
                                        src={p.image_url}
                                        alt={p.name || ''}
                                        className="w-6 h-6 rounded object-cover"
                                      />
                                    )}
                                    <span>{p.name || p.sku || ''}</span>
                                  </a>
                                ))}
                              </div>
                            )}
                            {m.conversation_stage && (
                              <p className="text-xs text-gray-500 mt-1">
                                Stage: {m.conversation_stage}
                              </p>
                            )}
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              {/* Product Journey */}
              {(detail.product_journey || []).length > 0 && (
                <div className="space-y-3">
                  <p className="text-sm font-semibold text-gray-900">
                    Product Journey
                  </p>
                  {detail.product_journey.map((pj, i) => (
                    <div key={i} className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        {pj.image_url && (
                          <img
                            src={pj.image_url}
                            alt={pj.name || ''}
                            className="w-8 h-8 rounded object-cover"
                          />
                        )}
                        {pj.product_url ? (
                          <a
                            href={pj.product_url}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-sm font-semibold text-[#B7007C] hover:underline no-underline"
                          >
                            {pj.product || pj.name || pj.sku || '-'}
                          </a>
                        ) : (
                          <span className="text-sm font-semibold text-gray-900">
                            {pj.product || pj.name || pj.sku || '-'}
                          </span>
                        )}
                      </div>
                      <div className="flex gap-1">
                        {pj.recommended && (
                          <span
                            className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${BADGE_TONE_CLASSES.info}`}
                          >
                            Recommended
                          </span>
                        )}
                        {pj.clicked && (
                          <span
                            className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${BADGE_TONE_CLASSES.attention}`}
                          >
                            Clicked
                          </span>
                        )}
                        {pj.carted && (
                          <span
                            className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${BADGE_TONE_CLASSES.success}`}
                          >
                            Added to cart
                          </span>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Stage Progression */}
              {(detail.stage_progression || []).length > 0 && (
                <div className="space-y-3">
                  <p className="text-sm font-semibold text-gray-900">
                    Stage Progression
                  </p>
                  <div className="flex flex-wrap items-center gap-2">
                    {detail.stage_progression.map((s, i) => (
                      <Fragment key={i}>
                        {i > 0 && (
                          <span className="text-gray-400">{'\u2192'}</span>
                        )}
                        <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-gray-100 text-gray-700">
                          {s}
                        </span>
                      </Fragment>
                    ))}
                  </div>
                </div>
              )}

              {/* Sentiment Progression */}
              {(detail.sentiment_progression || []).length > 0 && (
                <div className="space-y-3">
                  <p className="text-sm font-semibold text-gray-900">
                    Sentiment Progression
                  </p>
                  <div className="flex flex-wrap items-center gap-2">
                    {detail.sentiment_progression.map((s, i) => {
                      const label = getSentimentLabel(s);
                      const tone = getSentimentBadgeTone(label);
                      return (
                        <Fragment key={i}>
                          {i > 0 && (
                            <span className="text-gray-400">{'\u2192'}</span>
                          )}
                          <span
                            className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
                              BADGE_TONE_CLASSES[tone] ||
                              BADGE_TONE_CLASSES.info
                            }`}
                          >
                            {label}
                          </span>
                        </Fragment>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Clicked / Added to Cart Products */}
              {((detail.clicked_products || []).length > 0 ||
                (detail.carted_products || []).length > 0) && (
                <div className="space-y-3">
                  {(detail.clicked_products || []).length > 0 && (
                    <div className="space-y-2">
                      <p className="text-sm font-semibold text-gray-900">
                        Clicked Products
                      </p>
                      <div className="flex flex-wrap gap-2">
                        {detail.clicked_products.map((product, index) => (
                          <a
                            key={index}
                            href={product.product_url || '#'}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-1.5 rounded-full border border-yellow-200 bg-yellow-50 px-2 py-0.5 text-xs font-medium text-yellow-800 hover:border-yellow-400 transition-colors no-underline"
                          >
                            {product.image_url && (
                              <img
                                src={product.image_url}
                                alt={product.name || ''}
                                className="w-5 h-5 rounded-full object-cover"
                              />
                            )}
                            <span>{product.name || product.sku}</span>
                          </a>
                        ))}
                      </div>
                    </div>
                  )}
                  {(detail.carted_products || []).length > 0 && (
                    <div className="space-y-2">
                      <p className="text-sm font-semibold text-gray-900">
                        Added to Cart
                      </p>
                      <div className="flex flex-wrap gap-2">
                        {detail.carted_products.map((product, index) => (
                          <a
                            key={index}
                            href={product.product_url || '#'}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="flex items-center gap-1.5 rounded-full border border-green-200 bg-green-50 px-2 py-0.5 text-xs font-medium text-green-800 hover:border-green-400 transition-colors no-underline"
                          >
                            {product.image_url && (
                              <img
                                src={product.image_url}
                                alt={product.name || ''}
                                className="w-5 h-5 rounded-full object-cover"
                              />
                            )}
                            <span>{product.name || product.sku}</span>
                          </a>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Extra info */}
              <div className="border-t border-gray-200 pt-4">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  <div>
                    <p className="text-sm text-gray-500">Clicks</p>
                    <p className="text-base font-semibold text-gray-900">
                      {detail.product_clicks || 0}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Add to Cart</p>
                    <p className="text-base font-semibold text-gray-900">
                      {detail.add_to_cart_count || 0}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Likes</p>
                    <p className="text-base font-semibold text-gray-900">
                      {detail.liked_messages_count || 0}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">Dislikes</p>
                    <p className="text-base font-semibold text-gray-900">
                      {detail.disliked_messages_count || 0}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default JourneyDetailModal;
