import { useState, useEffect, useMemo, useCallback } from 'react';
import {
  Container,
  Box,
  Fade,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
} from '@mui/material';
import {
  Edit as EditIcon,
  Check as CheckIcon,
  Add as AddIcon,
  Refresh as RefreshIcon,
} from '@mui/icons-material';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
  DndContext,
  DragOverlay,
  PointerSensor,
  useSensor,
  useSensors,
  closestCorners,
} from '@dnd-kit/core';
import type { DragEndEvent, DragStartEvent, DragOverEvent } from '@dnd-kit/core';
import {
  SortableContext,
  rectSortingStrategy,
  verticalListSortingStrategy,
  arrayMove,
} from '@dnd-kit/sortable';
import { useAuth } from '../contexts/AuthContext';
import { usePermissionContext } from '../contexts/PermissionContext';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import SkeletonCard from '../components/shared/SkeletonCard';
import UserProfile from '../components/dashboard/UserProfile';
import UpcomingEventsWidget from '../components/dashboard/UpcomingEventsWidget';
import AtemschutzDashboardCard from '../components/atemschutz/AtemschutzDashboardCard';
import EquipmentDashboardCard from '../components/equipment/EquipmentDashboardCard';
import VehicleDashboardCard from '../components/vehicles/VehicleDashboardCard';
import BookStackRecentWidget from '../components/dashboard/BookStackRecentWidget';
import BookStackSearchWidget from '../components/dashboard/BookStackSearchWidget';
import VikunjaMyTasksWidget from '../components/dashboard/VikunjaMyTasksWidget';
import VikunjaQuickAddWidget from '../components/dashboard/VikunjaQuickAddWidget';
import VikunjaOverdueNotifier from '../components/dashboard/VikunjaOverdueNotifier';
import AtemschutzExpiryNotifier from '../components/dashboard/AtemschutzExpiryNotifier';
import BuchhaltungPendingNotifier from '../components/dashboard/BuchhaltungPendingNotifier';
import AdminStatusWidget from '../components/dashboard/AdminStatusWidget';
import AnnouncementBanner from '../components/dashboard/AnnouncementBanner';
import VehicleBookingQuickAddWidget from '../components/dashboard/VehicleBookingQuickAddWidget';
import VehicleBookingListWidget from '../components/dashboard/VehicleBookingListWidget';
import EventQuickAddWidget from '../components/dashboard/EventQuickAddWidget';
import LinksWidget from '../components/dashboard/LinksWidget';
import BannerWidget from '../components/dashboard/BannerWidget';
import WidgetGroup from '../components/dashboard/WidgetGroup';
import SortableWidget from '../components/dashboard/SortableWidget';
import BestellungenWidget from '../components/dashboard/BestellungenWidget';
import AusruestungsanfrageWidget from '../components/dashboard/AusruestungsanfrageWidget';
import IssueQuickAddWidget from '../components/dashboard/IssueQuickAddWidget';
import IssueOverviewWidget from '../components/dashboard/IssueOverviewWidget';
import ChecklistWidget from '../components/dashboard/ChecklistWidget';
import BuchhaltungWidget from '../components/dashboard/BuchhaltungWidget';
import { preferencesApi } from '../services/settings';
import { configApi } from '../services/config';
import { WidgetKey } from '../constants/widgets';
import { ConfirmDialog } from '../components/templates';

// ── Widget definitions per group ──

interface WidgetDef {
  key: string;
  widgetKey?: WidgetKey;
  permission?: string;
  component: React.ReactNode;
}

const BUILTIN_GROUPS: { name: string; title: string }[] = [
  { name: 'status', title: 'Status' },
  { name: 'kalender', title: 'Kalender' },
  { name: 'dienste', title: 'Dienste' },
  { name: 'information', title: 'Information' },
];

