'use client';

import { useState, useMemo } from 'react';
import {
  ComposedChart,
  Bar,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Brush,
  Area,
  ReferenceLine,
} from 'recharts';
import { X, TrendingUp, TrendingDown, Minus, Calendar, Filter } from 'lucide-react';
import type { TimelinePoint, TimeRange, Granularity } from '../types';
import { DOMAIN_LABELS } from '../types';
import { useReviewIQFilters } from '@/contexts/ReviewIQFilterContext';

interface TimelineChartProps {
  data: TimelinePoint[];
  // AI-generated insight headline (optional - shows when available)
  insight?: string | null;
  // Timeline granularity from API (day, week, month, year)
  granularity?: Granularity;
}

type ViewMode = 'sentiment' | 'volume' | 'rating';

const VIEW_OPTIONS: { value: ViewMode; emoji: string; label: string; description: string }[] = [
  { value: 'sentiment', emoji: '😊', label: 'Sentiment', description: 'Positive vs Negative over time' },
  { value: 'volume', emoji: '📊', label: 'Volume', description: 'Review & mention counts' },
  { value: 'rating', emoji: '⭐', label: 'Rating', description: 'Average rating trend' },
];

const TIME_RANGE_OPTIONS: { value: TimeRange; label: string; description: string }[] = [
  { value: '7d', label: '7D', description: 'Last 7 days' },
  { value: '14d', label: '2W', description: 'Last 2 weeks' },
  { value: '30d', label: '1M', description: 'Last month' },
  { value: '90d', label: '3M', description: 'Last 3 months' },
  { value: '1y', label: '1Y', description: 'Last year' },
  { value: 'all', label: 'All', description: 'All time' },
];

/**
 * Timeline Chart - Shows trends over time.
 * User-friendly design with view toggles and interactive brush.
 * Responds to domain/sentiment filters.
 */
