import React, { useState, useEffect } from 'react';
import Chart from 'react-apexcharts';
import ChartCard from './shared/ChartCard';
import ChartPagination from './shared/ChartPagination';
import {
  COLORS, apexAnimation, apexToolbar, apexFontFamily,
  apexLegend, apexGrid, apexTooltipStyle, apexMarkers,
  apexStroke, buildGradientFill, percentageYAxis, apexXAxisLabels,
} from './shared/chartTokens';

// ─────────────────────────────────────────────────────────────
// ProgressTrendsChart – Area / Line chart for progress trends
//
// Props:
//   chartData:        { series: [{name,data}], categories: string[] }
//   loading:          bool
//   title:            string
//   icon:             string (emoji)
//   description:      string
//   chartType:        'area' | 'line' | 'bar'
//   emptyStateMessage: string
//   enableDataLabels: bool
//   accentColor:      string
// ─────────────────────────────────────────────────────────────

const ITEMS_PER_PAGE = 8;

// Series color map — first = Answered, second = Accepted
const SERIES_COLORS = ['#6366F1', '#10B981', '#F59E0B', '#EF4444', '#06B6D4'];

const ProgressTrendsChart = ({
  chartData = null,
  loading = false,
  title = 'Progress Trends',
  icon = '📈',
  description = 'Track progress over time',
  chartType = 'area',
  emptyStateMessage = 'Select filters to view progress trends.',
  enableDataLabels = false,
  accentColor = '#6366F1',
}) => {
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => { setCurrentPage(1); }, [chartData]);

  // ── Data checks ──────────────────────────────────────────────────────────────
  const hasData =
    chartData &&
    chartData.series?.length > 0 &&
    chartData.categories?.length > 0;

  // ── Pagination ───────────────────────────────────────────────────────────────
  const totalItems = hasData ? chartData.categories.length : 0;
  const totalPages = Math.ceil(totalItems / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex   = Math.min(startIndex + ITEMS_PER_PAGE, totalItems);

  const paginatedData = hasData ? {
    categories: chartData.categories.slice(startIndex, endIndex),
    series: chartData.series.map(s => ({ ...s, data: s.data.slice(startIndex, endIndex) })),
  } : { categories: [], series: [] };

  // ── Chart options ────────────────────────────────────────────────────────────
  const chartOptions = {
    chart: {
      type: chartType,
      height: 340,
      toolbar: apexToolbar,
      fontFamily: apexFontFamily,
      background: 'transparent',
      animations: apexAnimation,
    },
    stroke: {
      ...apexStroke,
      width: chartType === 'bar' ? 0 : 3,
      dashArray: paginatedData.series.map((_, i) => i === 1 ? 5 : 0), // Accepted dashed
    },
    fill: chartType === 'area' ? buildGradientFill(0.3, 0.02) : { opacity: 1 },
    dataLabels: {
      enabled: enableDataLabels,
      formatter: (val) => `${Number(val).toFixed(1)}%`,
      style: { fontSize: '11px', fontFamily: apexFontFamily, fontWeight: '600', colors: ['#fff'] },
      background: {
        enabled: true, foreColor: '#1E293B', borderRadius: 4,
        padding: 4, opacity: 0.9, borderWidth: 0,
      },
    },
    markers: apexMarkers,
    xaxis: {
      categories: paginatedData.categories,
      labels: apexXAxisLabels,
      axisBorder: { show: true, color: COLORS.borderLight },
      axisTicks: { show: false },
    },
    yaxis: percentageYAxis(),
    colors: SERIES_COLORS,
    legend: apexLegend,
    grid: apexGrid,
    tooltip: {
      shared: true,
      intersect: false,
      style: apexTooltipStyle,
      y: {
        formatter: (val, { seriesIndex }) => {
          const name = paginatedData.series[seriesIndex]?.name || '';
          return `${name}: ${Number(val).toFixed(2)}%`;
        },
      },
    },
    responsive: [{
      breakpoint: 768,
      options: { chart: { height: 280 }, legend: { position: 'bottom' } },
    }],
  };

  const badge = hasData
    ? `${startIndex + 1}–${endIndex} of ${totalItems}`
    : null;

  return (
    <ChartCard
      title={title}
      icon={icon}
      description={description}
      badge={badge}
      loading={loading}
      isEmpty={!hasData}
      skeletonType="lines"
      emptyIcon="📊"
      emptyTitle="No Trend Data"
      emptyMessage={emptyStateMessage}
      accentColor={accentColor}
      minHeight="420px"
    >
      {/* Inner chart bg */}
      <div style={{
        background: '#FAFBFF', borderRadius: '12px',
        border: `1px solid ${COLORS.border}`, padding: '12px 8px', marginBottom: '12px',
      }}>
        <Chart
          options={chartOptions}
          series={paginatedData.series}
          type={chartType}
          height={totalPages > 1 ? 320 : 340}
        />
      </div>

      {/* Pagination */}
      <ChartPagination
        currentPage={currentPage}
        totalPages={totalPages}
        onPage={setCurrentPage}
        startIndex={startIndex}
        endIndex={endIndex}
        totalItems={totalItems}
        itemLabel="periods"
      />
    </ChartCard>
  );
};

export default ProgressTrendsChart;