"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Download, Loader2, Lock } from "lucide-react";
import { toast } from "sonner";
import api from "@/lib/api";
import Link from "next/link";
import type { MagazineIssue } from "@/lib/types";

export default function ReadIssuePage() {
  const params = useParams();
  const router = useRouter();
  const issueId = params.id as string;
  const [issue, setIssue] = useState<MagazineIssue | null>(null);
  const [pdfUrl, setPdfUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [accessDenied, setAccessDenied] = useState(false);

  useEffect(() => {
    // Load issue info
    api.get(`/api/magazine/issues/${issueId}`)
      .then(({ data }) => setIssue(data.data))
      .catch(() => {});

    // Try to load PDF
    api.get(`/api/magazine/issues/${issueId}/view`, { responseType: "blob" })
      .then(({ data }) => {
        const url = URL.createObjectURL(data);
        setPdfUrl(url);
      })
      .catch((err) => {
        if (err.response?.status === 403) {
          setAccessDenied(true);
        } else {
          toast.error("Failed to load PDF");
          router.push("/dashboard/magazine/issues");
        }
      })
      .finally(() => setLoading(false));

    return () => {
      if (pdfUrl) URL.revokeObjectURL(pdfUrl);
    };
  }, [issueId]);

  const handleDownload = async () => {
    try {
      const { data } = await api.get(`/api/magazine/issues/${issueId}/read`, {
        responseType: "blob",
      });
      const url = URL.createObjectURL(data);
      const a = document.createElement("a");
      a.href = url;
      a.download = issue?.pdf_file_name || `${issue?.slug || "magazine"}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      toast.error("Failed to download PDF");
    }
  };

  if (loading) {
    return (
      <div className="flex h-[60vh] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (accessDenied) {
    return (
      <div className="flex h-[60vh] flex-col items-center justify-center gap-4">
        <Lock className="h-12 w-12 text-muted-foreground" />
        <h2 className="text-xl font-semibold">Subscription Required</h2>
        <p className="text-muted-foreground">
          You need an active subscription to access this issue.
        </p>
        <Button asChild>
          <Link href="/dashboard/magazine/issues">Back to Issues</Link>
        </Button>
      </div>
    );
  }

  return (
    <div className="flex h-[calc(100vh-4rem)] flex-col">
      {/* Header */}
      <div className="flex items-center justify-between border-b px-4 py-3">
        <div className="flex items-center gap-3">
          <Button variant="ghost" size="sm" asChild>
            <Link href="/dashboard/magazine/issues">
              <ArrowLeft className="mr-2 h-4 w-4" /> Back
            </Link>
          </Button>
          {issue && (
            <h1 className="text-lg font-semibold">{issue.title}</h1>
          )}
        </div>
        <Button variant="outline" size="sm" onClick={handleDownload}>
          <Download className="mr-2 h-4 w-4" /> Download
        </Button>
      </div>

      {/* PDF Viewer */}
      {pdfUrl && (
        <iframe
          src={pdfUrl}
          className="flex-1 w-full border-0"
          title={issue?.title || "Magazine PDF"}
        />
      )}
    </div>
  );
}
