"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  CalendarDays,
  MapPin,
  CreditCard,
  Plus,
  Loader2,
  Settings,
} from "lucide-react";
import { toast } from "sonner";
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;
  location: { id: string; name: string };
  _count: { cards: number };
};

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

export default function EventsPage() {
  const [days, setDays] = useState<CollectionDay[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/collection-days")
      .then((r) => r.json())
      .then((data) => {
        setDays(Array.isArray(data) ? data : []);
        setLoading(false);
      })
      .catch(() => {
        toast.error("Failed to load collection days");
        setLoading(false);
      });
  }, []);

  return (
    <div className="space-y-6">
      <Header
        title="Collection Days"
        description="Manage recurring events and service times"
        icon={CalendarDays}
      >
        <Button render={<Link href="/settings/locations" />} size="sm" className="rounded-xl">
          <Plus className="size-4" />
          Create Collection Day
        </Button>
      </Header>

      {loading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="size-6 animate-spin text-muted-foreground" />
        </div>
      ) : days.length === 0 ? (
        <div className="glass-card flex flex-col items-center justify-center rounded-2xl p-12 text-center">
          <CalendarDays className="mb-4 size-12 text-muted-foreground/40" />
          <h2 className="text-lg font-semibold">No collection days configured</h2>
          <p className="mt-1 max-w-sm text-sm text-muted-foreground">
            Set up your locations and service schedule to start organizing
            response cards by collection day.
          </p>
          <Button
            render={<Link href="/settings/locations" />}
            size="sm"
            className="mt-6 rounded-xl"
          >
            <Settings className="mr-1 size-4" />
            Configure Locations
          </Button>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {days.map((day) => (
            <Link
              key={day.id}
              href={`/events/${day.id}`}
              className="glass-card group rounded-2xl p-5 transition-shadow hover:shadow-lg"
            >
              <div className="flex items-start justify-between gap-3">
                <h3 className="font-semibold tracking-tight group-hover:text-primary transition-colors">
                  {day.name}
                </h3>
                <Badge variant={day.isActive ? "default" : "secondary"}>
                  {day.isActive ? "Active" : "Inactive"}
                </Badge>
              </div>

              {day.description && (
                <p className="mt-1.5 line-clamp-2 text-sm text-muted-foreground">
                  {day.description}
                </p>
              )}

              <div className="mt-4 flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-muted-foreground">
                <span className="inline-flex items-center gap-1">
                  <MapPin className="size-3" />
                  {day.location.name}
                </span>
                {day.dayOfWeek != null && (
                  <span className="inline-flex items-center gap-1">
                    <CalendarDays className="size-3" />
                    {DAY_NAMES[day.dayOfWeek]}
                    {day.timeStart && ` at ${day.timeStart}`}
                  </span>
                )}
                <span className="inline-flex items-center gap-1">
                  <CreditCard className="size-3" />
                  {day._count.cards} card{day._count.cards !== 1 ? "s" : ""}
                </span>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
