"use client";

import { useState } from "react";
import { Lang } from "@/lib/config";
import LeadGateModal, { LeadFormData } from "./LeadGateModal";

interface GatedPDFDownloadProps {
  resourceTitle: string;
  resourceType: "guide" | "case-study" | "whitepaper" | "template";
  pdfUrl?: string;
  lang: Lang;
  className?: string;
}

export default function GatedPDFDownload({
  resourceTitle,
  resourceType,
  pdfUrl,
  lang,
  className = "",
}: GatedPDFDownloadProps) {
  const isAr = lang === "ar";
  const [isUnlocked, setIsUnlocked] = useState(false);
  const [showGate, setShowGate] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDownloadClick = () => {
    if (!isUnlocked) {
      setShowGate(true);
    } else {
      handleDownload();
    }
  };

  const handleDownload = () => {
    setIsDownloading(true);

    // Simulate PDF generation/download
    // In a real implementation, this would trigger a server-side PDF generation
    setTimeout(() => {
      setIsDownloading(false);

      // Create download link
      if (pdfUrl) {
        const link = document.createElement("a");
        link.href = pdfUrl;
        link.download = `${resourceTitle.replace(/\s+/g, "-").toLowerCase()}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }, 1000);
  };

  const handleLeadSubmit = async (data: LeadFormData) => {
    try {
      // Get CSRF token from cookie
      const csrfToken = document.cookie
        .split("; ")
        .find((row) => row.startsWith("csrf-token="))
        ?.split("=")[1];

      if (!csrfToken) {
        throw new Error("CSRF token not found");
      }

      const response = await fetch("/api/leads/resource-download", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          ...data,
          resourceTitle,
          resourceType,
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to submit");
      }

      setIsUnlocked(true);
      setShowGate(false);

      // Auto-download after unlock
      setTimeout(() => handleDownload(), 500);
    } catch (error) {
      throw error;
    }
  };

  return (
    <>
      <button
        onClick={handleDownloadClick}
        disabled={isDownloading}
        className={`w-full flex items-center justify-center gap-2 px-6 py-3 border-2 ${
          isUnlocked
            ? "border-brand-green bg-brand-green text-white hover:bg-brand-green-dark"
            : "border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-300 hover:border-brand-green hover:text-brand-green dark:hover:text-brand-green"
        } rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed font-medium ${className}`}
      >
        {isDownloading ? (
          <>
            <svg
              className="animate-spin h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              />
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              />
            </svg>
            {isAr ? "جارٍ التحميل..." : "Downloading..."}
          </>
        ) : !isUnlocked ? (
          <>
            <svg
              className="w-5 h-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
              />
            </svg>
            {isAr ? "تحميل PDF" : "Download PDF"}
          </>
        ) : (
          <>
            <svg
              className="w-5 h-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
              />
            </svg>
            {isAr ? "تحميل PDF" : "Download PDF"}
          </>
        )}
      </button>

      <LeadGateModal
        isOpen={showGate}
        onClose={() => setShowGate(false)}
        onSubmit={handleLeadSubmit}
        resourceTitle={resourceTitle}
        resourceType={resourceType}
        lang={lang}
      />
    </>
  );
}
