'use client';

import { useState } from 'react';
import { LayoutGrid } from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Switch } from '@/components/ui/switch';
import { useDashboardWidgets } from '@/hooks/use-dashboard-widgets';

/**
 * Modal widget picker for the dashboard header. Replaced the original
 * dropdown menu because 13 widgets + 3 footer buttons made the dropdown
 * cramped and hid the descriptions reps need to know what each card
 * actually shows.
 *
 * Backed by the same `useDashboardWidgets` hook that drives the
 * Settings card — toggles update both surfaces optimistically.
 */
export function CustomizeWidgetsMenu() {
  const [open, setOpen] = useState(false);
  const { allWidgets, visibility, setVisible, setAll, resetToDefaults, isSaving } =
    useDashboardWidgets();

  const visibleCount = Object.values(visibility).filter(Boolean).length;
  const allVisible = visibleCount === allWidgets.length;
  const allHidden = visibleCount === 0;
  // Reset is a no-op when state already matches the registry defaults —
  // disable in that case to avoid pointless API round-trips.
  const matchesDefaults = allWidgets.every((w) => (visibility[w.id] ?? false) === w.defaultVisible);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" className="gap-1.5">
          <LayoutGrid className="h-4 w-4" aria-hidden />
          Customize
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-xl">
        <DialogHeader>
          <DialogTitle>Customize dashboard</DialogTitle>
          <DialogDescription>
            Pick which analytics cards appear on your dashboard. Hidden cards leave no empty space -
            the layout reflows to fill the available width.
          </DialogDescription>
        </DialogHeader>

        {/* Toggle list. Capped at ~60vh with internal scroll so the modal
            doesn't push the action footer off-screen on shorter viewports. */}
        <div className="max-h-[60vh] -mx-2 overflow-y-auto px-2">
          <div className="space-y-1 py-1">
            {allWidgets.map((w) => (
              <label
                key={w.id}
                className="flex cursor-pointer items-start justify-between gap-4 rounded-md px-3 py-2.5 hover:bg-accent/40"
              >
                <div className="min-w-0 flex-1">
                  <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)}
                  className="mt-0.5 shrink-0"
                />
              </label>
            ))}
          </div>
        </div>

        {/* Footer: stacks vertically on mobile (counter row, secondary
            buttons row, full-width primary "Done") so no button gets
            orphaned beneath the others. Reverts to single inline row at
            sm+ where there's space. */}
        <DialogFooter className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-2">
          <span className="text-xs text-muted-foreground sm:order-first">
            {visibleCount} of {allWidgets.length} visible
          </span>
          <div className="flex flex-wrap items-center gap-2 sm:flex-nowrap">
            <Button
              variant="ghost"
              size="sm"
              disabled={matchesDefaults || isSaving}
              onClick={resetToDefaults}
            >
              Reset to defaults
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={allHidden || isSaving}
              onClick={() => setAll(false)}
            >
              Hide all
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={allVisible || isSaving}
              onClick={() => setAll(true)}
            >
              Show all
            </Button>
            <Button size="sm" onClick={() => setOpen(false)} className="w-full sm:w-auto">
              Done
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
