import { useState, useMemo } from 'react';
import { useAnalytics } from './useAnalytics';
import FunnelChart from './charts/FunnelChart';
import RevenueChart from './charts/RevenueChart';
import ObjectTypeChart from './charts/ObjectTypeChart';
import AvgTimeChart from './charts/AvgTimeChart';

const PERIODS = [
  { label: '7 дней', days: 7 },
  { label: '30 дней', days: 30 },
  { label: '90 дней', days: 90 },
  { label: '365 дней', days: 365 },
];

function getRange(days) {
  const to = new Date();
  const from = new Date();
  from.setDate(from.getDate() - days);
  return { from: from.toISOString(), to: to.toISOString() };
}

const KpiCard = ({ label, value, sub }) => (
  <div className="glass-panel" style={{ padding: '22px', flex: '1 1 190px', minWidth: '160px' }}>
    <p style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.4px', marginBottom: '7px' }}>
      {label}
    </p>
    <p style={{ fontFamily: 'var(--font-heading)', fontSize: '1.8rem', fontWeight: 800, color: 'var(--text-main)', lineHeight: 1 }}>
      {value}
    </p>
    {sub && <p style={{ fontSize: '0.8rem', color: 'var(--accent-blue)', marginTop: '5px' }}>{sub}</p>}
  </div>
);

const AnalyticsDashboard = () => {
  const [activeDays, setActiveDays] = useState(30);
  const { from, to } = useMemo(() => getRange(activeDays), [activeDays]);
  const {
    totalOrders, closedOrders, conversionRate,
    totalRevenue, avgDeal,
    funnelData, revenueByMonth, byObjectType, avgTimeData,
    loading,
  } = useAnalytics(from, to);

  return (
    <div>
      {/* Period selector */}
      <div style={{ display: 'flex', gap: '7px', marginBottom: '24px', flexWrap: 'wrap' }}>
        {PERIODS.map(({ label, days }) => (
          <button
            key={days}
            onClick={() => setActiveDays(days)}
            style={{
              padding: '7px 16px', borderRadius: '50px',
              border: `1.5px solid ${activeDays === days ? 'var(--accent-blue)' : 'var(--border-light)'}`,
              background: activeDays === days ? 'rgba(14, 165, 233, 0.08)' : '#fff',
              color: activeDays === days ? 'var(--accent-blue)' : 'var(--text-muted)',
              fontFamily: 'var(--font-heading)', fontWeight: 600, fontSize: '0.82rem',
              cursor: 'pointer', transition: 'all 0.15s',
            }}
          >
            {label}
          </button>
        ))}
      </div>

      {loading ? (
        <p style={{ textAlign: 'center', padding: '60px', color: 'var(--text-muted)' }}>Загрузка...</p>
      ) : (
        <>
          {/* KPI row */}
          <div style={{ display: 'flex', gap: '14px', flexWrap: 'wrap', marginBottom: '24px' }}>
            <KpiCard label="Всего заявок" value={totalOrders} />
            <KpiCard label="Закрыто" value={closedOrders} sub={`Конверсия ${conversionRate}%`} />
            <KpiCard label="Выручка" value={`${totalRevenue.toLocaleString('ru-RU')} ₽`} />
            <KpiCard label="Средний чек" value={avgDeal > 0 ? `${avgDeal.toLocaleString('ru-RU')} ₽` : '—'} />
          </div>

          {/* Charts grid */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))', gap: '18px' }}>
            <div className="glass-panel" style={{ padding: '22px' }}><FunnelChart data={funnelData} /></div>
            <div className="glass-panel" style={{ padding: '22px' }}><RevenueChart data={revenueByMonth} /></div>
            <div className="glass-panel" style={{ padding: '22px' }}><ObjectTypeChart data={byObjectType} /></div>
            <div className="glass-panel" style={{ padding: '22px' }}><AvgTimeChart data={avgTimeData} /></div>
          </div>
        </>
      )}
    </div>
  );
};

export default AnalyticsDashboard;
