// [REQ F9]  Analityka i raportowanie – statystyki rezerwacji, wykresy, eksport CSV
// [REQ D6]  Render props – DataRenderer z children jako funkcja
// [REQ T6]  Optymalizacja – useMemo dla obliczania statystyk
// [REQ T7]  Wzorce kompozycji – DataRenderer (render props) użyty do pobierania danych
import { useMemo } from 'react';
import { TrendingUp, DollarSign, Calendar, Users, CheckCircle2, XCircle, Clock, Download } from 'lucide-react';
import DataRenderer from './DataRenderer';
import { API_URL } from '../config';
import styles from './AnalyticsDashboard.module.scss';

const fetchServices = () =>
  fetch(`${API_URL}/services`).then((r) => r.json());

const StatCard = ({ icon: Icon, label, value, sub, accent }) => (
  <div className={[styles['stat'], accent ? styles[`stat--${accent}`] : ''].join(' ')}>
    <div className={styles['stat__icon']}><Icon size={20} /></div>
    <div className={styles['stat__body']}>
      <p className={styles['stat__value']}>{value}</p>
      <p className={styles['stat__label']}>{label}</p>
      {sub && <p className={styles['stat__sub']}>{sub}</p>}
    </div>
  </div>
);

const BarChart = ({ data, maxValue }) => (
  <div className={styles['bar-chart']}>
    {data.map(({ label, value, color }) => (
      <div key={label} className={styles['bar-chart__row']}>
        <span className={styles['bar-chart__label']}>{label}</span>
        <div className={styles['bar-chart__track']}>
          <div
            className={styles['bar-chart__fill']}
            style={{ width: `${maxValue ? (value / maxValue) * 100 : 0}%`, background: color }}
          />
        </div>
        <span className={styles['bar-chart__val']}>{value}</span>
      </div>
    ))}
  </div>
);

const AnalyticsDashboard = ({ reservations }) => {
  // useMemo do obliczania statystyk rezerwacji na podstawie danych reservations
  // , aby nie przeliczać ich przy każdym renderze komponentu
  // , tylko wtedy gdy zmieni się props reservations
  const stats = useMemo(() => {
    const total    = reservations.length;
    const pending  = reservations.filter((r) => r.status === 'pending').length;
    const confirmed= reservations.filter((r) => r.status === 'confirmed').length;
    const cancelled= reservations.filter((r) => r.status === 'cancelled').length;
    const revenue  = reservations.reduce((s, r) => s + Number(r.depositPaid ?? 0), 0);

    // Bookings per month (last 6 months)
    const monthly = {};
    reservations.forEach((r) => {
      const month = r.date?.slice(0, 7);
      if (month) monthly[month] = (monthly[month] ?? 0) + 1;
    });
    const monthlyData = Object.entries(monthly)
      .sort(([a], [b]) => a.localeCompare(b))
      .slice(-6)
      .map(([month, count]) => ({
        label: month,
        value: count,
        color: 'var(--clr-primary, #1e5f9a)',
      }));

    // By service
    const byService = {};
    reservations.forEach((r) => {
      byService[r.serviceId] = (byService[r.serviceId] ?? 0) + 1;
    });

    return { total, pending, confirmed, cancelled, revenue, monthlyData, byService };
  }, [reservations]);

  const maxMonthly = Math.max(...(stats.monthlyData.map((d) => d.value)), 1);

  const exportCSV = () => {
    const rows = [
      ['ID', 'User ID', 'Service ID', 'Date', 'Time', 'Status', 'Deposit Paid'],
      ...reservations.map((r) => [r.id, r.userId, r.serviceId, r.date, r.time, r.status, r.depositPaid ?? 0]),
    ];
    const csv = rows.map((r) => r.join(',')).join('\n');
    const a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = `reservations-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
  };

  return (
    <DataRenderer
      queryKey={['services']}
      queryFn={fetchServices}
    >
      {({ data: services = [] }) => {
        const serviceData = Object.entries(stats.byService).map(([id, count]) => ({
          label: services.find((s) => s.id === id)?.name ?? id,
          value: count,
          color: '#059669',
        })).sort((a, b) => b.value - a.value);

        return (
          <div className={styles['analytics']}>
            {/* Export */}
            <div className={styles['analytics__toolbar']}>
              <button className={styles['analytics__export-btn']} onClick={exportCSV}>
                <Download size={14} /> Export CSV
              </button>
            </div>

            {/* Stat cards */}
            <div className={styles['analytics__cards']}>
              <StatCard icon={Calendar}    label="Total reservations" value={stats.total}     accent="blue" />
              <StatCard icon={Clock}       label="Pending"            value={stats.pending}   accent="yellow" />
              <StatCard icon={CheckCircle2}label="Confirmed"          value={stats.confirmed} accent="green" />
              <StatCard icon={XCircle}     label="Cancelled"          value={stats.cancelled} accent="red" />
              <StatCard
                icon={DollarSign}
                label="Total deposit revenue"
                value={`$${stats.revenue.toFixed(2)}`}
                sub="Sum of all deposit payments"
                accent="blue"
              />
              <StatCard
                icon={TrendingUp}
                label="Occupancy rate"
                value={`${stats.total ? Math.round(((stats.confirmed + stats.pending) / stats.total) * 100) : 0}%`}
                sub="Non-cancelled reservations"
                accent="green"
              />
            </div>

            {/* Charts */}
            <div className={styles['analytics__charts']}>
              <div className={styles['analytics__chart-box']}>
                <h4 className={styles['analytics__chart-title']}>
                  <TrendingUp size={14} /> Bookings by month
                </h4>
                {stats.monthlyData.length > 0 ? (
                  <BarChart data={stats.monthlyData} maxValue={maxMonthly} />
                ) : (
                  <p className={styles['analytics__empty']}>No data yet.</p>
                )}
              </div>

              <div className={styles['analytics__chart-box']}>
                <h4 className={styles['analytics__chart-title']}>
                  <Users size={14} /> Bookings by service
                </h4>
                {serviceData.length > 0 ? (
                  <BarChart
                    data={serviceData}
                    maxValue={Math.max(...serviceData.map((d) => d.value), 1)}
                  />
                ) : (
                  <p className={styles['analytics__empty']}>No data yet.</p>
                )}
              </div>
            </div>
          </div>
        );
      }}
    </DataRenderer>
  );
};

export default AnalyticsDashboard;
