// @ts-nocheck
import React from 'react';
import { Link } from 'react-router-dom';
import { Card, CardContent } from '@/components/ui/card';
import { getDeviceId } from '../lib/device';
import { usePollGalleryDelta } from '../polling/usePollGalleryDelta';
import { Heart } from 'lucide-react';
import { useTranslation } from '../i18n/useTranslation';
import { useEventBranding } from '../context/EventBrandingContext';

type Props = { token: string };

type PreviewFilter = 'latest' | 'popular' | 'mine' | 'photobooth';
type PreviewPhoto = {
  id: number;
  session_id?: string | null;
  ingest_source?: string | null;
  likes_count?: number | null;
  created_at?: string | null;
  task_id?: number | null;
  task_title?: string | null;
  emotion_id?: number | null;
  emotion_name?: string | null;
  thumbnail_path?: string | null;
  file_path?: string | null;
  title?: string | null;
};

export default function GalleryPreview({ token }: Props) {
  const { locale } = useTranslation();
  const { branding } = useEventBranding();
  const { photos, loading } = usePollGalleryDelta(token, locale);
  const [mode, setMode] = React.useState<PreviewFilter>('latest');
  const typedPhotos = React.useMemo(() => photos as PreviewPhoto[], [photos]);
  const hasPhotobooth = React.useMemo(() => typedPhotos.some((p) => p.ingest_source === 'photobooth'), [typedPhotos]);
  const radius = branding.buttons?.radius ?? 12;
  const linkColor = branding.buttons?.linkColor ?? branding.secondaryColor;
  const headingFont = branding.typography?.heading ?? branding.fontFamily ?? undefined;
  const bodyFont = branding.typography?.body ?? branding.fontFamily ?? undefined;

  const items = React.useMemo(() => {
    let arr = typedPhotos.slice();
    
    // MyPhotos filter (requires session_id matching)
    if (mode === 'mine') {
      const deviceId = getDeviceId();
      arr = arr.filter((photo) => photo.session_id === deviceId);
    } else if (mode === 'photobooth') {
      arr = arr.filter((photo) => photo.ingest_source === 'photobooth');
    }
    
    // Sorting
    if (mode === 'popular') {
      arr.sort((a, b) => (b.likes_count ?? 0) - (a.likes_count ?? 0));
    } else {
      arr.sort((a, b) => new Date(b.created_at ?? 0).getTime() - new Date(a.created_at ?? 0).getTime());
    }
    
    return arr.slice(0, 4); // 2x2 = 4 items
  }, [typedPhotos, mode]);

  React.useEffect(() => {
    if (mode === 'photobooth' && !hasPhotobooth) {
      setMode('latest');
    }
  }, [mode, hasPhotobooth]);

  // Helper function to generate photo title (must be before return)
  function getPhotoTitle(photo: PreviewPhoto): string {
    if (photo.task_id) {
      return `Task: ${photo.task_title || 'Unbekannte Aufgabe'}`;
    }
    if (photo.emotion_id) {
      return `Emotion: ${photo.emotion_name || 'Gefühl'}`;
    }
    // Fallback based on creation time or placeholder
    const now = new Date();
    const created = new Date(photo.created_at || now);
    const hours = created.getHours();
    if (hours < 12) return 'Morgenmoment';
    if (hours < 18) return 'Nachmittagslicht';
    return 'Abendstimmung';
  }

  const filters: { value: PreviewFilter; label: string }[] = [
    { value: 'latest', label: 'Newest' },
    { value: 'popular', label: 'Popular' },
    { value: 'mine', label: 'My Photos' },
    ...(hasPhotobooth ? [{ value: 'photobooth', label: 'Fotobox' } as const] : []),
  ];

  return (
    <Card className="border border-muted/30 shadow-sm" style={{ borderRadius: radius, background: 'var(--guest-surface)', fontFamily: bodyFont }}>
      <CardContent className="space-y-3 p-3">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-xs uppercase tracking-wide text-muted-foreground" style={headingFont ? { fontFamily: headingFont } : undefined}>Live-Galerie</p>
            <h3 className="text-lg font-semibold text-foreground" style={headingFont ? { fontFamily: headingFont } : undefined}>Alle Uploads auf einen Blick</h3>
          </div>
          <Link
            to={`/e/${encodeURIComponent(token)}/gallery?mode=${mode}`}
            className="text-sm font-semibold transition"
            style={{ color: linkColor }}
          >
            Alle ansehen →
          </Link>
        </div>

        <div className="flex gap-2 overflow-x-auto pb-1 text-sm font-medium [-ms-overflow-style:none] [scrollbar-width:none]">
        {filters.map((filter) => (
          <button
            key={filter.value}
            type="button"
            onClick={() => setMode(filter.value)}
            style={{
              borderRadius: radius,
              border: mode === filter.value ? `1px solid ${branding.primaryColor}` : `1px solid ${branding.primaryColor}22`,
              background: mode === filter.value ? branding.primaryColor : 'var(--guest-surface)',
              color: mode === filter.value ? '#ffffff' : 'var(--foreground)',
              boxShadow: mode === filter.value ? `0 8px 18px ${branding.primaryColor}33` : 'none',
            }}
            className="px-4 py-1 transition"
          >
            {filter.label}
          </button>
        ))}
      </div>

        {loading && <p className="text-sm text-muted-foreground">Lädt…</p>}
        {!loading && items.length === 0 && (
          <div className="flex items-center gap-3 rounded-xl border border-muted/30 bg-[var(--guest-surface)] p-3 text-sm text-muted-foreground">
            <Heart className="h-4 w-4" style={{ color: branding.secondaryColor }} aria-hidden />
            Noch keine Fotos. Starte mit deinem ersten Upload!
          </div>
        )}

        <div className="grid gap-2 sm:grid-cols-2">
        {items.map((p: PreviewPhoto) => (
          <Link
            key={p.id}
            to={`/e/${encodeURIComponent(token)}/gallery?photoId=${p.id}`}
            className="group relative block overflow-hidden text-foreground"
            style={{
              borderRadius: radius,
              border: `1px solid ${branding.primaryColor}22`,
              background: 'var(--guest-surface)',
              boxShadow: `0 12px 26px ${branding.primaryColor}22`,
            }}
          >
            <img
              src={p.thumbnail_path || p.file_path}
              alt={p.title || 'Foto'}
              className="h-40 w-full object-cover transition duration-300 group-hover:scale-105"
              loading="lazy"
            />
            <div
              className="absolute inset-0"
              style={{
                background: `linear-gradient(180deg, transparent 50%, ${branding.primaryColor}33 100%)`,
              }}
              aria-hidden
            />
            <div className="absolute bottom-0 left-0 right-0 space-y-1 p-3">
              <p className="text-sm font-semibold leading-tight line-clamp-2" style={headingFont ? { fontFamily: headingFont } : undefined}>
                {p.title || getPhotoTitle(p)}
              </p>
              <div className="flex items-center gap-1 text-xs text-foreground/80">
                <Heart className="h-4 w-4" style={{ color: branding.primaryColor }} aria-hidden />
                {p.likes_count ?? 0}
              </div>
            </div>
          </Link>
        ))}
      </div>

        <p className="text-center text-sm text-muted-foreground">
          Lust auf mehr?{' '}
          <Link to={`/e/${encodeURIComponent(token)}/gallery`} className="font-semibold transition" style={{ color: linkColor }}>
            Zur Galerie →
          </Link>
        </p>
      </CardContent>
    </Card>
  );
}
