"use client";

import { useEffect } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import {
  Download,
  Trash2,
  Play,
  HardDriveDownload,
  X,
} from "lucide-react";
import { useDownloadManager } from "@/hooks/useDownloadManager";
import { useTranslation } from "@/i18n";

/* ── helpers ────────────────────────────────────────────────────────────────── */

function formatDate(iso: string) {
  try {
    return new Date(iso).toLocaleDateString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
    });
  } catch {
    return iso;
  }
}

function contentTypeLabel(type: number): string {
  switch (type) {
    case 1:
      return "Movie";
    case 2:
      return "Series";
    case 3:
      return "Episode";
    case 4:
      return "Music";
    case 5:
      return "Short";
    case 7:
      return "Podcast";
    default:
      return "Video";
  }
}

function contentTypeBadgeStyle(type: number): React.CSSProperties {
  switch (type) {
    case 4: // music
      return { background: "rgba(168,85,247,0.12)", color: "#a855f7", border: "1px solid rgba(168,85,247,0.2)" };
    case 5: // short
      return { background: "rgba(239,68,68,0.1)", color: "#ef4444", border: "1px solid rgba(239,68,68,0.18)" };
    default:
      return { background: "rgba(var(--accent-rgb),0.1)", color: "var(--accent)", border: "1px solid rgba(var(--accent-rgb),0.18)" };
  }
}

function playRoute(id: string, contentType: number): string {
  if (contentType === 4) return `/music`;
  if (contentType === 5) return `/reels`;
  return `/video/${id}`;
}

/* ── Empty state ────────────────────────────────────────────────────────────── */

function EmptyState() {
  const { t } = useTranslation();
  return (
    <div
      className="flex flex-col items-center justify-center py-24 gap-4"
      style={{ animation: "dl-rise 0.5s ease both" }}
    >
      <div
        className="w-20 h-20 rounded-full flex items-center justify-center"
        style={{
          background: "rgba(var(--accent-rgb),0.06)",
          border: "1.5px solid rgba(var(--accent-rgb),0.12)",
        }}
      >
        <HardDriveDownload size={32} strokeWidth={1.3} style={{ color: "var(--accent)", opacity: 0.5 }} />
      </div>
      <div className="text-center">
        <p
          className="text-sm font-semibold"
          style={{ color: "var(--text-secondary)" }}
        >
          {t("downloads_empty_title") || "No downloads yet"}
        </p>
        <p
          className="text-[12px] mt-1"
          style={{ color: "var(--text-muted)" }}
        >
          {t("downloads_empty_subtitle") || "Content you download will appear here"}
        </p>
      </div>
    </div>
  );
}

/* ── Download card ──────────────────────────────────────────────────────────── */

