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

interface NotificationItem {
  id: string;
  type: "booking" | "reminder" | "upgrade" | "trial" | "system";
  title: string;
  message: string;
  time: string;
  read: boolean;
}

export function NotificationDropdown(props: { bookings?: any[]; billing?: any }) {
  const i18n = useI18n();
  const [open, setOpen] = createSignal(false);
  const notifications = createMemo<NotificationItem[]>(() => {
    const items: NotificationItem[] = [];
    const cs = i18n.locale() === "cs";
    const bookings = props.bookings ?? [];

    // Recent bookings as notifications
    bookings.slice(0, 3).forEach((b: any, i: number) => {
      items.push({
        id: `booking-${i}`,
        type: "booking",
        title: `${cs ? "Nová rezervace" : "New booking"} ${b.customerName}`,
        message: `${b.service} — ${new Date(b.startsAt).toLocaleDateString()}`,
        time: new Date(b.startsAt).toLocaleDateString(undefined, { month: "short", day: "numeric" }),
        read: false,
      });
    });

    // Plan/trial notifications
    const billing = props.billing;
    if (billing?.subscriptionStatus === "trialing") {
      const daysLeft = billing?.trialDaysRemaining ?? 3;
      items.push({
        id: "trial",
        type: "trial",
        title: cs ? "Zkušební doba končí" : "Trial ending",
        message: cs ? `Zbývá ${daysLeft} dní` : `${daysLeft} days remaining`,
        time: "",
        read: false,
      });
    }

    if (items.length === 0) {
      items.push({
        id: "welcome",
        type: "system",
        title: cs ? "Vítejte v Bookra" : "Welcome to Bookra",
        message: cs ? "Začněte vytvořením první rezervace." : "Start by creating your first booking.",
        time: "",
        read: true,
      });
    }

    return items;
  });

  const [readIds, setReadIds] = createSignal<Set<string>>(new Set());

  const filteredNotifications = createMemo(() =>
    notifications().map((n) => ({ ...n, read: n.read || readIds().has(n.id) }))
  );

  const unreadCount = createMemo(() => filteredNotifications().filter((n) => !n.read).length);

  const markAllRead = () => {
    setReadIds(new Set(filteredNotifications().map((n) => n.id)));
  };

  const markRead = (id: string) => {
    setReadIds((prev) => { const next = new Set(prev); next.add(id); return next; });
  };

  const typeIcon = (type: string) => {
    const base = "w-8 h-8 rounded-full flex items-center justify-center shrink-0";
    switch (type) {
      case "booking":
        return (
          <div class={`${base} bg-accent-subtle text-accent`}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>
          </div>
        );
      case "reminder":
        return (
          <div class={`${base} bg-canvas-muted text-ink-muted`}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
          </div>
        );
      case "upgrade":
      case "trial":
        return (
          <div class={`${base} bg-canvas-muted text-ink-muted`}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>
          </div>
        );
      default:
        return (
          <div class={`${base} bg-canvas-muted text-ink-muted`}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>
          </div>
        );
    }
  };

  return (
    <div class="relative">
      <button
        onClick={() => setOpen(!open())}
        class="p-2 text-ink-subtle hover:text-ink hover:bg-canvas-subtle rounded-xl transition-all relative"
        aria-label={i18n.t("dashboard.notifications")}
      >
        <BellIcon />
        <Show when={unreadCount() > 0}>
          <span class="absolute top-1.5 right-1.5 w-2 h-2 bg-accent rounded-full" />
        </Show>
      </button>

      <Show when={open()}>
        <div class="absolute right-0 top-full mt-2 w-80 bg-canvas rounded-2xl shadow-xl border border-border z-50 overflow-hidden animate-scale-in">
          <div class="p-4 border-b border-border flex items-center justify-between">
            <h3 class="font-semibold text-ink">{i18n.t("dashboard.notifications.title")}</h3>
            <Show when={unreadCount() > 0}>
              <button onClick={markAllRead} class="text-xs text-accent hover:text-accent-hover font-medium">
                {i18n.t("dashboard.markAllRead")}
              </button>
            </Show>
          </div>
          <div class="max-h-80 overflow-y-auto">
            <Show
              when={filteredNotifications().length > 0}
              fallback={
                <div class="p-6 text-center text-sm text-ink-muted">
                  {i18n.t("dashboard.noNotifications")}
                </div>
              }
            >
              <For each={filteredNotifications()}>
                {(n) => (
                  <button
                    onClick={() => markRead(n.id)}
                    class={`w-full text-left flex items-start gap-3 p-4 hover:bg-canvas-subtle/50 transition-colors border-b border-border/50 last:border-0 ${n.read ? "opacity-60" : ""}`}
                  >
                    {typeIcon(n.type)}
                    <div class="flex-1 min-w-0">
                      <p class="text-sm font-medium text-ink truncate">{n.title}</p>
                      <p class="text-xs text-ink-muted mt-0.5">{n.message}</p>
                      <Show when={n.time}>
                        <p class="text-[10px] text-ink-subtle mt-1">{n.time}</p>
                      </Show>
                    </div>
                    {!n.read && <span class="w-2 h-2 rounded-full bg-accent shrink-0 mt-1" />}
                  </button>
                )}
              </For>
            </Show>
          </div>
        </div>
        <div class="fixed inset-0 z-40" onClick={() => setOpen(false)} />
      </Show>
    </div>
  );
}
