import { useEffect, useMemo, useState } from "react";
import { api } from "../api.js";

interface FunnelDef {
  name: string;
  steps: string[];
}
interface FunnelResult {
  name: string;
  startDate: string;
  endDate: string;
  steps: Array<{ step: number; event: string; count: number }>;
  conversionFromFirst: Array<{ step: number; event: string; rate: number }>;
}
interface RetentionResult {
  cohorts: Record<
    string,
    { cohortSize: number; retention: Array<{ day: number; active: number; rate: number }> }
  >;
}
interface EventCountsResult {
  counts: Array<{
    date: string;
    event_name: string;
    total: number;
    unique_sessions: number;
    unique_users: number;
  }>;
}

function today() {
  return new Date().toISOString().slice(0, 10);
}
function weekAgo() {
  const d = new Date();
  d.setUTCDate(d.getUTCDate() - 7);
  return d.toISOString().slice(0, 10);
}

export function AnalyticsPage() {
  const [funnels, setFunnels] = useState<FunnelDef[]>([]);
  const [funnelName, setFunnelName] = useState<string>("");
  const [funnelStart, setFunnelStart] = useState<string>(weekAgo());
  const [funnelEnd, setFunnelEnd] = useState<string>(today());
  const [funnelResult, setFunnelResult] = useState<FunnelResult | null>(null);

  const [retStart, setRetStart] = useState<string>(weekAgo());
  const [retEnd, setRetEnd] = useState<string>(today());
  const [retention, setRetention] = useState<RetentionResult | null>(null);

  const [countsStart, setCountsStart] = useState<string>(weekAgo());
  const [countsEnd, setCountsEnd] = useState<string>(today());
  const [counts, setCounts] = useState<EventCountsResult | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    api<{ funnels: FunnelDef[] }>("/admin/v1/analytics/funnels")
      .then((res) => {
        setFunnels(res.funnels);
        if (res.funnels[0]) setFunnelName(res.funnels[0].name);
      })
      .catch((e) => setError(String(e.message)));
  }, []);

  const loadFunnel = () => {
    if (!funnelName) return;
    api<FunnelResult>(
      `/admin/v1/analytics/funnels/${encodeURIComponent(funnelName)}?startDate=${funnelStart}&endDate=${funnelEnd}`,
    )
      .then(setFunnelResult)
      .catch((e) => setError(String(e.message)));
  };

  const loadRetention = () => {
    api<RetentionResult>(
      `/admin/v1/analytics/retention?startDate=${retStart}&endDate=${retEnd}`,
    )
      .then(setRetention)
      .catch((e) => setError(String(e.message)));
  };

  const loadCounts = () => {
    api<EventCountsResult>(
      `/admin/v1/analytics/event-counts?startDate=${countsStart}&endDate=${countsEnd}`,
    )
      .then(setCounts)
      .catch((e) => setError(String(e.message)));
  };

  const countsByEvent = useMemo(() => {
    if (!counts) return [];
    const grouped = new Map<string, { dates: string[]; totals: number[] }>();
    for (const row of counts.counts) {
      const existing = grouped.get(row.event_name);
      if (!existing) {
        grouped.set(row.event_name, { dates: [row.date], totals: [Number(row.total)] });
      } else {
        existing.dates.push(row.date);
        existing.totals.push(Number(row.total));
      }
    }
    return Array.from(grouped.entries()).map(([event, data]) => ({ event, ...data }));
  }, [counts]);

  return (
    <div>
      <h2>Analytics</h2>
      {error && <div className="error-text">{error}</div>}

      <div className="panel">
        <h3>Funnels</h3>
        <div className="form-row">
          <select value={funnelName} onChange={(e) => setFunnelName(e.target.value)}>
            {funnels.map((f) => (
              <option key={f.name} value={f.name}>
                {f.name}
              </option>
            ))}
          </select>
          <input type="date" value={funnelStart} onChange={(e) => setFunnelStart(e.target.value)} />
          <input type="date" value={funnelEnd} onChange={(e) => setFunnelEnd(e.target.value)} />
          <button onClick={loadFunnel}>Beräkna</button>
        </div>
        {funnelResult && (
          <table>
            <thead>
              <tr>
                <th>Steg</th>
                <th>Event</th>
                <th>Antal</th>
                <th>Konvertering från första</th>
              </tr>
            </thead>
            <tbody>
              {funnelResult.steps.map((s, i) => (
                <tr key={s.step}>
                  <td>{s.step}</td>
                  <td>{s.event}</td>
                  <td>{s.count}</td>
                  <td>{(funnelResult.conversionFromFirst[i]?.rate ?? 0 * 100).toFixed(1)}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <div className="panel">
        <h3>Retention</h3>
        <div className="form-row">
          <input type="date" value={retStart} onChange={(e) => setRetStart(e.target.value)} />
          <input type="date" value={retEnd} onChange={(e) => setRetEnd(e.target.value)} />
          <button onClick={loadRetention}>Ladda</button>
        </div>
        {retention && (
          <table>
            <thead>
              <tr>
                <th>Kohort</th>
                <th>Storlek</th>
                {Array.from({ length: 8 }, (_, i) => (
                  <th key={i}>Dag {i}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {Object.entries(retention.cohorts).map(([date, cohort]) => (
                <tr key={date}>
                  <td>{date}</td>
                  <td>{cohort.cohortSize}</td>
                  {cohort.retention.slice(0, 8).map((r) => (
                    <td key={r.day}>{(r.rate * 100).toFixed(0)}%</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <div className="panel">
        <h3>Eventvolymer</h3>
        <div className="form-row">
          <input type="date" value={countsStart} onChange={(e) => setCountsStart(e.target.value)} />
          <input type="date" value={countsEnd} onChange={(e) => setCountsEnd(e.target.value)} />
          <button onClick={loadCounts}>Ladda</button>
        </div>
        {countsByEvent.map(({ event, dates, totals }) => (
          <div key={event} style={{ marginTop: "1rem" }}>
            <strong>{event}</strong>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fill, minmax(120px, 1fr))",
                gap: "0.5rem",
              }}
            >
              {dates.map((d, i) => (
                <div key={d} className="stat" style={{ padding: "0.5rem" }}>
                  <div className="value">{totals[i]}</div>
                  <div className="label">{d.slice(5)}</div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