export function TimelineChart({ data, insight, granularity = 'week' }: TimelineChartProps) {
  const { filters, setTimeRange, setBrushRange } = useReviewIQFilters();
  const [viewMode, setViewMode] = useState<ViewMode>('sentiment');
  const [localBrushRange, setLocalBrushRange] = useState<{
    startIndex: number;
    endIndex: number;
  } | null>(null);

  // Sort data chronologically (oldest first, most recent on right)
  const sortedData = useMemo(() => {
    return [...data].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
  }, [data]);

  // Calculate summary stats
  const stats = useMemo(() => {
    if (sortedData.length === 0) return null;

    const totalReviews = sortedData.reduce((sum, d) => sum + d.review_count, 0);
    const totalPositive = sortedData.reduce((sum, d) => sum + d.positive_count, 0);
    const totalNegative = sortedData.reduce((sum, d) => sum + d.negative_count, 0);
    const avgRating = sortedData.reduce((sum, d) => sum + (d.avg_rating || 0), 0) / sortedData.length;

    // Calculate trend (compare last 30% vs first 30%)
    const splitPoint = Math.floor(sortedData.length * 0.3);
    const earlyData = sortedData.slice(0, splitPoint);
    const recentData = sortedData.slice(-splitPoint);

    const earlyPositiveRatio = earlyData.length > 0
      ? earlyData.reduce((sum, d) => sum + d.positive_count, 0) /
        Math.max(1, earlyData.reduce((sum, d) => sum + d.positive_count + d.negative_count, 0))
      : 0;
    const recentPositiveRatio = recentData.length > 0
      ? recentData.reduce((sum, d) => sum + d.positive_count, 0) /
        Math.max(1, recentData.reduce((sum, d) => sum + d.positive_count + d.negative_count, 0))
      : 0;

    const trendDirection = recentPositiveRatio > earlyPositiveRatio + 0.05
      ? 'improving'
      : recentPositiveRatio < earlyPositiveRatio - 0.05
      ? 'declining'
      : 'stable';

    return {
      totalReviews,
      totalPositive,
      totalNegative,
      avgRating,
      positiveRatio: totalReviews > 0 ? (totalPositive / (totalPositive + totalNegative)) * 100 : 0,
      trendDirection,
      dateRange: {
        start: sortedData[0]?.date,
        end: sortedData[sortedData.length - 1]?.date,
      },
    };
  }, [sortedData]);

  // Handle brush change
  const handleBrushChange = (range: { startIndex?: number; endIndex?: number }) => {
    if (
      range &&
      typeof range.startIndex === 'number' &&
      typeof range.endIndex === 'number'
    ) {
      setLocalBrushRange({ startIndex: range.startIndex, endIndex: range.endIndex });

      // Only set filter if not full range
      if (range.startIndex !== 0 || range.endIndex !== sortedData.length - 1) {
        const startDate = sortedData[range.startIndex]?.date;
        const endDate = sortedData[range.endIndex]?.date;
        if (startDate && endDate) {
          setBrushRange({ start: startDate, end: endDate });
        }
      } else {
        setBrushRange(null);
      }
    }
  };

  const clearBrushRange = () => {
    setLocalBrushRange({ startIndex: 0, endIndex: sortedData.length - 1 });
    setBrushRange(null);
  };

  const hasBrushFilter = filters.brushRange !== null;
  const hasDomainFilter = filters.urtDomain !== null;
  const hasSentimentFilter = filters.sentiment.length > 0;
  const hasAnyFilter = hasBrushFilter || hasDomainFilter || hasSentimentFilter;

  // Format date for display based on granularity
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    switch (granularity) {
      case 'day':
        return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
      case 'week':
        return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
      case 'month':
        return date.toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
      case 'year':
        return date.toLocaleDateString('en-US', { year: 'numeric' });
      default:
        return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    }
  };

  return (
    <div
      className={`bg-white rounded-xl p-6 shadow-md transition-all ${
        hasBrushFilter
          ? 'border-3 border-blue-500 ring-2 ring-blue-200'
          : hasAnyFilter
          ? 'border-2 border-purple-400 ring-1 ring-purple-200'
          : 'border-2 border-gray-300 hover:border-blue-400'
      }`}
    >
      {/* Header */}
      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 mb-4">
        <div className="flex items-start gap-3">
          <div className="p-2 bg-blue-100 rounded-lg">
            <Calendar className="w-6 h-6 text-blue-600" />
          </div>
          <div>
            <h3 className="text-xl font-bold text-gray-900">Trends Over Time</h3>
            <p className="text-sm text-gray-500 mt-0.5">
              {stats ? (
                <>
                  {stats.totalReviews.toLocaleString()} reviews
                  {stats.dateRange.start && stats.dateRange.end && (
                    <span className="text-gray-400">
                      {' '}• {formatDate(stats.dateRange.start)} - {formatDate(stats.dateRange.end)}
                    </span>
                  )}
                </>
              ) : (
                'No data available'
              )}
            </p>
          </div>
        </div>

        {/* Controls */}
        <div className="flex flex-wrap items-center gap-2">
          {/* Active filters indicator */}
          {(hasDomainFilter || hasSentimentFilter) && (
            <div className="flex items-center gap-1 text-xs text-purple-600 bg-purple-50 px-2 py-1 rounded-full">
              <Filter className="w-3 h-3" />
              {hasDomainFilter && DOMAIN_LABELS[filters.urtDomain!]}
              {hasDomainFilter && hasSentimentFilter && ' + '}
              {hasSentimentFilter && filters.sentiment.join(', ')}
            </div>
          )}

          {/* Clear brush button */}
          {hasBrushFilter && (
            <button
              onClick={clearBrushRange}
              className="px-3 py-1.5 text-sm font-semibold rounded-lg bg-red-100 text-red-700 hover:bg-red-200 transition-all flex items-center gap-1"
            >
              <X className="w-4 h-4" />
              Clear Range
            </button>
          )}

          {/* Time range buttons */}
          <div className="flex items-center bg-gray-100 rounded-lg p-1">
            {TIME_RANGE_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                onClick={() => {
                  setTimeRange(opt.value);
                  clearBrushRange();
                }}
                className={`px-2.5 py-1 text-xs font-semibold rounded-md transition-all ${
                  filters.timeRange === opt.value && !hasBrushFilter
                    ? 'bg-blue-600 text-white shadow-sm'
                    : 'text-gray-600 hover:bg-gray-200'
                }`}
                title={opt.description}
              >
                {opt.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* View Mode Toggle */}
      <div className="flex items-center gap-2 mb-4">
        {VIEW_OPTIONS.map((opt) => (
          <button
            key={opt.value}
            onClick={() => setViewMode(opt.value)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold transition-all ${
              viewMode === opt.value
                ? 'bg-blue-100 text-blue-700 ring-2 ring-blue-300'
                : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
            }`}
            title={opt.description}
          >
            <span className="text-lg">{opt.emoji}</span>
            <span>{opt.label}</span>
          </button>
        ))}

        {/* Trend indicator */}
        {stats && (
          <div className="ml-auto flex items-center gap-2">
            <span className="text-sm text-gray-500">Trend:</span>
            {stats.trendDirection === 'improving' && (
              <div className="flex items-center gap-1 text-green-600 bg-green-50 px-2 py-1 rounded-full">
                <TrendingUp className="w-4 h-4" />
                <span className="text-xs font-semibold">Improving</span>
              </div>
            )}
            {stats.trendDirection === 'declining' && (
              <div className="flex items-center gap-1 text-red-600 bg-red-50 px-2 py-1 rounded-full">
                <TrendingDown className="w-4 h-4" />
                <span className="text-xs font-semibold">Declining</span>
              </div>
            )}
            {stats.trendDirection === 'stable' && (
              <div className="flex items-center gap-1 text-gray-600 bg-gray-100 px-2 py-1 rounded-full">
                <Minus className="w-4 h-4" />
                <span className="text-xs font-semibold">Stable</span>
              </div>
            )}
          </div>
        )}
      </div>

      {/* AI Insight (when available) */}
      {insight && (
        <div className="mb-4 p-3 bg-gradient-to-r from-purple-50 to-blue-50 rounded-lg border border-purple-200">
          <div className="flex items-start gap-2">
            <span className="text-sm">✨</span>
            <div>
              <div className="text-xs font-medium text-purple-600 mb-0.5">AI Insight</div>
              <p className="text-sm text-gray-700">{insight}</p>
            </div>
          </div>
        </div>
      )}

      {sortedData.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-80 text-gray-500">
          <Calendar className="w-12 h-12 text-gray-300 mb-2" />
          <span>No timeline data available</span>
        </div>
      ) : (
        <ResponsiveContainer width="100%" height={350}>
          <ComposedChart
            data={sortedData}
            margin={{ top: 10, right: 30, left: 0, bottom: 30 }}
          >
            <defs>
              <linearGradient id="positiveGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#22c55e" stopOpacity={0.8} />
                <stop offset="95%" stopColor="#22c55e" stopOpacity={0.1} />
              </linearGradient>
              <linearGradient id="negativeGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#ef4444" stopOpacity={0.8} />
                <stop offset="95%" stopColor="#ef4444" stopOpacity={0.1} />
              </linearGradient>
              <linearGradient id="volumeGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.8} />
                <stop offset="95%" stopColor="#3b82f6" stopOpacity={0.1} />
              </linearGradient>
            </defs>

            <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" vertical={false} />

            <XAxis
              dataKey="date"
              tick={{ fill: '#6b7280', fontSize: 11 }}
              tickLine={false}
              axisLine={{ stroke: '#e5e7eb' }}
              tickFormatter={formatDate}
              interval="preserveStartEnd"
            />

            {/* Sentiment View */}
            {viewMode === 'sentiment' && (
              <>
                <YAxis
                  tick={{ fill: '#6b7280', fontSize: 11 }}
                  tickLine={false}
                  axisLine={false}
                  label={{
                    value: 'Mentions',
                    angle: -90,
                    position: 'insideLeft',
                    fill: '#9ca3af',
                    fontSize: 12,
                  }}
                />
                <Area
                  type="monotone"
                  dataKey="positive_count"
                  stackId="sentiment"
                  fill="url(#positiveGradient)"
                  stroke="#22c55e"
                  strokeWidth={2}
                  name="😊 Positive"
                />
                <Area
                  type="monotone"
                  dataKey="negative_count"
                  stackId="sentiment"
                  fill="url(#negativeGradient)"
                  stroke="#ef4444"
                  strokeWidth={2}
                  name="😟 Negative"
                />
              </>
            )}

            {/* Volume View */}
            {viewMode === 'volume' && (
              <>
                <YAxis
                  tick={{ fill: '#6b7280', fontSize: 11 }}
                  tickLine={false}
                  axisLine={false}
                  label={{
                    value: 'Count',
                    angle: -90,
                    position: 'insideLeft',
                    fill: '#9ca3af',
                    fontSize: 12,
                  }}
                />
                <Bar
                  dataKey="review_count"
                  fill="#3b82f6"
                  opacity={0.8}
                  name="📝 Reviews"
                  radius={[4, 4, 0, 0]}
                />
                <Line
                  type="monotone"
                  dataKey="span_count"
                  stroke="#8b5cf6"
                  strokeWidth={2}
                  dot={{ fill: '#8b5cf6', r: 3 }}
                  name="💬 Mentions"
                />
              </>
            )}

            {/* Rating View */}
            {viewMode === 'rating' && (
              <>
                <YAxis
                  domain={[0, 5]}
                  ticks={[0, 1, 2, 3, 4, 5]}
                  tick={{ fill: '#6b7280', fontSize: 11 }}
                  tickLine={false}
                  axisLine={false}
                  label={{
                    value: 'Rating',
                    angle: -90,
                    position: 'insideLeft',
                    fill: '#9ca3af',
                    fontSize: 12,
                  }}
                />
                <ReferenceLine y={4} stroke="#22c55e" strokeDasharray="5 5" label={{ value: 'Good', fill: '#22c55e', fontSize: 10 }} />
                <ReferenceLine y={3} stroke="#eab308" strokeDasharray="5 5" label={{ value: 'OK', fill: '#eab308', fontSize: 10 }} />
                <Area
                  type="monotone"
                  dataKey="avg_rating"
                  fill="url(#volumeGradient)"
                  stroke="#3b82f6"
                  strokeWidth={3}
                  name="⭐ Avg Rating"
                  dot={{ fill: '#3b82f6', r: 4, strokeWidth: 2, stroke: '#fff' }}
                />
              </>
            )}

            <Tooltip
              contentStyle={{
                backgroundColor: '#ffffff',
                border: 'none',
                borderRadius: '12px',
                boxShadow: '0 10px 40px rgba(0,0,0,0.15)',
                padding: '12px 16px',
              }}
              content={({ active, payload, label }) => {
                if (active && payload && payload.length) {
                  const data = payload[0]?.payload as TimelinePoint;
                  return (
                    <div className="min-w-[180px]">
                      <p className="font-bold text-gray-900 mb-2 pb-2 border-b border-gray-100">
                        📅 {formatDate(String(label))}
                      </p>

                      {viewMode === 'sentiment' && (
                        <>
                          <div className="flex items-center justify-between py-1">
                            <span className="text-green-600">😊 Positive</span>
                            <span className="font-bold text-green-600">{data.positive_count}</span>
                          </div>
                          <div className="flex items-center justify-between py-1">
                            <span className="text-red-600">😟 Negative</span>
                            <span className="font-bold text-red-600">{data.negative_count}</span>
                          </div>
                        </>
                      )}

                      {viewMode === 'volume' && (
                        <>
                          <div className="flex items-center justify-between py-1">
                            <span className="text-blue-600">📝 Reviews</span>
                            <span className="font-bold text-blue-600">{data.review_count}</span>
                          </div>
                          <div className="flex items-center justify-between py-1">
                            <span className="text-purple-600">💬 Mentions</span>
                            <span className="font-bold text-purple-600">{data.span_count}</span>
                          </div>
                        </>
                      )}

                      {viewMode === 'rating' && (
                        <div className="flex items-center justify-between py-1">
                          <span className="text-blue-600">⭐ Avg Rating</span>
                          <span className="font-bold text-blue-600">
                            {data.avg_rating?.toFixed(1) || 'N/A'}
                          </span>
                        </div>
                      )}

                      <div className="mt-2 pt-2 border-t border-gray-100 text-xs text-gray-500">
                        {data.review_count} reviews this period
                      </div>
                    </div>
                  );
                }
                return null;
              }}
            />

            {/* Brush for date range selection */}
            <Brush
              dataKey="date"
              height={40}
              stroke="#3b82f6"
              fill="#f8fafc"
              travellerWidth={10}
              startIndex={localBrushRange?.startIndex ?? 0}
              endIndex={localBrushRange?.endIndex ?? sortedData.length - 1}
              onChange={handleBrushChange}
              tickFormatter={formatDate}
            />
          </ComposedChart>
        </ResponsiveContainer>
      )}

      {/* Footer hint */}
      <div className="mt-2 text-center text-xs text-gray-500">
        💡 Drag the handles below the chart to zoom into a specific date range
      </div>
    </div>
  );
}
