import { UserTablo } from "@xtablo/shared/types/tablos.types";
import { Button } from "@xtablo/ui/components/button";
import { TypographyH3, TypographyMuted } from "@xtablo/ui/components/typography";
import { Calendar, Clock, Plus } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { useEventsByTablo } from "../hooks/events";
import { useIsReadOnlyUser } from "../providers/UserStoreProvider";
import { TabloHeaderActions } from "./TabloHeaderActions";

interface TabloEventsSectionProps {
  tablo: UserTablo;
  isAdmin: boolean;
}

export const TabloEventsSection = ({ tablo, isAdmin }: TabloEventsSectionProps) => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { data: events, isLoading, error } = useEventsByTablo(tablo.id);
  const isReadOnly = useIsReadOnlyUser();

  // Filter upcoming events (events in the future or today)
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const upcomingEvents = events
    ?.filter((event) => {
      const eventDate = new Date(event.start_date);
      return eventDate >= today;
    })
    .sort((a, b) => {
      const dateCompare = new Date(a.start_date).getTime() - new Date(b.start_date).getTime();
      if (dateCompare !== 0) return dateCompare;
      return (a.start_time || "").localeCompare(b.start_time || "");
    });

  const handleCreateEvent = () => {
    navigate(`/planning/create?tablo_id=${tablo.id}`);
  };

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return new Intl.DateTimeFormat("fr-FR", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    }).format(date);
  };

  const formatTime = (timeStr: string) => {
    if (!timeStr) return "";

    return timeStr.slice(0, 5); // HH:MM
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-start">
        <div>
          <TypographyH3 className="text-3xl font-bold text-foreground">
            {t("tablo:events.title")}
          </TypographyH3>
          <TypographyMuted className="text-muted-foreground mt-1">
            {t("tablo:events.description")}
          </TypographyMuted>
          {!isReadOnly && (
            <Button
              onClick={handleCreateEvent}
              className="flex items-center gap-2 mt-4 bg-[#804EEC] hover:bg-[#6f3fd4] text-white"
            >
              <Plus className="w-4 h-4" />
              {t("tablo:events.createEvent")}
            </Button>
          )}
        </div>
        <TabloHeaderActions tablo={tablo} isAdmin={isAdmin} />
      </div>
      {/* Events List */}
      <div className="bg-card rounded-lg border border-border">
        {isLoading ? (
          <div className="flex items-center justify-center p-8">
            <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#804EEC]"></div>
            <span className="ml-3 text-sm text-gray-500 dark:text-gray-400">
              Chargement des événements...
            </span>
          </div>
        ) : error ? (
          <div className="p-6">
            <div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
              <div className="flex items-center space-x-2">
                <svg
                  className="w-5 h-5 text-red-500"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                  />
                </svg>
                <span className="text-sm text-red-700 dark:text-red-300">
                  Erreur lors du chargement des événements
                </span>
              </div>
            </div>
          </div>
        ) : upcomingEvents && upcomingEvents.length > 0 ? (
          <div className="divide-y divide-border">
            {upcomingEvents.map((event) => (
              <div key={event.event_id} className="p-6">
                <div className="flex items-start space-x-4">
                  {/* Date Badge */}
                  <div className="shrink-0 w-14 h-14 bg-[#F4F3FF] dark:bg-purple-900/20 rounded-[8px] flex flex-col items-center justify-center">
                    <span className="text-[10px] font-semibold text-[#7F56D9] dark:text-purple-400 uppercase tracking-wide leading-none">
                      {new Date(event.start_date).toLocaleDateString("fr-FR", {
                        month: "short",
                      })}
                    </span>
                    <span className="text-xl font-bold text-[#7F56D9] dark:text-purple-400 leading-none mt-0.5">
                      {new Date(event.start_date).getDate()}
                    </span>
                  </div>

                  {/* Event Details */}
                  <div className="flex-1 min-w-0">
                    <h3 className="text-lg font-semibold text-foreground mb-1">{event.title}</h3>

                    <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
                      <div className="flex items-center gap-1">
                        <Calendar className="w-4 h-4" />
                        <span className="capitalize">{formatDate(event.start_date)}</span>
                      </div>

                      {event.start_time && (
                        <div className="flex items-center gap-1">
                          <Clock className="w-4 h-4" />
                          <span>
                            {formatTime(event.start_time)}
                            {event.end_time && ` - ${formatTime(event.end_time)}`}
                          </span>
                        </div>
                      )}
                    </div>

                    {event.description && (
                      <p className="mt-2 text-sm text-muted-foreground line-clamp-2">
                        {event.description}
                      </p>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="text-center py-12">
            <svg
              className="w-16 h-16 text-gray-300 dark:text-gray-600 mx-auto mb-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
              />
            </svg>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Aucun événement à venir pour ce tablo
            </p>
            {!isReadOnly && (
              <Button
                onClick={handleCreateEvent}
                className="mt-4 bg-[#804EEC] hover:bg-[#6f3fd4] text-white"
              >
                <Plus className="w-4 h-4 mr-2" />
                Créer le premier événement
              </Button>
            )}
          </div>
        )}
      </div>
    </div>
  );
};
