'use client';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { useDashboardWidgets } from '@/hooks/use-dashboard-widgets';

/**
 * Per-user toggle list for dashboard widgets. The dashboard reads the
 * same `useDashboardWidgets` hook, so flipping a switch here causes the
 * dashboard to reflow on the next visit (or instantly if the user has
 * both pages open in different tabs — TanStack Query's optimistic
 * update + invalidate handles the cache sync).
 *
 * Mounted from UserSettings under the id `dashboard` so the dashboard
 * "Customize" button can deep-link via `/settings#dashboard`.
 */
export function DashboardWidgetsCard() {
  const { allWidgets, visibility, setVisible, setAll, isSaving } = useDashboardWidgets();

  const visibleCount = Object.values(visibility).filter(Boolean).length;
  const allVisible = visibleCount === allWidgets.length;
  const allHidden = visibleCount === 0;

  return (
    <Card id="dashboard">
      <CardHeader>
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <CardTitle>Dashboard widgets</CardTitle>
            <CardDescription>
              Pick which cards show up on your dashboard. Hidden cards leave no empty space — the
              layout reflows to fill the available width.
            </CardDescription>
          </div>
          <div className="flex shrink-0 items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setAll(true)}
              disabled={allVisible || isSaving}
            >
              Show all
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setAll(false)}
              disabled={allHidden || isSaving}
            >
              Hide all
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-1">
        {allWidgets.map((w) => (
          <div
            key={w.id}
            className="flex items-start justify-between gap-4 rounded-md px-3 py-2 hover:bg-accent/40"
          >
            <div className="min-w-0">
              <div className="text-sm font-medium text-foreground">{w.label}</div>
              <p className="text-xs text-muted-foreground">{w.description}</p>
            </div>
            <Switch
              aria-label={`Show ${w.label}`}
              checked={visibility[w.id] ?? false}
              disabled={isSaving}
              onCheckedChange={(checked) => setVisible(w.id, checked)}
            />
          </div>
        ))}
      </CardContent>
    </Card>
  );
}
