import React, { useState, useEffect, useCallback, useMemo } from 'react';

import { fetchAgentJourneys } from '../../service/agent-analytics/agent-analytics.service';
import type {
  IAgentDateRange,
  IJourneyListItem,
} from '../../service/agent-analytics/agent-analytics.interface';
import ThumbsDownIcon from '../svg/ThumbsDownIcon';
import ThumbsUpIcon from '../svg/ThumbsUpIcon';

import EmptyState from './EmptyState';
import ErrorBanner from './ErrorBanner';
import JourneyDetailModal from './JourneyDetailModal';
import { formatNumber, formatDateTime, formatIntentScore } from './helpers';
import { getOutcomeBadgeTone } from './conversationsTab.utils';

const OUTCOME_OPTIONS = [
  { label: 'All outcomes', value: '' },
  { label: 'Purchase intent', value: 'purchase_intent' },
  { label: 'Abandoned', value: 'abandoned' },
  { label: 'Information only', value: 'information_only' },
  { label: 'Comparison', value: 'comparison' },
  { label: 'Support resolved', value: 'support_resolved' },
  { label: 'Complaint', value: 'complaint' },
];

const SENTIMENT_OPTIONS = [
  { label: 'All sentiments', value: '' },
  { label: 'Positive', value: 'positive' },
  { label: 'Neutral', value: 'neutral' },
  { label: 'Negative', value: 'negative' },
];

interface ConversationsTabProps {
  dateRange: IAgentDateRange;
  initialOutcomeFilter?: string;
  initialSentimentFilter?: string;
}

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

