'use client';

import { useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import { Edit3, RotateCcw, Check, Users, CheckCircle2, Calendar, AlertCircle } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { TooltipProvider } from '@/components/ui/tooltip';
import { useDashboardStore } from '@/stores/dashboard-store';
import {
  WidgetGrid,
  WidgetGridEmpty,
  AddWidgetDialog,
  ClockWidget,
  WelcomeWidget,
  QuickActionsWidget,
  StatsWidget,
  CalendarWidget,
  ActivityWidget,
  OrdersWidget,
  ChatWidget,
  TasksWidget,
  TicketsWidget,
  FilesWidget,
  DocumentsWidget,
  GembaDocsWidget,
  type WidgetItem,
  type StatConfig,
} from '@/components/dashboard';

interface DashboardContentProps {
  locale: string;
}

/** Sample stats config - trendTextKey references i18n key under widgets.stats */
const SAMPLE_STATS_CONFIG: Record<string, Omit<StatConfig, 'trendText'> & { trendTextKey: string }> = {
  presentToday: {
    id: 'presentToday',
    labelKey: 'presentToday',
    value: '42',
    trend: 'up',
    trendTextKey: 'trendPresentToday',
    icon: Users,
  },
  openTasks: {
    id: 'openTasks',
    labelKey: 'openTasks',
    value: '12',
    trend: 'neutral',
    trendTextKey: 'trendOpenTasks',
    icon: CheckCircle2,
  },
  upcomingMeetings: {
    id: 'upcomingMeetings',
    labelKey: 'upcomingMeetings',
    value: '8',
    trend: 'neutral',
    trendTextKey: 'trendUpcomingMeetings',
    icon: Calendar,
  },
  openTickets: {
    id: 'openTickets',
    labelKey: 'openTickets',
    value: '23',
    trend: 'down',
    trendTextKey: 'trendOpenTickets',
    icon: AlertCircle,
  },
};

/**
 * Dashboard Content - Main dashboard view with customizable widgets
 */
export function DashboardContent({ locale }: DashboardContentProps) {
  const { data: session } = useSession();
  const t = useTranslations('dashboard');
  const tWidgets = useTranslations('widgets');

  const {
    widgets,
    isEditing,
    setWidgets,
    addWidget,
    removeWidget,
    toggleEditMode,
    resetToDefault,
  } = useDashboardStore();

  const userRoles = session?.user?.roles || [];

  // Resolve SAMPLE_STATS with translated trendText
  const sampleStats: Record<string, StatConfig> = Object.fromEntries(
    Object.entries(SAMPLE_STATS_CONFIG).map(([key, { trendTextKey, ...rest }]) => [
      key,
      { ...rest, trendText: tWidgets(`stats.${trendTextKey}`) },
    ])
  );

  // Handle widget order change from drag and drop
  const handleWidgetsChange = useCallback(
    (newWidgets: WidgetItem[]) => {
      setWidgets(newWidgets);
    },
    [setWidgets]
  );

  // Handle adding a new widget
  const handleAddWidget = useCallback(
    (type: string) => {
      addWidget(type);
    },
    [addWidget]
  );

  // Handle removing a widget
  const handleRemoveWidget = useCallback(
    (id: string) => {
      removeWidget(id);
    },
    [removeWidget]
  );

  // Render a widget based on its type
  const renderWidget = useCallback(
    (item: WidgetItem, editing: boolean) => {
      const commonProps = {
        id: item.id,
        isEditing: editing,
        onRemove: editing ? () => handleRemoveWidget(item.id) : undefined,
        locale,
      };

      switch (item.type) {
        case 'clock':
          return <ClockWidget {...commonProps} />;

        case 'welcome':
          return <WelcomeWidget {...commonProps} />;

        case 'quickActions':
          return <QuickActionsWidget {...commonProps} />;

        case 'stats': {
          const statKey = (item.settings?.statKey as string) || 'presentToday';
          const stat = sampleStats[statKey] || sampleStats.presentToday;
          return <StatsWidget {...commonProps} stat={stat} />;
        }

        case 'calendar':
          return <CalendarWidget {...commonProps} events={[]} />;

        case 'activity':
          return <ActivityWidget {...commonProps} />;

        // Integration Widgets
        case 'orders':
          return <OrdersWidget {...commonProps} />;

        case 'chat':
          return <ChatWidget {...commonProps} />;

        case 'todoistTasks':
          return <TasksWidget {...commonProps} />;

        case 'tickets':
          return <TicketsWidget {...commonProps} />;

        case 'files':
          return <FilesWidget {...commonProps} />;

        case 'documents':
          return <DocumentsWidget {...commonProps} />;

        case 'gembadocs':
          return <GembaDocsWidget {...commonProps} />;

        default:
          return (
            <div className="flex h-32 items-center justify-center rounded-lg border bg-muted">
              <span className="text-sm text-muted-foreground">
                Unknown widget: {item.type}
              </span>
            </div>
          );
      }
    },
    [handleRemoveWidget, locale, sampleStats]
  );

  return (
    <TooltipProvider delayDuration={0}>
      <div className="space-y-6">
        {/* Dashboard Header */}
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
          className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"
        >
          <div>
            <h1 className="text-3xl font-bold tracking-tight">{t('title')}</h1>
            <p className="text-muted-foreground">{t('overview')}</p>
          </div>

          {/* Dashboard Actions */}
          <div className="flex items-center gap-2">
            {isEditing ? (
              <>
                <AddWidgetDialog
                  onAddWidget={handleAddWidget}
                  existingWidgets={widgets.map((w) => w.type)}
                  userRoles={userRoles}
                />

                <Button variant="outline" size="sm" onClick={resetToDefault} className="gap-2">
                  <RotateCcw className="h-4 w-4" />
                  <span className="hidden sm:inline">{t('reset')}</span>
                </Button>

                <Button size="sm" onClick={toggleEditMode} className="gap-2">
                  <Check className="h-4 w-4" />
                  <span className="hidden sm:inline">{t('done')}</span>
                </Button>
              </>
            ) : (
              <Button variant="outline" size="sm" onClick={toggleEditMode} className="gap-2">
                <Edit3 className="h-4 w-4" />
                <span className="hidden sm:inline">{t('customize')}</span>
              </Button>
            )}
          </div>
        </motion.div>

        {/* Edit Mode Banner */}
        {isEditing && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="rounded-lg border border-primary/20 bg-primary/5 p-4"
          >
            <p className="text-sm text-primary">
              <strong>{t('editModeActive')}</strong> {t('editModeDescription')}
            </p>
          </motion.div>
        )}

        {/* Widget Grid */}
        {widgets.length === 0 ? (
          <WidgetGridEmpty onAddWidget={() => toggleEditMode()} />
        ) : (
          <WidgetGrid
            widgets={widgets}
            onWidgetsChange={handleWidgetsChange}
            isEditing={isEditing}
            renderWidget={renderWidget}
            columns={4}
            className={cn(
              // Responsive grid adjustments
              'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
            )}
          />
        )}
      </div>
    </TooltipProvider>
  );
}
