import { createSignal, createMemo, Show, For } from "solid-js";
import { useI18n } from "../../providers/i18n-provider";
import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "./icons";

const CalendarIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
    <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
    <line x1="16" y1="2" x2="16" y2="6" />
    <line x1="8" y1="2" x2="8" y2="6" />
    <line x1="3" y1="10" x2="21" y2="10" />
  </svg>
);

export function CalendarView(props: { bookings: any[]; locale?: string; onBookingClick?: (b: any) => void }) {
  const i18n = useI18n();
  const [currentDate, setCurrentDate] = createSignal(new Date());
  const [selectedDay, setSelectedDay] = createSignal<number | null>(null);
  const [modalDay, setModalDay] = createSignal<number | null>(null);
  const [isAnimating, setIsAnimating] = createSignal(false);
  const isCs = () => props.locale === "cs";

  const calendarMonth = createMemo(() => currentDate().getMonth());
  const calendarYear = createMemo(() => currentDate().getFullYear());

  const monthYear = createMemo(() =>
    `${i18n.t(`calendar.months.${calendarMonth()}`)} ${calendarYear()}`
  );

  const changeMonth = (direction: number) => {
    setIsAnimating(true);
    setTimeout(() => {
      setCurrentDate(new Date(currentDate().getFullYear(), currentDate().getMonth() + direction, 1));
      setIsAnimating(false);
      setSelectedDay(null);
      setModalDay(null);
    }, 150);
  };

  const calendarDays = createMemo(() => {
    const year = calendarYear();
    const month = calendarMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDay = firstDay.getDay();
    const adjustedStart = startingDay === 0 ? 6 : startingDay - 1;

    const days: Array<{ day: number | null; bookings: any[]; isToday: boolean }> = [];
    for (let i = 0; i < adjustedStart; i++) {
      days.push({ day: null, bookings: [], isToday: false });
    }

    const today = new Date();
    for (let day = 1; day <= daysInMonth; day++) {
      const dayBookings = props.bookings.filter((b) => {
        const bd = new Date(b.startsAt);
        return bd.getDate() === day && bd.getMonth() === month && bd.getFullYear() === year;
      });
      const isToday = today.getDate() === day && today.getMonth() === month && today.getFullYear() === year;
      days.push({ day, bookings: dayBookings, isToday });
    }
    return days;
  });

  const handleDayClick = (day: number | null) => {
    if (!day) return;
    const dayData = calendarDays().find((d) => d.day === day);
    if (dayData && dayData.bookings.length > 0) {
      setModalDay(day);
    } else {
      setSelectedDay(selectedDay() === day ? null : day);
    }
  };

  const handleBookingClick = (booking: any) => {
    props.onBookingClick?.(booking);
    setModalDay(null);
  };

  const modalBookings = createMemo(() => {
    const day = modalDay();
    if (!day) return [];
    return calendarDays().find((d) => d.day === day)?.bookings ?? [];
  });

  // Booking visual density for bars
  const getBookingBars = (bookings: any[]) => {
    if (bookings.length === 0) return null;
    const count = bookings.length;
    const hasMultiple = count >= 2;
    const hasMany = count >= 3;
    return (
      <div class="mt-2 space-y-1.5">
        <div class="h-2 bg-accent/30 rounded-full w-full group-hover:bg-accent/40 transition-colors" />
        {hasMultiple && <div class="h-2 bg-accent/20 rounded-full w-3/4 group-hover:bg-accent/30 transition-colors" />}
        {hasMany && <div class="h-2 bg-accent/10 rounded-full w-1/2 group-hover:bg-accent/20 transition-colors" />}
      </div>
    );
  };

  return (
    <>
      <div class="surface-card p-6 shadow-sm hover:shadow-md transition-all duration-500">
        {/* Header */}
        <div class="flex items-center justify-between mb-6">
          <div class="flex items-center gap-3">
            <div class="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center text-accent">
              <CalendarIcon />
            </div>
            <div>
              <h3 class="text-lg font-semibold text-ink font-display">{monthYear()}</h3>
              <p class="text-sm text-ink-muted mt-0.5">
                {props.bookings.length} {isCs() ? i18n.t("dashboard.calendar.bookingsCount") : "bookings"}
              </p>
            </div>
          </div>
          <div class="flex items-center gap-2">
            <button
              onClick={() => changeMonth(-1)}
              aria-label={i18n.t("calendar.prevMonth")}
              class="w-8 h-8 rounded-lg border border-border flex items-center justify-center text-ink-muted hover:bg-canvas-subtle transition-colors"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m15 18-6-6 6-6"/></svg>
            </button>
            <button
              onClick={() => changeMonth(1)}
              aria-label={i18n.t("calendar.nextMonth")}
              class="w-8 h-8 rounded-lg border border-border flex items-center justify-center text-ink-muted hover:bg-canvas-subtle transition-colors"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 18 6-6-6-6"/></svg>
            </button>
          </div>
        </div>

        {/* Day headers */}
        <div class="grid grid-cols-7 gap-px bg-border/50">
          {[0, 1, 2, 3, 4, 5, 6].map((dayIndex) => (
            <div class="bg-canvas-subtle/50 p-3 text-center text-xs font-medium text-ink-subtle uppercase tracking-wider">
              {i18n.t(`calendar.days.${dayIndex}`)}
            </div>
          ))}
        </div>

        {/* Calendar grid */}
        <div class={`grid grid-cols-7 gap-px bg-border/50 transition-opacity duration-200 ${isAnimating() ? "opacity-0" : "opacity-100"}`}>
          {calendarDays().map(({ day, bookings, isToday }) => {
            if (!day) {
              return <div class="p-3 min-h-[80px] lg:min-h-[100px] bg-canvas/50" />;
            }
            return (
              <button
                onClick={() => handleDayClick(day)}
                class={`
                  p-3 min-h-[80px] lg:min-h-[100px] bg-canvas transition-all duration-200 hover:bg-canvas-subtle group relative text-left
                  ${isToday ? "ring-2 ring-inset ring-accent bg-accent-soft" : ""}
                  ${selectedDay() === day ? "ring-2 ring-inset ring-accent bg-accent-subtle/30" : ""}
                  ${bookings.length > 0 && !isToday ? "bg-accent-subtle/10" : ""}
                `}
              >
                <span class={`text-sm transition-colors ${isToday ? "font-semibold text-accent" : "text-ink-muted group-hover:text-ink"}`}>
                  {day}
                </span>
                {getBookingBars(bookings)}
                {bookings.length > 0 && (
                  <div class="absolute top-2 right-2">
                    <span class="text-[10px] font-semibold text-accent bg-accent/10 px-1.5 py-0.5 rounded-full">
                      {bookings.length}
                    </span>
                  </div>
                )}
              </button>
            );
          })}
        </div>

        {/* Inline selected day preview for empty days */}
        <Show when={selectedDay() && !modalDay()}>
          <div class="mt-4 p-4 bg-canvas-subtle/50 rounded-xl border border-border/60 animate-fade-in">
            <div class="flex items-center justify-between mb-2">
              <span class="text-sm font-medium text-ink">
                {selectedDay()}. {monthYear()}
              </span>
              <button onClick={() => setSelectedDay(null)} class="text-xs text-ink-muted hover:text-ink">
                {i18n.t("dashboard.close")}
              </button>
            </div>
            <p class="text-sm text-ink-muted">{i18n.t("dashboard.calendar.noBookings")}</p>
          </div>
        </Show>
      </div>

      {/* Day bookings modal */}
      <Show when={modalDay()}>
        <div class="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div class="absolute inset-0 bg-ink/40 backdrop-blur-sm" onClick={() => setModalDay(null)} />
          <div class="relative bg-canvas rounded-2xl shadow-2xl w-full max-w-md max-h-[80vh] overflow-hidden animate-scale-in">
            <div class="p-5 border-b border-border flex items-center justify-between">
              <div>
                <h3 class="text-lg font-bold text-ink">
                  {modalDay()}. {monthYear()}
                </h3>
                <p class="text-xs text-ink-muted mt-0.5">
                  {modalBookings().length} {isCs() ? "rezervací" : "bookings"}
                </p>
              </div>
              <button
                onClick={() => setModalDay(null)}
                class="p-2 hover:bg-canvas-subtle rounded-lg transition-colors"
                aria-label={i18n.t("dashboard.close")}
              >
                <XIcon />
              </button>
            </div>
            <div class="p-5 overflow-y-auto max-h-[60vh] space-y-3">
              <For each={modalBookings()}>
                {(booking) => (
                  <button
                    onClick={() => handleBookingClick(booking)}
                    class="w-full text-left flex items-center gap-3 p-3 rounded-xl border border-border/60 hover:border-accent/30 hover:bg-accent-subtle/20 transition-all"
                  >
                    <div
                      class={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${
                        booking.status === "confirmed"
                          ? "bg-accent text-canvas"
                          : booking.status === "pending"
                          ? "bg-canvas-muted text-ink"
                          : "bg-canvas-subtle text-ink-muted"
                      }`}
                    >
                      {(booking.customerName ?? "?")
                        .split(" ")
                        .map((n: string) => n[0])
                        .join("")
                        .slice(0, 2)
                        .toUpperCase()}
                    </div>
                    <div class="flex-1 min-w-0">
                      <p class="text-sm font-medium text-ink truncate">{booking.customerName}</p>
                      <p class="text-xs text-ink-muted">{booking.service}</p>
                    </div>
                    <div class="text-right shrink-0">
                      <p class="text-xs font-medium text-ink">
                        {new Date(booking.startsAt).toLocaleTimeString(isCs() ? "cs-CZ" : "en-US", { hour: "2-digit", minute: "2-digit" })}
                      </p>
                      <span
                        class={`text-[10px] px-1.5 py-0.5 rounded-full font-medium ${
                          booking.status === "confirmed"
                            ? "bg-accent/10 text-accent"
                            : booking.status === "pending"
                            ? "bg-canvas-muted text-ink-muted"
                            : "bg-canvas-subtle text-ink-subtle"
                        }`}
                      >
                        {i18n.t(`dashboard.${booking.status}`)}
                      </span>
                    </div>
                  </button>
                )}
              </For>
            </div>
          </div>
        </div>
      </Show>
    </>
  );
}
