"use client";

import Image from "next/image";
import dynamic from "next/dynamic";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { BookOpen } from "lucide-react";
import { Content as DialogPrimitiveContent } from "@radix-ui/react-dialog";
import {
  Dialog,
  DialogPortal,
  DialogOverlay,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";

const PdfFlipbook = dynamic(() => import("./pdf-flipbook"), { ssr: false });

interface LifiCardProps {
  title: string;
  date: string;
  fileUrl?: string;
  coverImage?: string;
}

function formatMonthYear(isoDate: string): string {
  if (!isoDate) return "";
  try {
    return new Date(isoDate).toLocaleDateString("ar-SA", {
      month: "long",
      year: "numeric",
    });
  } catch {
    return isoDate;
  }
}

export default function LifiCard({
  title,
  date,
  fileUrl,
  coverImage = "/images/lifi/book-cover.png",
}: LifiCardProps) {
  const t = useTranslations("lifi.viewer");
  const formattedDate = formatMonthYear(date);
  const [open, setOpen] = useState(false);

  const inner = (
    <div className="group/card bg-card border border-border rounded-2xl p-6 shadow-[8px_13px_16px_0px_rgba(147,147,147,0.1)] flex flex-col gap-10 items-center transition-all hover:shadow-[8px_13px_24px_0px_rgba(147,147,147,0.15)] hover:border-primary-500/20 h-full">
      <div className="relative w-[173px] h-[250px] shrink-0 overflow-hidden">
        <Image
          src={coverImage}
          alt={title}
          fill
          className="object-contain"
          priority={false}
        />
        {fileUrl && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/0 opacity-0 transition-all duration-200 group-hover/card:bg-black/35 group-hover/card:opacity-100">
            <span className="flex items-center gap-1.5 rounded-full bg-white/95 px-3 py-1.5 text-xs font-medium text-foreground shadow-sm">
              <BookOpen className="size-3.5 text-primary-500" />
              {t("readHint")}
            </span>
          </div>
        )}
      </div>
      <div className="flex flex-col gap-4 items-start w-full">
        <h3 className="font-bold text-xl leading-[1.4] text-foreground text-start w-full">
          {title}
        </h3>
        {formattedDate && (
          <p className="font-normal text-base leading-[1.4] text-muted-foreground text-start w-full">
            {formattedDate}
          </p>
        )}
      </div>
    </div>
  );

  if (fileUrl) {
    return (
      <>
        <button
          type="button"
          onClick={() => setOpen(true)}
          className="block h-full w-full text-start"
        >
          {inner}
        </button>
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogPortal>
            <DialogOverlay className="bg-black/85 backdrop-blur-sm" />
            <DialogPrimitiveContent
              onOpenAutoFocus={(e) => e.preventDefault()}
              className="fixed inset-0 z-50 flex flex-col outline-none data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
            >
              <DialogTitle className="sr-only">{title}</DialogTitle>
              {formattedDate && (
                <DialogDescription className="sr-only">{formattedDate}</DialogDescription>
              )}
              {open && (
                <PdfFlipbook
                  fileUrl={fileUrl}
                  title={title}
                  onClose={() => setOpen(false)}
                />
              )}
            </DialogPrimitiveContent>
          </DialogPortal>
        </Dialog>
      </>
    );
  }

  return inner;
}
