"use client"

import {
  getEventTypeLabel,
  getIcalUrl,
  usePortalRsvpMutation,
  useUpcomingEventsQuery,
} from "@/services/events"
import { format } from "date-fns"
import { de } from "date-fns/locale"
import { useTranslations } from "next-intl"
import {
  Calendar,
  Check,
  Download,
  HelpCircle,
  MapPin,
  Users,
  X,
} from "lucide-react"

import type { ClubEvent, RsvpStatus } from "@/services/events"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export default function PortalEventsPage() {
  const t = useTranslations("events")
  const { data: events = [], isLoading } = useUpcomingEventsQuery()

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold flex items-center gap-2">
          <Calendar className="h-6 w-6" />
          {t("portalTitle")}
        </h1>
        <p className="text-muted-foreground">{t("portalDescription")}</p>
      </div>

      {isLoading ? (
        <p className="text-muted-foreground">Laden...</p>
      ) : events.length === 0 ? (
        <Card>
          <CardContent className="py-8 text-center text-muted-foreground">
            {t("noUpcomingEvents")}
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {events.map((event: ClubEvent) => (
            <PortalEventCard key={event.id} event={event} />
          ))}
        </div>
      )}
    </div>
  )
}

function PortalEventCard({ event }: { event: ClubEvent }) {
  const t = useTranslations("events")
  const rsvpMutation = usePortalRsvpMutation(event.id)
  const accepted = event.attendeeCounts?.ACCEPTED ?? 0
  const maybe = event.attendeeCounts?.MAYBE ?? 0
  const isFull = event.maxAttendees != null && accepted >= event.maxAttendees

  const handleRsvp = (status: RsvpStatus) => {
    rsvpMutation.mutate(status)
  }

  return (
    <Card>
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <div>
            <Badge variant="secondary" className="mb-2">
              {getEventTypeLabel(event.eventType)}
            </Badge>
            <CardTitle className="text-lg">{event.title}</CardTitle>
          </div>
          {isFull && <Badge variant="destructive">{t("full")}</Badge>}
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="text-sm text-muted-foreground space-y-1">
          <p>
            📅{" "}
            {format(new Date(event.startAt), "EEEE, d. MMMM yyyy · HH:mm", {
              locale: de,
            })}{" "}
            Uhr
            {event.endAt && ` – ${format(new Date(event.endAt), "HH:mm")} Uhr`}
          </p>
          {event.location && (
            <p className="flex items-center gap-1">
              <MapPin className="h-4 w-4" /> {event.location}
            </p>
          )}
          <p className="flex items-center gap-1">
            <Users className="h-4 w-4" /> {accepted} Zusagen, {maybe} Vielleicht
            {event.maxAttendees && ` (max. ${event.maxAttendees})`}
          </p>
        </div>

        {event.description && <p className="text-sm">{event.description}</p>}

        {/* RSVP Buttons */}
        <div className="flex flex-wrap gap-2 pt-2">
          <Button
            size="sm"
            variant={event.myRsvpStatus === "ACCEPTED" ? "default" : "outline"}
            onClick={() => handleRsvp("ACCEPTED")}
            disabled={isFull && event.myRsvpStatus !== "ACCEPTED"}
          >
            <Check className="h-4 w-4 mr-1" /> {t("rsvp.accept")}
          </Button>
          <Button
            size="sm"
            variant={event.myRsvpStatus === "MAYBE" ? "default" : "outline"}
            onClick={() => handleRsvp("MAYBE")}
          >
            <HelpCircle className="h-4 w-4 mr-1" /> {t("rsvp.maybe")}
          </Button>
          <Button
            size="sm"
            variant={
              event.myRsvpStatus === "DECLINED" ? "destructive" : "outline"
            }
            onClick={() => handleRsvp("DECLINED")}
          >
            <X className="h-4 w-4 mr-1" /> {t("rsvp.decline")}
          </Button>
          <a href={getIcalUrl(event.id)} download>
            <Button size="sm" variant="ghost">
              <Download className="h-4 w-4 mr-1" /> iCal
            </Button>
          </a>
        </div>
      </CardContent>
    </Card>
  )
}
