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

import {
  fetchAiInsights,
  dismissAiInsight,
} from '../../service/agent-analytics/agent-analytics.service';
import { createCampaign } from '../../service/campaigns/campaigns.service';
import type {
  IInsightReport,
  IInsightsResponse,
  IInsight,
  IInsightMetric,
  ISuggestedCampaign,
} from '../../service/agent-analytics/agent-analytics.interface';

interface InsightsTabProps {
  onInsightCountChange?: (count: number) => void;
}

const PRIORITY_STYLES: Record<
  string,
  { dot: string; badge: string; badgeText: string }
> = {
  high: {
    dot: 'bg-red-500',
    badge: 'bg-red-50 text-red-700 ring-red-600/10',
    badgeText: 'high',
  },
  medium: {
    dot: 'bg-yellow-500',
    badge: 'bg-yellow-50 text-yellow-700 ring-yellow-600/10',
    badgeText: 'medium',
  },
  low: {
    dot: 'bg-green-500',
    badge: 'bg-green-50 text-green-700 ring-green-600/10',
    badgeText: 'low',
  },
};

const InsightsTab = ({
  onInsightCountChange,
}: InsightsTabProps): JSX.Element => {
  const [report, setReport] = useState<IInsightReport | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [creatingCampaign, setCreatingCampaign] = useState<string | null>(null);
  const [campaignSuccess, setCampaignSuccess] = useState<Set<string>>(
    new Set()
  );
  const [campaignError, setCampaignError] = useState<string | null>(null);

  const fetchInsights = useCallback(() => {
    setLoading(true);
    setError(null);
    fetchAiInsights()
      .then((data: IInsightsResponse | null) => {
        const nextReport: IInsightReport | null = data?.report ?? null;
        setReport(nextReport);
        const activeInsights: IInsight[] = (nextReport?.insights || []).filter(
          (insight: IInsight) => !insight.dismissed
        );
        onInsightCountChange?.(activeInsights.length);
        setLoading(false);
      })
      .catch((err: Error) => {
        setError(err.message || 'Failed to load insights');
        setLoading(false);
      });
  }, [onInsightCountChange]);

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

  const handleDismiss = async (insightId: string) => {
    if (!report) return;
    try {
      await dismissAiInsight(report.report_id, insightId);
      setReport((prev: IInsightReport | null) => {
        if (!prev) return prev;
        const updated: IInsightReport = {
          ...prev,
          insights: prev.insights.map((insight: IInsight) =>
            insight.id === insightId ? { ...insight, dismissed: true } : insight
          ),
        };
        const activeInsights: IInsight[] = updated.insights.filter(
          (insight: IInsight) => !insight.dismissed
        );
        onInsightCountChange?.(activeInsights.length);
        return updated;
      });
    } catch {
      // Silent fail — insight stays visible
    }
  };

  const handleCreateCampaign = async (insight: IInsight) => {
    const suggestedCampaign: ISuggestedCampaign | undefined =
      insight.suggested_campaign;
    if (!suggestedCampaign) return;

    setCreatingCampaign(insight.id);
    setCampaignError(null);

    try {
      await createCampaign({
        name: suggestedCampaign.name,
        goal: suggestedCampaign.goal,
        target_categories: suggestedCampaign.target_categories,
        tone_of_voice: suggestedCampaign.tone_of_voice,
        priority: suggestedCampaign.priority,
        description: suggestedCampaign.description,
      });
      setCampaignSuccess(prev => new Set(prev).add(insight.id));
    } catch (err: unknown) {
      setCampaignError(
        err instanceof Error ? err.message : 'Failed to create campaign'
      );
    } finally {
      setCreatingCampaign(null);
    }
  };

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map(i => (
          <div key={i} className="animate-pulse">
            <div className="h-4 rounded bg-gray-200 w-3/4 mb-2" />
            <div className="h-3 rounded bg-gray-100 w-1/2" />
          </div>
        ))}
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-lg border border-red-200 bg-red-50 p-4">
        <p className="text-sm text-red-700">{error}</p>
        <button
          onClick={fetchInsights}
          className="mt-2 text-sm font-medium text-red-700 underline hover:text-red-800"
        >
          Try again
        </button>
      </div>
    );
  }

  const activeInsights: IInsight[] = (report?.insights || []).filter(
    (insight: IInsight) => !insight.dismissed
  );

  if (!report || activeInsights.length === 0) {
    return (
      <div className="space-y-5">
        <div className="rounded-2xl bg-gradient-to-br from-pink-50 via-white to-purple-50 border border-pink-100 p-6">
          <div className="flex items-start gap-3">
            <div className="p-2 rounded-xl bg-pink-100 shrink-0">
              <svg
                className="w-5 h-5 text-pink-600"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth="1.5"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
            <div>
              <h3 className="text-sm font-semibold text-gray-900">
                Insights are on their way
              </h3>
              <p className="mt-1 text-sm text-gray-500">
                AI-powered insights are generated weekly based on your
                conversation data. Once you have at least 7 days of
                conversations, your first report will appear here automatically.
              </p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const periodLabel =
    report.period_start && report.period_end
      ? `${report.period_start} — ${report.period_end}`
      : '';

  return (
    <div className="space-y-5">
      {/* Summary banner */}
      <div className="rounded-2xl bg-gradient-to-br from-pink-50 via-white to-purple-50 border border-pink-100 p-6">
        <div className="flex items-start gap-3">
          <div className="p-2 rounded-xl bg-pink-100 shrink-0">
            <svg
              className="w-5 h-5 text-pink-600"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.455 2.456L21.75 6l-1.036.259a3.375 3.375 0 00-2.455 2.456z"
              />
            </svg>
          </div>
          <div>
            <h3 className="text-sm font-semibold text-gray-900">AI Insights</h3>
            <p className="mt-1 text-sm text-gray-600">{report.summary}</p>
            {periodLabel && (
              <p className="mt-1 text-xs text-gray-400">
                Based on data from {periodLabel}
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Section header */}
      <div className="px-1">
        <p className="text-xs font-medium tracking-wide text-gray-400 uppercase">
          Recommended Actions
        </p>
      </div>

      {campaignError && (
        <div className="rounded-lg border border-red-200 bg-red-50 p-3 flex items-center justify-between">
          <p className="text-sm text-red-700">{campaignError}</p>
          <button
            onClick={() => setCampaignError(null)}
            className="text-red-400 hover:text-red-600"
          >
            <svg
              className="w-4 h-4"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>
      )}

      {/* Insight cards */}
      <div className="space-y-3">
        {activeInsights.map(insight => {
          const isExpanded = expandedId === insight.id;
          const style =
            PRIORITY_STYLES[insight.priority] || PRIORITY_STYLES.low;
          const isCampaignCreated = campaignSuccess.has(insight.id);
          const isCreating = creatingCampaign === insight.id;

          return (
            <div
              key={insight.id}
              className="border border-gray-200 rounded-xl bg-white overflow-hidden"
            >
              {/* Collapsed header */}
              <button
                type="button"
                className="w-full px-4 py-3 flex items-center gap-3 hover:bg-gray-50 transition-colors text-left"
                onClick={() => setExpandedId(isExpanded ? null : insight.id)}
              >
                <span
                  className={`w-2.5 h-2.5 rounded-full shrink-0 ${style.dot}`}
                />
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-gray-900 truncate">
                    {insight.title}
                  </p>
                  <p className="text-xs text-gray-500 truncate">
                    {insight.subtitle}
                  </p>
                </div>
                <span
                  className={`inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset ${style.badge}`}
                >
                  {style.badgeText}
                </span>
                <svg
                  className={`w-4 h-4 text-gray-400 shrink-0 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                  fill="none"
                  viewBox="0 0 24 24"
                  strokeWidth="1.5"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M19.5 8.25l-7.5 7.5-7.5-7.5"
                  />
                </svg>
              </button>

              {/* Expanded content */}
              {isExpanded && (
                <div className="px-4 pb-4 border-t border-gray-100">
                  {/* Metrics */}
                  {insight.metrics?.length > 0 && (
                    <div className="flex flex-wrap gap-2 mt-3">
                      {insight.metrics.map(
                        (metric: IInsightMetric, index: number) => (
                          <div
                            key={index}
                            className="px-3 py-2 rounded-lg bg-gray-50 border border-gray-100"
                          >
                            <p className="text-xs text-gray-500">
                              {metric.label}
                            </p>
                            <p className="text-sm font-semibold text-gray-900">
                              {metric.value}
                            </p>
                          </div>
                        )
                      )}
                    </div>
                  )}

                  {/* Suggested campaign */}
                  {insight.suggested_campaign && (
                    <div className="mt-4 rounded-xl bg-purple-50 border border-purple-100 p-4">
                      <div className="flex items-center gap-2">
                        <svg
                          className="w-4 h-4 text-purple-600 shrink-0"
                          fill="none"
                          viewBox="0 0 24 24"
                          strokeWidth="1.5"
                          stroke="currentColor"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            d="M7.5 3.75H6A2.25 2.25 0 003.75 6v1.5M16.5 3.75H18A2.25 2.25 0 0120.25 6v1.5m0 9V18A2.25 2.25 0 0118 20.25h-1.5m-9 0H6A2.25 2.25 0 013.75 18v-1.5M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                          />
                        </svg>
                        <p className="text-sm font-semibold text-purple-900">
                          Suggested action: Create a targeted campaign
                        </p>
                      </div>

                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-3">
                        <div>
                          <p className="text-xs text-purple-600">
                            Campaign name
                          </p>
                          <div className="mt-1 px-3 py-1.5 rounded-lg bg-white border border-purple-100 text-sm">
                            {insight.suggested_campaign.name}
                          </div>
                        </div>
                        <div>
                          <p className="text-xs text-purple-600">Goal</p>
                          <div className="mt-1 px-3 py-1.5 rounded-lg bg-white border border-purple-100 text-sm capitalize">
                            {insight.suggested_campaign.goal}
                          </div>
                        </div>
                        <div>
                          <p className="text-xs text-purple-600">
                            Target categories
                          </p>
                          <div className="mt-1 px-3 py-1.5 rounded-lg bg-white border border-purple-100 text-sm">
                            {insight.suggested_campaign.target_categories?.join(
                              ', '
                            ) || '—'}
                          </div>
                        </div>
                        <div>
                          <p className="text-xs text-purple-600">Tone</p>
                          <div className="mt-1 px-3 py-1.5 rounded-lg bg-white border border-purple-100 text-sm">
                            {insight.suggested_campaign.tone_of_voice}
                          </div>
                        </div>
                      </div>

                      <div className="mt-3 flex gap-2">
                        {isCampaignCreated ? (
                          <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-green-50 border border-green-200 text-green-700 text-sm">
                            <svg
                              className="w-4 h-4"
                              fill="none"
                              viewBox="0 0 24 24"
                              strokeWidth="1.5"
                              stroke="currentColor"
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                d="M4.5 12.75l6 6 9-13.5"
                              />
                            </svg>
                            Campaign created
                          </div>
                        ) : (
                          <button
                            onClick={() => handleCreateCampaign(insight)}
                            disabled={isCreating}
                            className="inline-flex items-center gap-2 rounded-lg bg-purple-600 px-4 py-2 text-sm font-medium text-white hover:bg-purple-700 disabled:opacity-50 transition-colors"
                          >
                            {isCreating && (
                              <div className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                            )}
                            Create campaign with these settings
                          </button>
                        )}
                      </div>
                    </div>
                  )}

                  {/* Dismiss */}
                  <div className="mt-3 flex justify-end">
                    <button
                      onClick={() => handleDismiss(insight.id)}
                      className="text-sm text-red-500 hover:text-red-700 transition-colors"
                    >
                      Dismiss
                    </button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default InsightsTab;
