"use client";

import Link from "next/link";
import { useActionState, useEffect, useTransition } from "react";
import { ArrowRight, Check, CheckCheck, Loader2 } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  markAllNotificationsReadAction,
  markNotificationReadAction,
} from "@/lib/appwrite/notification-actions";
import { initialNotificationActionState } from "@/lib/appwrite/notification-types";
import type { Notification } from "@/lib/appwrite/schema";

const dateFormatter = new Intl.DateTimeFormat("tr-TR", {
  day: "2-digit",
  month: "2-digit",
  year: "numeric",
  hour: "2-digit",
  minute: "2-digit",
});

export function NotificationsList({ rows }: { rows: Notification[] }) {
  const unread = rows.filter((r) => !r.read).length;

  if (rows.length === 0) {
    return (
      <p className="text-muted-foreground py-6 text-center text-sm">
        Henüz bildirim yok.
      </p>
    );
  }

  return (
    <div className="space-y-3">
      {unread > 0 && (
        <div className="flex justify-end">
          <MarkAllReadButton />
        </div>
      )}
      <ul className="divide-y rounded-md border">
        {rows.map((n) => (
          <NotificationRow key={n.$id} row={n} />
        ))}
      </ul>
    </div>
  );
}

function NotificationRow({ row }: { row: Notification }) {
  const [state, action, pending] = useActionState(
    markNotificationReadAction,
    initialNotificationActionState,
  );
  const [, startTransition] = useTransition();

  useEffect(() => {
    if (state.error) toast.error(state.error);
  }, [state]);

  const link = row.jobId
    ? `/jobs/${row.jobId}`
    : row.connectionId
      ? "/connections"
      : null;

  return (
    <li className={`flex items-start gap-3 px-3 py-3 ${row.read ? "opacity-70" : ""}`}>
      <span
        className={`mt-1.5 size-2 shrink-0 rounded-full ${row.read ? "bg-muted" : "bg-primary"}`}
        aria-hidden
      />
      <div className="min-w-0 flex-1">
        <p className="text-sm">{row.message}</p>
        <p className="text-muted-foreground mt-0.5 text-xs">
          {dateFormatter.format(new Date(row.$createdAt))}
        </p>
      </div>
      {!row.read && (
        <Badge variant="secondary" className="text-[10px] uppercase">
          Yeni
        </Badge>
      )}
      {link && (
        <Button asChild variant="ghost" size="sm">
          <Link href={link}>
            <ArrowRight className="size-4" />
          </Link>
        </Button>
      )}
      {!row.read && (
        <form
          action={(fd) => {
            startTransition(() => action(fd));
          }}
        >
          <input type="hidden" name="id" value={row.$id} />
          <Button type="submit" size="sm" variant="outline" disabled={pending}>
            {pending ? <Loader2 className="size-4 animate-spin" /> : <Check className="size-4" />}
          </Button>
        </form>
      )}
    </li>
  );
}

function MarkAllReadButton() {
  const [pending, startTransition] = useTransition();

  return (
    <Button
      size="sm"
      variant="outline"
      disabled={pending}
      onClick={() =>
        startTransition(async () => {
          const res = await markAllNotificationsReadAction();
          if (res.ok) toast.success("Tümü okundu olarak işaretlendi.");
          else if (res.error) toast.error(res.error);
        })
      }
    >
      {pending ? <Loader2 className="size-4 animate-spin" /> : <CheckCheck className="size-4" />}
      Hepsini okundu işaretle
    </Button>
  );
}
