"use client";

import React, { useEffect, useState, useSyncExternalStore } from "react";
import { createPortal } from "react-dom";
import {
  X,
  Download,
  ExternalLink,
  Tv,
  Loader2,
  Server,
  CheckCircle2,
  AlertCircle,
  Copy,
  ShieldCheck,
} from "lucide-react";
import { isMdriveLink, resolveMdriveLinks } from "../services/scraper";

interface DownloadModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  initialUrl: string;
  label?: string;
}

function useIsClient() {
  return useSyncExternalStore(
    () => () => {},
    () => true,
    () => false
  );
}

export function DownloadModal({
  isOpen,
  onClose,
  title,
  initialUrl,
  label = "",
}: DownloadModalProps) {
  const isClient = useIsClient();
  const [loading, setLoading] = useState(() => isMdriveLink(initialUrl));
  const [resolvedLinks, setResolvedLinks] = useState<string[]>(() =>
    isMdriveLink(initialUrl) ? [] : [initialUrl]
  );
  const [copiedIndex, setCopiedIndex] = useState<number | null>(null);

  // Extract episode label if series
  const extractEpisode = (text: string): string | null => {
    const combined = `${label} ${text} ${title}`;
    const match = combined.match(/\b(S\d{1,2}E\d{1,2}|E\d{1,3}|Episode\s*\d{1,3}|Ep\s*\d{1,3})\b/i);
    return match ? match[0].toUpperCase() : null;
  };

  const episodeBadge = extractEpisode(label);

  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      }
    };

    window.addEventListener("keydown", handleKeyDown);

    let isMounted = true;

    async function fetchLinks() {
      if (!isMdriveLink(initialUrl)) {
        if (isMounted) {
          setResolvedLinks([initialUrl]);
          setLoading(false);
        }
        return;
      }

      try {
        const links = await resolveMdriveLinks(initialUrl);
        if (!isMounted) return;
        if (links.length > 0) {
          setResolvedLinks(links);
        } else {
          setResolvedLinks([initialUrl]);
        }
      } catch {
        if (!isMounted) return;
        setResolvedLinks([initialUrl]);
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    }

    fetchLinks();

    return () => {
      isMounted = false;
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, initialUrl, onClose]);

  if (!isClient || !isOpen) return null;

  const getServerName = (url: string): { name: string; tag: string } => {
    try {
      const parsed = new URL(url);
      const host = parsed.hostname.toLowerCase();
      if (host.includes("hubcloud")) return { name: "HubCloud Fast Server", tag: "Fast" };
      if (host.includes("gdflix")) return { name: "GDFlix Google Drive", tag: "Instant" };
      if (host.includes("gdtot")) return { name: "GDTot Direct Drive", tag: "Fast" };
      if (host.includes("gdmirror")) return { name: "GDMirror Multi Server", tag: "Mirror" };
      if (host.includes("filepress")) return { name: "FilePress High-Speed", tag: "Ultra" };
      if (host.includes("fast-dl")) return { name: "Fast-DL Server", tag: "Direct" };
      if (host.includes("sdrive")) return { name: "SDrive Cloud Server", tag: "Direct" };
      if (host.includes("mdrive")) return { name: "MDrive Master Link", tag: "Primary" };
      return { name: parsed.hostname, tag: "Download" };
    } catch {
      return { name: "Cloud Server", tag: "Download" };
    }
  };

  const handleOpenLink = (url: string, _index: number) => {
    window.open(url, "_blank", "noopener,noreferrer");
  };

  const handleCopyLink = (url: string, index: number, e: React.MouseEvent) => {
    e.stopPropagation();
    navigator.clipboard.writeText(url);
    setCopiedIndex(index);
    setTimeout(() => setCopiedIndex(null), 2000);
  };

  return createPortal(
    <div
      id="download-modal-backdrop"
      onClick={onClose}
      className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-black/80 backdrop-blur-xl animate-in fade-in duration-200"
    >
      <div
        id="download-modal-container"
        onClick={(e) => e.stopPropagation()}
        className="relative w-full max-w-lg max-h-[85vh] flex flex-col rounded-3xl bg-neutral-950/95 border border-white/15 shadow-[0_0_50px_rgba(220,38,38,0.25)] overflow-hidden animate-in zoom-in-95 duration-200"
      >
        {/* Modal Header */}
        <div className="flex items-start justify-between p-5 sm:p-6 border-b border-white/10 bg-white/[0.02]">
          <div className="space-y-1.5 pr-4">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-red-600/90 text-white shadow-sm">
                <Download className="w-3.5 h-3.5" />
                Download Link
              </span>
              {episodeBadge && (
                <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-red-950 text-red-400 border border-red-500/40">
                  <Tv className="w-3.5 h-3.5" />
                  {episodeBadge}
                </span>
              )}
            </div>
            <h2 className="text-base sm:text-lg font-bold text-white leading-snug line-clamp-2">
              {title}
            </h2>
            {label && (
              <p className="text-xs text-red-400 font-medium tracking-wide">
                {label}
              </p>
            )}
          </div>

          <button
            id="download-modal-close-btn"
            onClick={onClose}
            aria-label="Close download modal"
            className="p-2 rounded-full bg-white/5 hover:bg-white/10 text-white/70 hover:text-white border border-white/10 transition-colors shrink-0"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-5 sm:p-6 space-y-4 custom-scrollbar">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-12 space-y-4 text-center">
              <Loader2 className="w-10 h-10 text-red-500 animate-spin" />
              <div className="space-y-1">
                <p className="text-sm font-semibold text-white">
                  Resolving High-Speed Cloud Servers...
                </p>
                <p className="text-xs text-white/50">
                  Checking HubCloud, GDFlix, and Direct Mirrors
                </p>
              </div>
            </div>
          ) : resolvedLinks.length > 0 ? (
            <div className="space-y-3">
              <div className="flex items-center justify-between text-xs text-white/60 px-1">
                <span className="flex items-center gap-1.5">
                  <ShieldCheck className="w-4 h-4 text-emerald-400" />
                  Select a server to begin download:
                </span>
                <span className="text-white/40">{resolvedLinks.length} servers available</span>
              </div>

              {resolvedLinks.map((link, idx) => {
                const server = getServerName(link);
                const rowEpisode = extractEpisode(link);

                return (
                  <div
                    key={idx}
                    id={`server-link-${idx}`}
                    onClick={() => handleOpenLink(link, idx)}
                    className="group flex items-center justify-between p-3.5 sm:p-4 rounded-2xl bg-white/[0.04] hover:bg-red-600/10 border border-white/10 hover:border-red-500/50 transition-all duration-200 cursor-pointer shadow-sm hover:shadow-[0_0_15px_rgba(220,38,38,0.2)]"
                  >
                    <div className="flex items-center gap-3 min-w-0 pr-2">
                      <div className="w-10 h-10 rounded-xl bg-red-600/20 text-red-400 group-hover:bg-red-600 group-hover:text-white flex items-center justify-center border border-red-500/30 transition-all shrink-0">
                        <Server className="w-5 h-5" />
                      </div>
                      <div className="min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-semibold text-white group-hover:text-red-400 transition-colors truncate">
                            {server.name}
                          </span>
                          <span className="px-1.5 py-0.2 rounded text-[10px] font-bold uppercase bg-white/10 text-white/80 border border-white/10">
                            {server.tag}
                          </span>
                          {rowEpisode && (
                            <span className="px-1.5 py-0.2 rounded text-[10px] font-bold uppercase bg-red-950 text-red-400 border border-red-500/30">
                              {rowEpisode}
                            </span>
                          )}
                        </div>
                        <p className="text-[11px] text-white/40 group-hover:text-white/60 transition-colors truncate max-w-[240px] sm:max-w-[280px]">
                          {link}
                        </p>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 shrink-0">
                      <button
                        onClick={(e) => handleCopyLink(link, idx, e)}
                        title="Copy link"
                        aria-label="Copy server link"
                        className="p-2 rounded-lg bg-white/5 hover:bg-white/15 text-white/60 hover:text-white transition-colors"
                      >
                        {copiedIndex === idx ? (
                          <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                        ) : (
                          <Copy className="w-4 h-4" />
                        )}
                      </button>

                      <div className="flex items-center gap-1 px-3 py-1.5 rounded-xl bg-red-600 text-white text-xs font-semibold shadow-md group-hover:bg-red-500 transition-colors">
                        <span>Open</span>
                        <ExternalLink className="w-3.5 h-3.5" />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center py-10 space-y-3 text-center">
              <AlertCircle className="w-10 h-10 text-yellow-500/80" />
              <p className="text-sm text-white/80 font-medium">
                No direct cloud links extracted yet.
              </p>
              <button
                onClick={() => handleOpenLink(initialUrl, 0)}
                className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-red-600 hover:bg-red-500 text-white text-sm font-semibold transition-colors shadow-lg"
              >
                <span>Open Source Download Page</span>
                <ExternalLink className="w-4 h-4" />
              </button>
            </div>
          )}

          {/* Quick Notice */}
          <div className="p-3.5 rounded-2xl bg-white/[0.02] border border-white/5 text-[11px] text-white/50 space-y-1">
            <p className="font-semibold text-white/70">Tip for Fastest Download:</p>
            <p>
              If a server displays a timer, wait for it or try HubCloud/GDFlix servers for instant direct downloads.
            </p>
          </div>
        </div>

        {/* Modal Footer */}
        <div className="p-4 sm:p-5 border-t border-white/10 bg-white/[0.02] flex items-center justify-between">
          <span className="text-xs text-white/40 font-mono">PK Movies Secure Link</span>
          <button
            id="download-modal-dismiss-btn"
            onClick={onClose}
            className="px-4 py-2 rounded-xl bg-white/10 hover:bg-white/15 text-white text-xs font-medium border border-white/10 transition-colors"
          >
            Close
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}