const ConversationsTab = ({
  dateRange,
  initialOutcomeFilter = '',
  initialSentimentFilter = '',
}: ConversationsTabProps): JSX.Element => {
  const [journeys, setJourneys] = useState<IJourneyListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedFp, setSelectedFp] = useState<string | null>(null);
  const [outcomeFilter, setOutcomeFilter] = useState(initialOutcomeFilter);
  const [sentimentFilter, setSentimentFilter] = useState(
    initialSentimentFilter
  );

  const fetchJourneys = useCallback(() => {
    setLoading(true);
    setError(null);
    fetchAgentJourneys(dateRange.start, dateRange.end)
      .then(d => {
        setJourneys(d.journeys || []);
        setLoading(false);
      })
      .catch(e => {
        setError(e.message);
        setLoading(false);
      });
  }, [dateRange.start, dateRange.end]);

  useEffect(() => {
    fetchJourneys();
  }, [fetchJourneys]);

  const filteredJourneys = useMemo(() => {
    let result = journeys;
    if (outcomeFilter) {
      result = result.filter(j => j.outcome === outcomeFilter);
    }
    if (sentimentFilter) {
      result = result.filter(j => j.sentiment === sentimentFilter);
    }
    return result;
  }, [journeys, outcomeFilter, sentimentFilter]);

  if (loading) {
    return (
      <div className="bg-white rounded-xl border border-gray-200 p-5">
        <div className="flex flex-col gap-4">
          <div className="space-y-2">
            {Array.from({ length: 8 }).map((_, i) => (
              <div key={i} className="h-4 bg-gray-200 rounded animate-pulse" />
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (error) return <ErrorBanner message={error} onRetry={fetchJourneys} />;
  if (journeys.length === 0)
    return <EmptyState message="No conversations for this period" />;

  return (
    <div>
      <div className="bg-white rounded-xl border border-gray-200 p-5">
        <div className="flex flex-col gap-4">
          <div className="flex items-center justify-between">
            <h3 className="text-sm font-semibold text-gray-900">
              {filteredJourneys.length} Conversations
              {(outcomeFilter || sentimentFilter) && (
                <span className="text-xs font-normal text-gray-500">
                  {` (filtered from ${journeys.length})`}
                </span>
              )}
            </h3>
            <div className="flex items-center gap-2">
              <select
                className="text-xs border border-gray-200 rounded-md px-2 py-1 bg-white text-gray-700"
                value={outcomeFilter}
                onChange={e => setOutcomeFilter(e.target.value)}
              >
                {OUTCOME_OPTIONS.map(o => (
                  <option key={o.value} value={o.value}>
                    {o.label}
                  </option>
                ))}
              </select>
              <select
                className="text-xs border border-gray-200 rounded-md px-2 py-1 bg-white text-gray-700"
                value={sentimentFilter}
                onChange={e => setSentimentFilter(e.target.value)}
              >
                {SENTIMENT_OPTIONS.map(o => (
                  <option key={o.value} value={o.value}>
                    {o.label}
                  </option>
                ))}
              </select>
            </div>
          </div>
          {filteredJourneys.length > 0 ? (
            <>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-gray-200">
                      <th className="text-left py-2 px-3 font-medium text-gray-600">
                        Date
                      </th>
                      <th className="text-right py-2 px-3 font-medium text-gray-600">
                        Duration
                      </th>
                      <th className="text-right py-2 px-3 font-medium text-gray-600">
                        Messages
                      </th>
                      <th className="text-left py-2 px-3 font-medium text-gray-600">
                        Outcome
                      </th>
                      <th className="text-right py-2 px-3 font-medium text-gray-600">
                        Intent
                      </th>
                      <th className="text-right py-2 px-3 font-medium text-gray-600">
                        Clicks
                      </th>
                      <th className="text-right py-2 px-3 font-medium text-gray-600">
                        Carts
                      </th>
                      <th className="text-left py-2 px-3 font-medium text-gray-600">
                        Feedback
                      </th>
                      <th className="text-left py-2 px-3 font-medium text-gray-600">
                        Stage
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredJourneys.map((j, idx) => (
                      <tr
                        key={j.fingerprint || idx}
                        className="border-b border-gray-100 cursor-pointer hover:bg-[#ffeef8] transition-colors"
                        onClick={() => setSelectedFp(j.fingerprint)}
                      >
                        <td className="py-2 px-3">
                          {formatDateTime(j.first_message_at)}
                        </td>
                        <td className="text-right py-2 px-3">
                          {j.duration_minutes != null
                            ? formatNumber(j.duration_minutes, 1) + 'm'
                            : '-'}
                        </td>
                        <td className="text-right py-2 px-3">
                          {j.message_count || 0}
                        </td>
                        <td className="py-2 px-3">
                          <span
                            className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${
                              BADGE_TONE_CLASSES[
                                getOutcomeBadgeTone(j.outcome)
                              ] || BADGE_TONE_CLASSES.info
                            }`}
                          >
                            {j.outcome || '-'}
                          </span>
                        </td>
                        <td className="text-right py-2 px-3">
                          {formatIntentScore(j.purchase_intent_score)}
                        </td>
                        <td className="py-2 px-3">
                          {(j.clicked_products || []).length > 0 ? (
                            <div className="flex flex-wrap gap-1">
                              {j.clicked_products.map((product, index) => (
                                <span
                                  key={index}
                                  className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${BADGE_TONE_CLASSES.warning}`}
                                >
                                  {product.name || product.sku}
                                </span>
                              ))}
                            </div>
                          ) : (
                            j.product_clicks || 0
                          )}
                        </td>
                        <td className="py-2 px-3">
                          {(j.carted_products || []).length > 0 ? (
                            <div className="flex flex-wrap gap-1">
                              {j.carted_products.map((product, index) => (
                                <span
                                  key={index}
                                  className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${BADGE_TONE_CLASSES.success}`}
                                >
                                  {product.name || product.sku}
                                </span>
                              ))}
                            </div>
                          ) : (
                            j.add_to_cart_count || 0
                          )}
                        </td>
                        <td className="py-2 px-3">
                          {j.liked_messages_count ||
                          j.disliked_messages_count ? (
                            <div className="flex items-center gap-2 text-xs">
                              {j.liked_messages_count > 0 && (
                                <span className="inline-flex items-center gap-1 text-emerald-600">
                                  <ThumbsUpIcon />
                                  {j.liked_messages_count}
                                </span>
                              )}
                              {j.disliked_messages_count > 0 && (
                                <span className="inline-flex items-center gap-1 text-rose-600">
                                  <ThumbsDownIcon />
                                  {j.disliked_messages_count}
                                </span>
                              )}
                            </div>
                          ) : (
                            <span className="text-gray-400">-</span>
                          )}
                        </td>
                        <td className="py-2 px-3">
                          {j.last_stage ? (
                            <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-gray-100 text-gray-700">
                              {j.last_stage}
                            </span>
                          ) : (
                            '-'
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <p className="text-sm text-gray-500">
                Click a row to view conversation details
              </p>
            </>
          ) : (
            <EmptyState message="No conversations match the selected filters" />
          )}
        </div>
      </div>

      {selectedFp && (
        <JourneyDetailModal
          fingerprint={selectedFp}
          onClose={() => setSelectedFp(null)}
        />
      )}
    </div>
  );
};

export default ConversationsTab;
