'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import toast from 'react-hot-toast';
import { Download, RefreshCw, Radio } from 'lucide-react';
import type { StoreReport } from '@/lib/reports/storeReport';
import { getApiErrorMessage } from '@/lib/utils/apiError';
import ReportFilters, {
  DEFAULT_REPORT_FILTERS,
  SECTION_OPTIONS,
  filtersToQuery,
  type FilterOptions,
  type ReportFilterState,
} from './ReportFilters';
import ReportSections from './ReportSections';
import ReportSkeleton from './ReportSkeleton';

// Auto-refresh choices (seconds; 0 = off). Every refresh re-runs the report
// against the live database — nothing is cached server-side.
const REFRESH_CHOICES = [
  { value: 0, label: 'Off' },
  { value: 30, label: '30 sec' },
  { value: 60, label: '1 min' },
  { value: 300, label: '5 min' },
];

function clockTime(iso: string): string {
  return new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}

export default function ReportsContent({ canExport }: { canExport: boolean }) {
  const [filters, setFilters] = useState<ReportFilterState>(DEFAULT_REPORT_FILTERS);
  const [options, setOptions] = useState<FilterOptions | null>(null);
  const [report, setReport] = useState<StoreReport | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshEvery, setRefreshEvery] = useState(60);
  const [downloading, setDownloading] = useState(false);

  const query = filtersToQuery(filters);
  const noSections = filters.sections.length === 0;
  const seq = useRef(0);
  const abortRef = useRef<AbortController | null>(null);

  // Filter dropdown options (categories, cities, coupons) — once.
  useEffect(() => {
    let cancelled = false;
    fetch('/api/reports/filters', { credentials: 'include' })
      .then((r) => r.json())
      .then((json) => { if (!cancelled && json.success) setOptions(json.data); })
      .catch(() => { /* dropdowns just stay empty; the report still works */ });
    return () => { cancelled = true; };
  }, []);

  const load = useCallback(async (q: string) => {
    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    const mySeq = ++seq.current;
    setLoading(true);
    try {
      const res = await fetch(`/api/reports?${q}`, { credentials: 'include', cache: 'no-store', signal: controller.signal });
      const json = await res.json();
      if (mySeq !== seq.current) return; // a newer request has started
      if (!res.ok || !json.success) {
        setError(getApiErrorMessage(json, 'Failed to load the report'));
        return;
      }
      setReport(json.data);
      setError(null);
    } catch (err) {
      if ((err as Error).name === 'AbortError') return;
      if (mySeq === seq.current) setError('Could not reach the server. Check your connection and try again.');
    } finally {
      if (mySeq === seq.current) setLoading(false);
    }
  }, []);

  // Re-run whenever the filters change (short debounce so quick clicks in a
  // multi-select don't fire one request each).
  useEffect(() => {
    if (noSections) return;
    const t = setTimeout(() => load(query), 250);
    return () => clearTimeout(t);
  }, [query, noSections, load]);

  // Live auto-refresh; paused while the tab is hidden, catches up on return.
  useEffect(() => {
    if (!refreshEvery || noSections) return;
    const tick = () => { if (document.visibilityState === 'visible') load(query); };
    const id = setInterval(tick, refreshEvery * 1000);
    const onVisible = () => {
      if (document.visibilityState !== 'visible' || !report) return;
      if (Date.now() - new Date(report.meta.generatedAt).getTime() > refreshEvery * 1000) load(query);
    };
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      clearInterval(id);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, [refreshEvery, query, noSections, load, report]);

  useEffect(() => () => abortRef.current?.abort(), []);

  const downloadPdf = async () => {
    setDownloading(true);
    try {
      const res = await fetch(`/api/reports/pdf?${query}`, { credentials: 'include', cache: 'no-store' });
      if (!res.ok) {
        const json = await res.json().catch(() => null);
        toast.error(getApiErrorMessage(json, 'Failed to generate the PDF'));
        return;
      }
      const blob = await res.blob();
      const name = /filename="([^"]+)"/.exec(res.headers.get('Content-Disposition') ?? '')?.[1] ?? 'store-report.pdf';
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = name;
      document.body.appendChild(a);
      a.click();
      a.remove();
      setTimeout(() => URL.revokeObjectURL(url), 1000);
      toast.success('PDF downloaded');
    } catch {
      toast.error('Could not reach the server. Check your connection and try again.');
    } finally {
      setDownloading(false);
    }
  };

  const shown = report ? SECTION_OPTIONS.filter((s) => report.sections[s.id as keyof StoreReport['sections']]) : [];

  return (
    <div className="space-y-5">
      {/* Live status + actions */}
      <div className="flex flex-wrap items-center gap-2">
        <span
          className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium"
          style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}
        >
          <Radio size={13} style={{ color: refreshEvery ? '#059669' : 'var(--color-text-secondary)' }} />
          {report ? `Updated ${clockTime(report.meta.generatedAt)}` : 'Loading…'}
          {refreshEvery ? ' · live' : ''}
        </span>
        <label className="inline-flex items-center gap-1.5 text-xs" style={{ color: 'var(--color-text-secondary)' }}>
          Auto-refresh
          <select
            value={refreshEvery}
            onChange={(e) => setRefreshEvery(Number(e.target.value))}
            className="px-2 py-1.5 rounded-lg text-xs outline-none"
            style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
          >
            {REFRESH_CHOICES.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
          </select>
        </label>
        <div className="flex gap-2 ml-auto">
          <button
            type="button"
            onClick={() => load(query)}
            disabled={loading || noSections}
            className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium disabled:opacity-50"
            style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
          >
            <RefreshCw size={15} className={loading ? 'animate-spin' : ''} /> Refresh
          </button>
          {canExport && (
            <button
              type="button"
              onClick={downloadPdf}
              disabled={downloading || noSections || !report}
              className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium text-white disabled:opacity-50"
              style={{ background: 'var(--color-cta)' }}
            >
              <Download size={15} className={downloading ? 'animate-bounce' : ''} />
              {downloading ? 'Generating…' : 'Download PDF'}
            </button>
          )}
        </div>
      </div>

      <ReportFilters value={filters} onChange={setFilters} options={options} loading={loading} />

      {/* Jump links */}
      {shown.length > 1 && (
        <nav className="flex gap-1.5 overflow-x-auto pb-1 -mx-1 px-1" aria-label="Report sections">
          {shown.map((s) => (
            <a
              key={s.id}
              href={`#report-${s.id}`}
              className="shrink-0 px-2.5 py-1 rounded-full text-xs font-medium"
              style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}
            >
              {s.label}
            </a>
          ))}
        </nav>
      )}

      {noSections ? (
        <p className="p-6 rounded-xl text-sm text-center" style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text-secondary)' }}>
          Pick at least one section to build the report.
        </p>
      ) : error && !report ? (
        <div className="p-6 rounded-xl text-sm text-center space-y-3" style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}>
          <p style={{ color: '#DC2626' }}>{error}</p>
          <button type="button" onClick={() => load(query)} className="px-3 py-1.5 rounded-lg text-white text-sm" style={{ background: 'var(--color-cta)' }}>
            Try again
          </button>
        </div>
      ) : !report ? (
        <ReportSkeleton />
      ) : (
        <>
          {error && (
            <p className="text-xs px-3 py-2 rounded-lg" style={{ background: '#FEF2F2', color: '#B91C1C' }}>
              {error} Showing the last loaded figures.
            </p>
          )}
          <div className={`transition-opacity ${loading ? 'opacity-60' : ''}`}>
            <ReportSections report={report} />
          </div>
        </>
      )}
    </div>
  );
}
