'use client';

import { useEffect, useState } from 'react';
import { Loader2, AlertTriangle, RefreshCw, ArrowLeft } from 'lucide-react';
import Link from 'next/link';
import { cn } from '@/lib/utils';
import { BrandStatsCard, type BrandStatsCardProps } from '@/modules/stats/ui/BrandStatsCard';

type BrandRow = BrandStatsCardProps['workspace'];

interface DashboardResponse {
  ok: boolean;
  days: number;
  since: string;
  workspaces: BrandRow[];
}

const RANGES = [
  { days: 7, label: '7 Tage' },
  { days: 30, label: '30 Tage' },
  { days: 90, label: '90 Tage' },
] as const;

export default function DashboardPage() {
  const [days, setDays] = useState<7 | 30 | 90>(30);
  const [data, setData] = useState<DashboardResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = async (rangeDays: number) => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/dashboard/workspace-stats?days=${rangeDays}`);
      const json = (await res.json()) as DashboardResponse | { error: string };
      if (!res.ok || !('ok' in json) || !json.ok) {
        setError('error' in json ? json.error : `HTTP ${res.status}`);
        return;
      }
      setData(json);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Network error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load(days);
  }, [days]);

  return (
    <div className="mx-auto max-w-6xl px-4 py-6">
      {/* Header */}
      <div className="mb-6 flex items-center justify-between">
        <div>
          <Link
            href="/"
            className="inline-flex items-center gap-1 text-xs text-zinc-500 hover:text-zinc-700 dark:hover:text-zinc-300"
          >
            <ArrowLeft className="h-3 w-3" /> Zurück zum Builder
          </Link>
          <h1 className="mt-1 text-2xl font-bold tracking-tight text-zinc-900 dark:text-zinc-100">
            Workspace-Dashboard
          </h1>
          <p className="text-xs text-zinc-500">
            Aggregierte Email-Performance pro Workspace über alle Campaigns.
          </p>
        </div>
        <div className="flex items-center gap-3">
          {/* Range-Switcher */}
          <div className="flex rounded-md border border-zinc-200 bg-white p-0.5 dark:border-zinc-700 dark:bg-zinc-900">
            {RANGES.map((r) => (
              <button
                key={r.days}
                type="button"
                onClick={() => setDays(r.days)}
                className={cn(
                  'rounded px-2.5 py-1 text-xs font-medium transition',
                  days === r.days
                    ? 'bg-zinc-900 text-white dark:bg-zinc-100 dark:text-zinc-900'
                    : 'text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100',
                )}
              >
                {r.label}
              </button>
            ))}
          </div>
          <button
            type="button"
            onClick={() => void load(days)}
            disabled={loading}
            title="Neu laden"
            className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-200 text-zinc-600 hover:bg-zinc-50 disabled:opacity-50 dark:border-zinc-700 dark:text-zinc-300 dark:hover:bg-zinc-800"
          >
            {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
          </button>
        </div>
      </div>

      {/* Error / Empty State */}
      {error && (
        <div className="mb-4 flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-800 dark:border-red-900/50 dark:bg-red-950/30">
          <AlertTriangle className="mt-0.5 h-4 w-4" />
          <span className="flex-1">{error}</span>
        </div>
      )}

      {!data && loading && (
        <div className="flex items-center gap-2 text-sm text-zinc-500">
          <Loader2 className="h-4 w-4 animate-spin" /> Lade Workspace-Stats …
        </div>
      )}

      {/* Cards-Grid */}
      {data && (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
          {data.workspaces.map((b) => (
            <BrandStatsCard key={b.workspaceSlug} workspace={b} />
          ))}
        </div>
      )}

      {data && data.workspaces.length === 0 && (
        <div className="rounded-md border border-dashed border-zinc-200 bg-zinc-50/50 p-6 text-center text-sm text-zinc-500 dark:border-zinc-800 dark:bg-zinc-900/30">
          Noch keine Workspaces konfiguriert. Lege zuerst eine Workspace im Settings-Drawer an.
        </div>
      )}
    </div>
  );
}
