"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import {
  CalendarDays,
  MapPin,
  CreditCard,
  Clock,
  ArrowLeft,
  Loader2,
  RefreshCw,
} from "lucide-react";
import { Header } from "@/components/layout/header";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";

type CollectionDay = {
  id: string;
  name: string;
  description: string | null;
  dayOfWeek: number | null;
  timeStart: string | null;
  timeEnd: string | null;
  isRecurring: boolean;
  isActive: boolean;
  date: string | null;
  rrule: string | null;
  location: { id: string; name: string };
  _count: { cards: number };
};

const DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

export default function EventDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [day, setDay] = useState<CollectionDay | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);

  useEffect(() => {
    fetch(`/api/collection-days/${id}`)
      .then((r) => {
        if (!r.ok) throw new Error("not found");
        return r.json();
      })
      .then(setDay)
      .catch(() => setNotFound(true))
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (notFound || !day) {
    return (
      <div className="space-y-6">
        <Header
          title="Not Found"
          description="This collection day doesn't exist or you don't have access."
          icon={CalendarDays}
        />
        <Button render={<Link href="/events" />} variant="outline" size="sm" className="rounded-xl">
          <ArrowLeft className="size-4" />
          Back to Collection Days
        </Button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Header
        title={day.name}
        description={day.description || "Collection day details"}
        icon={CalendarDays}
      >
        <Button render={<Link href="/events" />} variant="outline" size="sm" className="rounded-xl">
          <ArrowLeft className="size-4" />
          All Collection Days
        </Button>
      </Header>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <InfoCard
          icon={MapPin}
          label="Location"
          value={day.location.name}
        />
        <InfoCard
          icon={CalendarDays}
          label="Day"
          value={
            day.dayOfWeek != null
              ? DAY_NAMES[day.dayOfWeek]
              : day.date
                ? new Date(day.date).toLocaleDateString()
                : "Not set"
          }
        />
        <InfoCard
          icon={Clock}
          label="Time"
          value={
            day.timeStart
              ? `${day.timeStart}${day.timeEnd ? ` – ${day.timeEnd}` : ""}`
              : "Not set"
          }
        />
        <InfoCard
          icon={CreditCard}
          label="Linked Cards"
          value={String(day._count.cards)}
        />
      </div>

      <div className="glass-card rounded-2xl p-5">
        <div className="flex flex-wrap items-center gap-3">
          <Badge variant={day.isActive ? "default" : "secondary"}>
            {day.isActive ? "Active" : "Inactive"}
          </Badge>
          {day.isRecurring && (
            <Badge variant="outline">
              <RefreshCw className="size-3" />
              Recurring
            </Badge>
          )}
          {day.rrule && (
            <span className="text-xs text-muted-foreground">
              Rule: {day.rrule}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

function InfoCard({
  icon: Icon,
  label,
  value,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string;
}) {
  return (
    <div className="glass-card rounded-2xl p-4">
      <div className="flex items-center gap-2 text-xs text-muted-foreground">
        <Icon className="size-3.5" />
        {label}
      </div>
      <p className="mt-1 text-lg font-semibold tracking-tight">{value}</p>
    </div>
  );
}