function DownloadCard({
  entry,
  index,
  onRemove,
}: {
  entry: {
    id: string;
    contentType: number;
    title: string;
    thumbnail: string;
    url: string;
    downloadedAt: string;
  };
  index: number;
  onRemove: (id: string) => void;
}) {
  const router = useRouter();
  const { t } = useTranslation();

  return (
    <div
      className="relative rounded-2xl overflow-hidden group"
      style={{
        background: "var(--card)",
        border: "1px solid var(--border)",
        boxShadow: "0 2px 12px rgba(0,0,0,0.2)",
        animation: "dl-card-in 0.4s ease both",
        animationDelay: `${index * 60}ms`,
        transition: "border-color 0.2s ease, box-shadow 0.2s ease",
      }}
      onMouseEnter={(e) => {
        (e.currentTarget as HTMLDivElement).style.borderColor = "rgba(var(--accent-rgb),0.3)";
        (e.currentTarget as HTMLDivElement).style.boxShadow = "0 6px 24px rgba(var(--accent-rgb),0.08), 0 2px 12px rgba(0,0,0,0.3)";
      }}
      onMouseLeave={(e) => {
        (e.currentTarget as HTMLDivElement).style.borderColor = "var(--border)";
        (e.currentTarget as HTMLDivElement).style.boxShadow = "0 2px 12px rgba(0,0,0,0.2)";
      }}
    >
      {/* Thumbnail */}
      <div className="relative w-full aspect-video overflow-hidden" style={{ background: "var(--deep)" }}>
        {entry.thumbnail ? (
          <Image
            src={entry.thumbnail}
            alt={entry.title}
            fill
            className="object-cover transition-transform duration-300 group-hover:scale-105"
            unoptimized
          />
        ) : (
          <div className="absolute inset-0 flex items-center justify-center">
            <Download size={28} strokeWidth={1.3} style={{ color: "var(--text-muted)", opacity: 0.4 }} />
          </div>
        )}
        {/* overlay gradient */}
        <div
          className="absolute inset-0 pointer-events-none"
          style={{
            background: "linear-gradient(to top, rgba(0,0,0,0.6) 0%, transparent 50%)",
          }}
        />
        {/* type badge */}
        <span
          className="absolute top-2 left-2 px-2 py-0.5 rounded-md text-[9px] font-black uppercase tracking-widest"
          style={contentTypeBadgeStyle(entry.contentType)}
        >
          {contentTypeLabel(entry.contentType)}
        </span>
        {/* remove button */}
        <button
          onClick={() => onRemove(entry.id)}
          title="Remove download"
          className="absolute top-2 right-2 w-7 h-7 rounded-lg flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 active:scale-95"
          style={{
            background: "rgba(0,0,0,0.6)",
            backdropFilter: "blur(4px)",
            border: "1px solid rgba(255,255,255,0.1)",
            color: "#ef4444",
          }}
        >
          <X size={12} strokeWidth={2.5} />
        </button>
      </div>

      {/* Content */}
      <div className="p-3 flex flex-col gap-2">
        <p
          className="text-[13px] font-semibold line-clamp-2 leading-snug"
          style={{ color: "var(--text-primary)" }}
        >
          {entry.title}
        </p>
        <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
          {t("downloads_saved_on") || "Saved on"} {formatDate(entry.downloadedAt)}
        </p>

        {/* Actions */}
        <div className="flex items-center gap-2 mt-1">
          <button
            onClick={() => router.push(playRoute(entry.id, entry.contentType))}
            className="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-xl text-[12px] font-bold transition-all duration-200 active:scale-95"
            style={{
              background: "linear-gradient(135deg, var(--accent), rgba(var(--accent-rgb),0.8))",
              color: "#fff",
              boxShadow: "0 3px 12px rgba(var(--accent-rgb),0.25)",
            }}
          >
            <Play size={12} fill="white" strokeWidth={0} />
            {t("downloads_play") || "Play"}
          </button>
          <button
            onClick={() => onRemove(entry.id)}
            className="w-9 h-9 flex items-center justify-center rounded-xl transition-all duration-200 active:scale-95"
            style={{
              background: "rgba(239,68,68,0.08)",
              border: "1px solid rgba(239,68,68,0.15)",
              color: "#ef4444",
            }}
          >
            <Trash2 size={14} strokeWidth={2} />
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Main page ──────────────────────────────────────────────────────────────── */

export default function DownloadsPage() {
  const { t } = useTranslation();
  const { downloads, removeDownload, clearAll, refresh } = useDownloadManager();

  // Refresh on mount (localStorage is client-only)
  useEffect(() => {
    refresh();
  }, [refresh]);

  return (
    <>
      <style>{`
        @keyframes dl-rise { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:none; } }
        @keyframes dl-card-in { from { opacity:0; transform:translateY(18px) scale(0.97); } to { opacity:1; transform:none; } }
      `}</style>

      <div
        className="min-h-screen px-4 py-6 pb-28 md:px-6"
        style={{ background: "var(--bg)" }}
      >
        <div className="mx-auto flex flex-col gap-6">
          {/* Header */}
          <div
            className="flex items-center justify-between"
            style={{ animation: "dl-rise 0.35s ease both" }}
          >
            <div className="flex items-center gap-3">
              <div
                className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0"
                style={{
                  background: "rgba(var(--accent-rgb),0.1)",
                  border: "1px solid rgba(var(--accent-rgb),0.18)",
                }}
              >
                <HardDriveDownload size={17} strokeWidth={1.8} style={{ color: "var(--accent)" }} />
              </div>
              <div>
                <h1
                  className="text-lg font-black tracking-tight"
                  style={{ letterSpacing: "-0.02em", color: "var(--text-primary)" }}
                >
                  {t("downloads_title") || "Downloads"}
                </h1>
                <p className="text-[11px] mt-0.5" style={{ color: "var(--text-muted)" }}>
                  {downloads.length > 0
                    ? `${downloads.length} ${t("downloads_items") || "item(s) saved locally"}`
                    : (t("downloads_subtitle") || "Your offline content")}
                </p>
              </div>
            </div>

            {/* Clear All */}
            {downloads.length > 0 && (
              <button
                onClick={clearAll}
                className="flex items-center gap-1.5 px-3 py-2 rounded-xl text-[11px] font-semibold transition-all duration-200 active:scale-95"
                style={{
                  background: "rgba(239,68,68,0.08)",
                  border: "1px solid rgba(239,68,68,0.15)",
                  color: "#ef4444",
                }}
              >
                <Trash2 size={12} strokeWidth={2.2} />
                {t("downloads_clear_all") || "Clear All"}
              </button>
            )}
          </div>

          {/* Content */}
          {downloads.length === 0 ? (
            <EmptyState />
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {downloads.map((entry, i) => (
                <DownloadCard
                  key={entry.id}
                  entry={entry}
                  index={i}
                  onRemove={removeDownload}
                />
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
}
