﻿import React from 'react';
import { Link, useParams } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import EmotionPicker from '../components/EmotionPicker';
import GalleryPreview from '../components/GalleryPreview';
import { useGuestIdentity } from '../context/GuestIdentityContext';
import { useEventStats } from '../context/EventStatsContext';
import { useEventData } from '../hooks/useEventData';
import { useGuestTaskProgress } from '../hooks/useGuestTaskProgress';
import { Sparkles, UploadCloud, Images, CheckCircle2, Users, TimerReset } from 'lucide-react';

export default function HomePage() {
  const { slug } = useParams<{ slug: string }>();
  const { name, hydrated } = useGuestIdentity();
  const stats = useEventStats();
  const { event } = useEventData();
  const { completedCount } = useGuestTaskProgress(slug);

  if (!slug) return null;

  const displayName = hydrated && name ? name : 'Gast';
  const latestUploadText = formatLatestUpload(stats.latestPhotoAt);

  const primaryActions: Array<{ to: string; label: string; description: string; icon: React.ReactNode }> = [
    {
      to: 'tasks',
      label: 'Aufgabe ziehen',
      description: 'Hol dir deine naechste Challenge',
      icon: <Sparkles className="h-5 w-5" />,
    },
    {
      to: 'upload',
      label: 'Direkt hochladen',
      description: 'Teile deine neuesten Fotos',
      icon: <UploadCloud className="h-5 w-5" />,
    },
    {
      to: 'gallery',
      label: 'Galerie ansehen',
      description: 'Lass dich von anderen inspirieren',
      icon: <Images className="h-5 w-5" />,
    },
  ];

  const checklistItems = [
    'Aufgabe auswaehlen oder starten',
    'Emotion festhalten und Foto schiessen',
    'Bild hochladen und Credits sammeln',
  ];

  return (
    <div className="space-y-6 pb-24">
      <HeroCard name={displayName} eventName={event?.name ?? 'Dein Event'} tasksCompleted={completedCount} />

      <Card>
        <CardContent className="grid grid-cols-1 gap-4 py-4 sm:grid-cols-4">
          <StatTile
            icon={<Users className="h-4 w-4" />}
            label="Gleichzeitig online"
            value={`${stats.onlineGuests}`}
          />
          <StatTile
            icon={<Sparkles className="h-4 w-4" />}
            label="Aufgaben gelöst"
            value={`${stats.tasksSolved}`}
          />
          <StatTile
            icon={<TimerReset className="h-4 w-4" />}
            label="Letzter Upload"
            value={latestUploadText}
          />
          <StatTile
            icon={<CheckCircle2 className="h-4 w-4" />}
            label="Deine erledigten Aufgaben"
            value={`${completedCount}`}
          />
        </CardContent>
      </Card>

      <section className="space-y-3">
        <div className="flex items-center justify-between">
          <h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">Deine Aktionen</h2>
          <span className="text-xs text-muted-foreground">Waehle aus, womit du starten willst</span>
        </div>
        <div className="grid gap-3 sm:grid-cols-2">
          {primaryActions.map((action) => (
            <Link to={action.to} key={action.to} className="block">
              <Card className="transition-all hover:shadow-lg">
                <CardContent className="flex items-center gap-3 py-4">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-pink-100 text-pink-600">
                    {action.icon}
                  </div>
                  <div className="flex flex-col">
                    <span className="text-base font-semibold">{action.label}</span>
                    <span className="text-sm text-muted-foreground">{action.description}</span>
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
        <Button variant="outline" asChild className="w-full">
          <Link to="queue">Uploads in Warteschlange ansehen</Link>
        </Button>
      </section>

      <Card>
        <CardHeader>
          <CardTitle>Dein Fortschritt</CardTitle>
          <CardDescription>Halte dich an diese drei kurzen Schritte fuer die besten Ergebnisse.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {checklistItems.map((item) => (
            <div key={item} className="flex items-start gap-3">
              <CheckCircle2 className="mt-0.5 h-5 w-5 text-green-500" />
              <span className="text-sm leading-relaxed text-muted-foreground">{item}</span>
            </div>
          ))}
        </CardContent>
      </Card>

      <Separator />

      <EmotionPicker />

      <GalleryPreview slug={slug} />
    </div>
  );
}

function HeroCard({ name, eventName, tasksCompleted }: { name: string; eventName: string; tasksCompleted: number }) {
  const progressMessage = tasksCompleted > 0
    ? `Schon ${tasksCompleted} Aufgaben erledigt - weiter so!`
    : 'Starte mit deiner ersten Aufgabe - wir zählen auf dich!';

  return (
    <Card className="overflow-hidden border-0 bg-gradient-to-r from-pink-500 via-fuchsia-500 to-purple-500 text-white shadow-md">
      <CardHeader className="space-y-1">
        <CardDescription className="text-sm text-white/80">Willkommen zur Party</CardDescription>
        <CardTitle className="text-2xl font-bold">Hey {name}!</CardTitle>
        <p className="text-sm text-white/80">Du bist bereit für "{eventName}". Fang die Highlights des Events ein und teile sie mit allen Gästen.</p>
        <p className="text-sm font-medium text-white/90">{progressMessage}</p>
      </CardHeader>
    </Card>
  );
}

function StatTile({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return (
    <div className="flex items-center gap-3 rounded-lg border bg-muted/30 px-3 py-2">
      <div className="flex h-10 w-10 items-center justify-center rounded-full bg-white text-pink-600 shadow-sm">
        {icon}
      </div>
      <div className="flex flex-col">
        <span className="text-xs uppercase tracking-wide text-muted-foreground">{label}</span>
        <span className="text-lg font-semibold text-foreground">{value}</span>
      </div>
    </div>
  );
}

function formatLatestUpload(isoDate: string | null) {
  if (!isoDate) {
    return 'Noch kein Upload';
  }
  const date = new Date(isoDate);
  if (Number.isNaN(date.getTime())) {
    return 'Noch kein Upload';
  }
  const diffMs = Date.now() - date.getTime();
  const diffMinutes = Math.round(diffMs / 60000);
  if (diffMinutes < 1) {
    return 'Gerade eben';
  }
  if (diffMinutes < 60) {
    return `vor ${diffMinutes} Min`;
  }
  const diffHours = Math.round(diffMinutes / 60);
  if (diffHours < 24) {
    return `vor ${diffHours} Std`;
  }
  const diffDays = Math.round(diffHours / 24);
  return `vor ${diffDays} Tagen`;
}
