'use client';

import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { format } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { Clock } from 'lucide-react';

import { cn } from '@/lib/utils';
import { WidgetContainer } from '../widget-container';

interface ClockWidgetProps {
  id: string;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  className?: string;
}

/**
 * Clock Widget - Displays current time and date
 * Updates every second for real-time display
 */
export function ClockWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  className,
}: ClockWidgetProps) {
  const t = useTranslations('widgets.clock');
  const [now, setNow] = useState<Date | null>(null);
  const [mounted, setMounted] = useState(false);

  // Initialize time only on client
  useEffect(() => {
    setMounted(true);
    setNow(new Date());
  }, []);

  // Update time every second
  useEffect(() => {
    if (!mounted) return;

    const interval = setInterval(() => {
      setNow(new Date());
    }, 1000);

    return () => clearInterval(interval);
  }, [mounted]);

  const dateLocale = locale === 'de' ? de : enUS;

  // Show placeholder during server render and initial client mount
  if (!mounted || !now) {
    return (
      <WidgetContainer
        id={id}
        title={t('name')}
        icon={<Clock className="h-4 w-4 text-primary" />}
        isEditing={isEditing}
        onRemove={onRemove}
        className={className}
      >
        <div className="flex flex-col items-center justify-center py-2">
          <div
            className={cn(
              'font-mono text-4xl font-bold tracking-tight tabular-nums',
              'bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent'
            )}
          >
            --:--:--
          </div>
          <p className="mt-2 text-sm text-muted-foreground capitalize">Loading...</p>
        </div>
      </WidgetContainer>
    );
  }

  const timeString = format(now, 'HH:mm:ss');
  const dateString = format(now, 'EEEE, d. MMMM yyyy', { locale: dateLocale });

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<Clock className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
    >
      <div className="flex flex-col items-center justify-center py-2">
        <div
          className={cn(
            'font-mono text-4xl font-bold tracking-tight tabular-nums',
            'bg-gradient-to-r from-primary to-primary/60 bg-clip-text text-transparent'
          )}
        >
          {timeString}
        </div>
        <p className="mt-2 text-sm text-muted-foreground capitalize">{dateString}</p>
      </div>
    </WidgetContainer>
  );
}