// Default widget order per group (used when no preference is set)
const DEFAULT_ORDER: Record<string, string[]> = {
  status: ['vehicles', 'equipment', 'atemschutz', 'adminStatus', 'bestellungen', 'ausruestungsanfragen', 'issueOverview', 'checklistOverdue', 'buchhaltung'],
  kalender: ['events', 'vehicleBookingList', 'vehicleBooking', 'eventQuickAdd'],
  dienste: ['bookstackRecent', 'bookstackSearch', 'vikunjaTasks', 'vikunjaQuickAdd', 'issueQuickAdd'],
  information: ['links', 'bannerWidget'],
};

function Dashboard() {
  const { user } = useAuth();
  const { hasPermission } = usePermissionContext();
  const queryClient = useQueryClient();
  const [dataLoading, setDataLoading] = useState(true);
  const [editMode, setEditMode] = useState(false);
  const [activeId, setActiveId] = useState<string | null>(null);
  const [addGroupOpen, setAddGroupOpen] = useState(false);
  const [newGroupTitle, setNewGroupTitle] = useState('');
  const [resetOpen, setResetOpen] = useState(false);
  const [localGroupOrder, setLocalGroupOrder] = useState<string[]>(BUILTIN_GROUPS.map(g => g.name));

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
  );

  const { data: preferences } = useQuery({
    queryKey: ['user-preferences'],
    queryFn: preferencesApi.get,
  });

  const { data: externalLinks } = useQuery({
    queryKey: ['external-links'],
    queryFn: () => configApi.getExternalLinks(),
    staleTime: 10 * 60 * 1000,
  });

  const linkCollections = (externalLinks?.linkCollections ?? []).filter(
    (c) => c.links.length > 0
  );

  const widgetVisible = (key: WidgetKey) => {
    return preferences?.widgets?.[key] !== false;
  };

  // Build widget definitions for each group
  const widgetDefs: Record<string, WidgetDef[]> = useMemo(() => ({
    status: [
      { key: 'vehicles', widgetKey: 'vehicles', permission: 'fahrzeuge:widget', component: <VehicleDashboardCard /> },
      { key: 'equipment', widgetKey: 'equipment', permission: 'ausruestung:widget', component: <EquipmentDashboardCard /> },
      { key: 'atemschutz', widgetKey: 'atemschutz', permission: 'atemschutz:widget', component: <AtemschutzDashboardCard /> },
      { key: 'adminStatus', widgetKey: 'adminStatus', permission: 'admin:view', component: <AdminStatusWidget /> },
      { key: 'bestellungen', widgetKey: 'bestellungen', permission: 'bestellungen:widget', component: <BestellungenWidget /> },
      { key: 'ausruestungsanfragen', widgetKey: 'ausruestungsanfragen', permission: 'ausruestungsanfrage:widget', component: <AusruestungsanfrageWidget /> },
      { key: 'issueOverview', widgetKey: 'issueOverview', permission: 'issues:view_all', component: <IssueOverviewWidget /> },
      { key: 'checklistOverdue', widgetKey: 'checklistOverdue', permission: 'checklisten:widget', component: <ChecklistWidget /> },
      { key: 'buchhaltung', widgetKey: 'buchhaltung', permission: 'buchhaltung:widget', component: <BuchhaltungWidget /> },
    ],
    kalender: [
      { key: 'events', widgetKey: 'events', permission: 'kalender:view', component: <UpcomingEventsWidget /> },
      { key: 'vehicleBookingList', widgetKey: 'vehicleBookingList', permission: 'fahrzeugbuchungen:view', component: <VehicleBookingListWidget /> },
      { key: 'vehicleBooking', widgetKey: 'vehicleBooking', permission: 'fahrzeugbuchungen:manage', component: <VehicleBookingQuickAddWidget /> },
      { key: 'eventQuickAdd', widgetKey: 'eventQuickAdd', permission: 'kalender:create', component: <EventQuickAddWidget /> },
    ],
    dienste: [
      { key: 'bookstackRecent', widgetKey: 'bookstackRecent', permission: 'wissen:view', component: <BookStackRecentWidget /> },
      { key: 'bookstackSearch', widgetKey: 'bookstackSearch', permission: 'wissen:view', component: <BookStackSearchWidget /> },
      { key: 'vikunjaTasks', widgetKey: 'vikunjaTasks', permission: 'vikunja:widget_tasks', component: <VikunjaMyTasksWidget /> },
      { key: 'vikunjaQuickAdd', widgetKey: 'vikunjaQuickAdd', permission: 'vikunja:widget_quick_add', component: <VikunjaQuickAddWidget /> },
      { key: 'issueQuickAdd', widgetKey: 'issueQuickAdd', permission: 'issues:widget', component: <IssueQuickAddWidget /> },
    ],
    information: [
      // Links are handled specially (dynamic collections), but we keep a placeholder
      { key: 'links', widgetKey: 'links', permission: 'dashboard:widget_links', component: null },
      { key: 'bannerWidget', permission: 'dashboard:widget_banner', component: <BannerWidget /> },
    ],
  }), []);

  // Widget order from preferences, falling back to defaults
  const [localOrder, setLocalOrder] = useState<Record<string, string[]>>(DEFAULT_ORDER);
  const [localCustomGroups, setLocalCustomGroups] = useState<{ name: string; title: string }[]>([]);

  // Always persist the FULL preferences object to avoid wiping unrelated fields (widgets, menuOrder, etc.)
  const savePreferences = useCallback((patch: Record<string, unknown>) => {
    const full = { ...(preferences ?? {}), ...patch };
    queryClient.setQueryData(['user-preferences'], full);
    preferencesApi.update(full);
  }, [preferences, queryClient]);

  useEffect(() => {
    if (preferences?.widgetOrder) {
      setLocalOrder((prev) => {
        const merged = { ...prev };

        // Build a set of all widget keys that are explicitly placed in some saved group
        const allSavedKeys = new Set<string>();
        for (const groupKeys of Object.values(preferences.widgetOrder)) {
          for (const k of (groupKeys as string[])) allSavedKeys.add(k);
        }

        // Widgets in custom groups take priority — don't let built-in groups claim them
        const customGroupKeys = new Set<string>();
        if (preferences.customGroups) {
          for (const cg of preferences.customGroups as { name: string; title: string }[]) {
            const cgOrder = preferences.widgetOrder[cg.name] as string[] | undefined;
            if (cgOrder) { for (const k of cgOrder) customGroupKeys.add(k); }
          }
        }

        for (const group of Object.keys(DEFAULT_ORDER)) {
          if (preferences.widgetOrder[group]) {
            // Merge: saved order first (excluding custom-group widgets), then new widgets
            const saved = preferences.widgetOrder[group] as string[];
            const allKeys = DEFAULT_ORDER[group];
            const ordered = saved.filter((k: string) => allKeys.includes(k) && !customGroupKeys.has(k));
            const remaining = allKeys.filter((k) => !allSavedKeys.has(k));
            merged[group] = [...new Set([...ordered, ...remaining])];
          }
        }
        // Include custom groups from preferences
        if (preferences.customGroups) {
          for (const cg of preferences.customGroups as { name: string; title: string }[]) {
            if (!merged[cg.name]) merged[cg.name] = [];
            if (preferences.widgetOrder[cg.name]) {
              merged[cg.name] = [...new Set(preferences.widgetOrder[cg.name] as string[])];
            }
          }
        }
        return merged;
      });

      // Sync local custom groups
      setLocalCustomGroups((preferences.customGroups as { name: string; title: string }[]) ?? []);

      // Sync group order from preferences
      const customGroupNames = (preferences.customGroups as { name: string; title: string }[] | undefined ?? []).map(g => g.name);
      const allGroupNames = [...BUILTIN_GROUPS.map(g => g.name), ...customGroupNames];
      const savedGroupOrder = preferences.groupsOrder as string[] | undefined;
      if (savedGroupOrder) {
        const ordered = savedGroupOrder.filter((n: string) => allGroupNames.includes(n));
        const remaining = allGroupNames.filter(n => !ordered.includes(n));
        setLocalGroupOrder([...ordered, ...remaining]);
      } else {
        setLocalGroupOrder(allGroupNames);
      }
    }
  }, [preferences?.widgetOrder, preferences?.customGroups, preferences?.groupsOrder]);

  // Flat map of all widget defs for cross-group lookup
  const allWidgetDefs = useMemo(() => {
    const map = new Map<string, WidgetDef>();
    for (const defs of Object.values(widgetDefs)) {
      for (const d of defs) map.set(d.key, d);
    }
    return map;
  }, [widgetDefs]);

  // Get sorted + filtered widgets for a group
  const getVisibleWidgets = useCallback((group: string) => {
    const order = localOrder[group] || [];
    return order
      .map((key) => allWidgetDefs.get(key))
      .filter((d): d is WidgetDef => {
        if (!d) return false;
        if (d.permission && !hasPermission(d.permission)) return false;
        if (d.widgetKey && !widgetVisible(d.widgetKey)) return false;
        return true;
      });
  }, [localOrder, allWidgetDefs, hasPermission, preferences]);

  // Find which group a widget key belongs to
  const findGroupForWidget = useCallback((widgetId: string): string | undefined => {
    for (const group of Object.keys(localOrder)) {
      if (localOrder[group].includes(widgetId)) return group;
    }
    return undefined;
  }, [localOrder]);

  const handleDragStart = useCallback((event: DragStartEvent) => {
    setActiveId(event.active.id as string);
  }, []);

  const handleDragOver = useCallback((event: DragOverEvent) => {
    const { active, over } = event;
    if (!over) return;

    // Skip group-level drags
    if ((active.id as string).startsWith('group:')) return;

    const activeWidget = active.id as string;
    const overId = over.id as string;

    const sourceGroup = findGroupForWidget(activeWidget);
    // over.id could be a widget key or a group droppable id (prefixed "group-")
    let targetGroup: string | undefined;
    if (overId.startsWith('group-')) {
      targetGroup = overId.replace('group-', '');
    } else {
      targetGroup = findGroupForWidget(overId);
    }

    if (!sourceGroup || !targetGroup || sourceGroup === targetGroup) return;

    // Move widget from source group to target group during drag (live preview)
    setLocalOrder((prev) => {
      const sourceItems = prev[sourceGroup].filter((k) => k !== activeWidget);
      const targetItems = [...prev[targetGroup!]];
      // Insert at the position of the over item, or at end if dropped on group
      const overIndex = targetItems.indexOf(overId);
      if (overIndex >= 0) {
        targetItems.splice(overIndex, 0, activeWidget);
      } else {
        targetItems.push(activeWidget);
      }
      return { ...prev, [sourceGroup]: sourceItems, [targetGroup!]: targetItems };
    });
  }, [findGroupForWidget]);

  const handleDragEnd = useCallback((event: DragEndEvent) => {
    setActiveId(null);
    const { active, over } = event;
    if (!over || active.id === over.id) return;

    const activeIdStr = active.id as string;
    const overIdStr = over.id as string;

    // Group reorder
    if (activeIdStr.startsWith('group:') && overIdStr.startsWith('group:')) {
      const sourceName = activeIdStr.replace('group:', '');
      const targetName = overIdStr.replace('group:', '');
      const oldIndex = localGroupOrder.indexOf(sourceName);
      const newIndex = localGroupOrder.indexOf(targetName);
      if (oldIndex === -1 || newIndex === -1) return;
      const newOrder = arrayMove(localGroupOrder, oldIndex, newIndex);
      setLocalGroupOrder(newOrder);
      savePreferences({ widgetOrder: localOrder, groupsOrder: newOrder });
      return;
    }

    const activeWidget = activeIdStr;

    const sourceGroup = findGroupForWidget(activeWidget);
    let targetGroup: string | undefined;
    if (overIdStr.startsWith('group-')) {
      targetGroup = overIdStr.replace('group-', '');
    } else {
      targetGroup = findGroupForWidget(overIdStr);
    }

    if (!sourceGroup || !targetGroup) return;

    if (sourceGroup === targetGroup) {
      // Same group reorder
      const order = localOrder[sourceGroup];
      const oldIndex = order.indexOf(activeWidget);
      const newIndex = order.indexOf(overIdStr);
      if (oldIndex !== -1 && newIndex !== -1) {
        const newOrder = arrayMove(order, oldIndex, newIndex);
        setLocalOrder((prev) => ({ ...prev, [sourceGroup]: newOrder }));
      }
    }
    // Cross-group move was already handled in handleDragOver
    // Persist current state using a timeout to read the latest localOrder after state updates
    setTimeout(() => {
      setLocalOrder((current) => {
        savePreferences({ widgetOrder: current });
        return current;
      });
    }, 0);
  }, [localOrder, localGroupOrder, savePreferences, findGroupForWidget]);

  // ── Add custom group ──
  const handleAddGroup = useCallback(() => {
    const title = newGroupTitle.trim();
    if (!title) return;
    const name = title.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_');

    // Guard duplicate
    const existingGroups = [...BUILTIN_GROUPS, ...localCustomGroups];
    if (existingGroups.some((g) => g.name === name)) return;

    const updatedCustomGroups = [...localCustomGroups, { name, title }];
    const updatedOrder = { ...localOrder, [name]: [] };
    const updatedGroupOrder = [...localGroupOrder, name];
    setLocalOrder(updatedOrder);
    setLocalGroupOrder(updatedGroupOrder);
    setLocalCustomGroups(updatedCustomGroups);
    savePreferences({ widgetOrder: updatedOrder, customGroups: updatedCustomGroups, groupsOrder: updatedGroupOrder });
    setNewGroupTitle('');
    setAddGroupOpen(false);
  }, [newGroupTitle, localCustomGroups, localOrder, localGroupOrder, savePreferences]);

  // ── Delete custom group — move widgets back to their default groups ──
  const handleDeleteGroup = useCallback((groupName: string) => {
    const widgetsToMove = localOrder[groupName] || [];
    const updatedOrder = { ...localOrder };
    delete updatedOrder[groupName];

    for (const widgetKey of widgetsToMove) {
      // Find original default group
      let targetGroup = 'information';
      for (const [group, keys] of Object.entries(DEFAULT_ORDER)) {
        if (keys.includes(widgetKey)) { targetGroup = group; break; }
      }
      if (!updatedOrder[targetGroup]) updatedOrder[targetGroup] = [];
      if (!updatedOrder[targetGroup].includes(widgetKey)) {
        updatedOrder[targetGroup].push(widgetKey);
      }
    }

    const updatedCustomGroups = localCustomGroups.filter((g) => g.name !== groupName);
    const updatedGroupOrder = localGroupOrder.filter(n => n !== groupName);
    setLocalOrder(updatedOrder);
    setLocalGroupOrder(updatedGroupOrder);
    setLocalCustomGroups(updatedCustomGroups);
    savePreferences({ widgetOrder: updatedOrder, customGroups: updatedCustomGroups, groupsOrder: updatedGroupOrder });
  }, [localOrder, localGroupOrder, localCustomGroups, savePreferences]);

  // ── Reset to defaults ──
  const handleReset = useCallback(() => {
    const defaultGroupOrder = BUILTIN_GROUPS.map(g => g.name);
    setLocalOrder(DEFAULT_ORDER);
    setLocalGroupOrder(defaultGroupOrder);
    setLocalCustomGroups([]);
    savePreferences({ widgetOrder: DEFAULT_ORDER, customGroups: [], groupsOrder: defaultGroupOrder });
    setResetOpen(false);
  }, [savePreferences]);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDataLoading(false);
    }, 800);
    return () => clearTimeout(timer);
  }, []);

  const baseDelay = 300;
  let delayCounter = 0;
  const nextDelay = () => `${baseDelay + (delayCounter++) * 40}ms`;

  // Render a group's widgets
  const renderGroup = (group: string, title: string) => {
    const visible = getVisibleWidgets(group);
    const keys = visible.map((d) => d.key);
    const isCustomGroup = !BUILTIN_GROUPS.some((g) => g.name === group);

    // Special handling for information group (links are dynamic)
    if (group === 'information') {
      const linksVisible = visible.some((d) => d.key === 'links');
      const bannerVisible = visible.some((d) => d.key === 'bannerWidget');
      const hasContent = (linksVisible && linkCollections.length > 0) || bannerVisible;
      if (!hasContent) return null;

      return (
        <WidgetGroup title={title} gridColumn="1 / -1" key="information" groupId="information" sortableId="group:information" editMode={editMode}>
          {linksVisible && linkCollections.map((collection) => (
            <Fade key={collection.id} in={!dataLoading} timeout={600} style={{ transitionDelay: nextDelay() }}>
              <Box>
                <LinksWidget collection={collection} />
              </Box>
            </Fade>
          ))}
          {bannerVisible && (
            <Fade in={!dataLoading} timeout={600} style={{ transitionDelay: nextDelay() }}>
              <Box>
                <BannerWidget />
              </Box>
            </Fade>
          )}
        </WidgetGroup>
      );
    }

    if (keys.length === 0 && !editMode) return null;

    return (
      <WidgetGroup
        title={title}
        gridColumn="1 / -1"
        key={group}
        groupId={group}
        sortableId={`group:${group}`}
        editMode={editMode}
        onDelete={isCustomGroup ? () => handleDeleteGroup(group) : undefined}
      >
        <SortableContext items={keys} strategy={rectSortingStrategy}>
          {visible.map((def) => {
            const delay = nextDelay();
            return (
              <SortableWidget key={def.key} id={def.key} editMode={editMode}>
                <Fade in={!dataLoading} timeout={600} style={{ transitionDelay: delay }}>
                  <Box>{def.component}</Box>
                </Fade>
              </SortableWidget>
            );
          })}
        </SortableContext>
      </WidgetGroup>
    );
  };

  // Compute the full group list: built-in + custom groups, ordered by localGroupOrder
  const groupOrder = useMemo(() => {
    const allGroups = [...BUILTIN_GROUPS, ...localCustomGroups.filter(cg => !BUILTIN_GROUPS.some(g => g.name === cg.name))];
    const orderedGroups = localGroupOrder
      .map(name => allGroups.find(g => g.name === name))
      .filter((g): g is { name: string; title: string } => !!g);
    const remaining = allGroups.filter(g => !localGroupOrder.includes(g.name));
    return [...orderedGroups, ...remaining];
  }, [localCustomGroups, localGroupOrder]);

  return (
    <DashboardLayout>
      <VikunjaOverdueNotifier />
      <AtemschutzExpiryNotifier />
      <BuchhaltungPendingNotifier />

      <Container maxWidth={false} disableGutters>
        <DndContext
          sensors={sensors}
          collisionDetection={closestCorners}
          onDragStart={handleDragStart}
          onDragOver={handleDragOver}
          onDragEnd={handleDragEnd}
        >
          <Box
            sx={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
              gap: 2.5,
              alignItems: 'start',
            }}
          >
            <AnnouncementBanner gridColumn="1 / -1" />

            {user && (
              <Box sx={{ gridColumn: '1 / -1' }}>
                {dataLoading ? (
                  <SkeletonCard variant="detailed" />
                ) : (
                  <Fade in={true} timeout={600} style={{ transitionDelay: '100ms' }}>
                    <Box>
                      <UserProfile user={user} />
                    </Box>
                  </Fade>
                )}
              </Box>
            )}

            <SortableContext
              items={groupOrder.map(g => `group:${g.name}`)}
              strategy={verticalListSortingStrategy}
            >
              {groupOrder.map((g) => renderGroup(g.name, g.title))}
            </SortableContext>
          </Box>

          <DragOverlay>
            {activeId ? (
              activeId.startsWith('group:') ? (
                <Box sx={{
                  opacity: 0.7,
                  bgcolor: 'background.paper',
                  border: '1px solid',
                  borderColor: 'primary.light',
                  borderRadius: 2,
                  p: 2,
                  pointerEvents: 'none',
                }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Box sx={{ fontSize: '0.6875rem', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'text.secondary' }}>
                      {groupOrder.find(g => `group:${g.name}` === activeId)?.title ?? activeId}
                    </Box>
                  </Box>
                </Box>
              ) : (
                <Box sx={{ opacity: 0.8, transform: 'scale(1.02)', pointerEvents: 'none' }}>
                  {(() => {
                    for (const defs of Object.values(widgetDefs)) {
                      const def = defs.find((d) => d.key === activeId);
                      if (def?.component) return def.component;
                    }
                    return null;
                  })()}
                </Box>
              )
            ) : null}
          </DragOverlay>
        </DndContext>
      </Container>

      {/* Edit mode toggle — bottom */}
      <Box sx={{ display: 'flex', justifyContent: 'center', gap: 1.5, mt: 3, mb: 1 }}>
        {editMode && (
          <>
            <Button
              variant="outlined"
              size="small"
              startIcon={<AddIcon />}
              onClick={() => setAddGroupOpen(true)}
              sx={{ borderRadius: 4, px: 3 }}
            >
              Gruppe hinzufügen
            </Button>
            <Button
              variant="outlined"
              size="small"
              color="warning"
              startIcon={<RefreshIcon />}
              onClick={() => setResetOpen(true)}
              sx={{ borderRadius: 4, px: 3 }}
            >
              Zurücksetzen
            </Button>
          </>
        )}
        <Button
          variant={editMode ? 'contained' : 'outlined'}
          size="small"
          startIcon={editMode ? <CheckIcon /> : <EditIcon />}
          onClick={() => setEditMode((prev) => !prev)}
          color={editMode ? 'primary' : 'inherit'}
          sx={{ borderRadius: 4, px: 3 }}
        >
          {editMode ? 'Bearbeitung beenden' : 'Widgets anordnen'}
        </Button>
      </Box>

      {/* Add group dialog */}
      <Dialog open={addGroupOpen} onClose={() => setAddGroupOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>Neue Gruppe erstellen</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            fullWidth
            label="Gruppenname"
            value={newGroupTitle}
            onChange={(e) => setNewGroupTitle(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') handleAddGroup(); }}
            sx={{ mt: 1 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => { setAddGroupOpen(false); setNewGroupTitle(''); }}>Abbrechen</Button>
          <Button variant="contained" onClick={handleAddGroup} disabled={!newGroupTitle.trim()}>Hinzufügen</Button>
        </DialogActions>
      </Dialog>

      {/* Reset confirmation dialog */}
      <ConfirmDialog
        open={resetOpen}
        onClose={() => setResetOpen(false)}
        onConfirm={handleReset}
        title="Layout zurücksetzen?"
        message="Das Dashboard-Layout wird auf die Standardanordnung zurückgesetzt. Alle eigenen Gruppen und Widget-Verschiebungen werden gelöscht."
        confirmLabel="Zurücksetzen"
        confirmColor="warning"
      />
    </DashboardLayout>
  );
}

export default Dashboard;
