"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { FileText, Award, Download, Eye, ExternalLink } from "lucide-react";
import type { AuctionItem } from "../types";

export default function DocumentsSection({ item }: { item: AuctionItem }) {
  const [previewDoc, setPreviewDoc] = useState<{
    title: string;
    url: string;
  } | null>(null);
  const tDocs = useTranslations("SINGLE_AUCTION.DOCUMENTS");
  const tActions = useTranslations("SINGLE_AUCTION.ACTIONS");

  const media = item?.media_files || {};

  const normalizeUrl = (val: unknown): string => {
    if (!val) return "";
    if (typeof val === "string") return val;
    if (
      typeof val === "object" &&
      "url" in val &&
      typeof val.url === "string"
    ) {
      return val.url;
    }
    return "";
  };

  const docs = [
    {
      key: "owner_document",
      name: tDocs("owner"),
      hint: "PDF / صورة — عرض أو تحميل",
      url: normalizeUrl(media.owner_document),
      icon: FileText,
    },
    {
      key: "info_certificate",
      name: tDocs("info"),
      hint: "PDF — عرض / فتح / تحميل",
      url: normalizeUrl(media.info_certificate),
      icon: Award,
    },
    {
      key: "medical_exam_certificate",
      name: tDocs("medical"),
      hint: "PDF — شهادة الفحص البيطري",
      url: normalizeUrl(media.medical_exam_certificate),
      icon: Award,
    },
  ].filter((d) => !!d.url);

  const handlePreview = (doc: { name: string; url: string }) => {
    if (!doc.url) return;
    setPreviewDoc({ title: doc.name, url: doc.url });
  };

  const handleDownload = (url: string) => {
    if (!url) return;
    const link = document.createElement("a");
    link.href = url;
    link.target = "_blank";
    link.rel = "noopener noreferrer";
    link.download = "";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="space-y-4">
      {/* Documents Section Card */}
      <div className="bg-white rounded-2xl border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)] p-4 sm:p-5">
        {/* Section Header */}
        <div className="flex items-center justify-between gap-3 mb-4">
          <h3 className="text-lg font-black text-[#0b1b13] flex items-center gap-2.5">
            <span className="w-2.5 h-2.5 rounded-full bg-[#0F5132] shadow-[0_0_0_4px_rgba(15,81,50,0.14)]" />
            {tDocs("title")}
          </h3>
        </div>

        {docs.length > 0 ? (
          <div className="grid sm:grid-cols-2 gap-3">
            {docs.map((d, i) => {
              const IconComponent = d.icon;
              return (
                <div
                  key={i}
                  className="relative overflow-hidden rounded-2xl border border-slate-200/80 p-3.5 sm:p-4 bg-gradient-to-b from-white to-slate-50/50 flex items-center justify-between gap-3 group hover:shadow-md transition-shadow"
                >
                  {/* Right accent bar */}
                  <div className="absolute right-0 top-0 bottom-0 w-1.5 bg-[#0F5132] opacity-90 rounded-r-2xl" />

                  {/* Doc Info */}
                  <div className="flex items-center gap-3 min-w-0 flex-1 pr-2">
                    <div className="w-8 h-8 flex items-center justify-center flex-shrink-0">
                      <IconComponent className="w-5 h-5 stroke-[#0F5132]" />
                    </div>
                    <div className="min-w-0">
                      <p className="font-black text-sm text-slate-800 truncate">
                        {d.name}
                      </p>
                      <p className="text-xs text-slate-500 truncate mt-0.5">
                        {d.hint}
                      </p>
                    </div>
                  </div>

                  {/* Actions */}
                  <div className="flex items-center gap-1.5 flex-shrink-0">
                    <button
                      onClick={() => handlePreview(d)}
                      className="h-8 px-2.5 rounded-full border border-slate-200 bg-slate-50 hover:bg-white text-slate-700 font-bold text-xs flex items-center gap-1.5 transition-all hover:-translate-y-0.5 active:scale-95"
                    >
                      <Eye className="w-3.5 h-3.5" />
                      <span className="hidden sm:inline">
                        {tActions("view")}
                      </span>
                    </button>
                    {/* <a
                      href={d.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="h-8 px-2.5 rounded-full border border-slate-200 bg-slate-50 hover:bg-white text-slate-700 font-bold text-xs flex items-center gap-1.5 transition-all hover:-translate-y-0.5 active:scale-95"
                    >
                      <ExternalLink className="w-3.5 h-3.5" />
                      <span className="hidden sm:inline">
                        {tActions("open")}
                      </span>
                    </a> */}
                    <button
                      onClick={() => handleDownload(d.url)}
                      className="h-8 px-2.5 rounded-full border-0 bg-[#0F5132] text-white font-bold text-xs flex items-center gap-1.5 shadow-[0_8px_16px_rgba(15,81,50,0.25)] transition-all hover:-translate-y-0.5 active:scale-95 hover:bg-[#0c432a]"
                    >
                      <Download className="w-3.5 h-3.5" />
                      <span className="hidden sm:inline">
                        {tActions("download")}
                      </span>
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <p className="text-slate-500 text-sm py-4 text-center">
            {tDocs("empty")}
          </p>
        )}
      </div>

      {/* Inline Document Preview (same page) */}
      {previewDoc && (
        <div className="bg-white rounded-2xl border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)] overflow-hidden">
          {/* Preview Header */}
          <div className="flex items-center justify-between gap-3 p-4 border-b border-slate-100 bg-slate-50/50">
            <div className="flex items-center gap-2.5">
              <div className="w-8 h-8 rounded-xl bg-[#0F5132] flex items-center justify-center">
                <FileText className="w-4 h-4 text-white" />
              </div>
              <div>
                <h4 className="font-bold text-slate-800">{previewDoc.title}</h4>
                <p className="text-xs text-slate-500">
                  {tDocs("preview_label")}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <a
                href={previewDoc.url}
                target="_blank"
                rel="noopener noreferrer"
                className="h-8 px-3 rounded-full border border-slate-200 bg-white hover:bg-slate-50 text-slate-700 font-bold text-xs flex items-center gap-1.5 transition-all"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                {tActions("open")}
              </a>
              <button
                onClick={() => handleDownload(previewDoc.url)}
                className="h-8 px-3 rounded-full bg-[#0F5132] text-white font-bold text-xs flex items-center gap-1.5 shadow-md transition-all hover:bg-[#0c432a]"
              >
                <Download className="w-3.5 h-3.5" />
                {tActions("download")}
              </button>
              <button
                onClick={() => setPreviewDoc(null)}
                className="h-8 w-8 rounded-full border border-slate-200 bg-white hover:bg-red-50 text-slate-500 hover:text-red-500 font-bold text-sm flex items-center justify-center transition-all"
              >
                ✕
              </button>
            </div>
          </div>

          {/* Preview Content */}
          <div className="p-4">
            {previewDoc.url.match(/\.(pdf)$/i) ? (
              <iframe
                src={previewDoc.url}
                className="w-full h-[500px] border rounded-xl bg-slate-100"
                title={previewDoc.title}
              />
            ) : previewDoc.url.match(/\.(jpe?g|png|webp|gif)$/i) ? (
              <div className="flex items-center justify-center bg-slate-100 rounded-xl p-4 min-h-[400px]">
                <img
                  src={previewDoc.url}
                  alt={previewDoc.title}
                  className="max-w-full max-h-[500px] rounded-lg shadow-lg object-contain"
                />
              </div>
            ) : (
              <div className="flex flex-col items-center justify-center h-[300px] text-slate-500 border rounded-xl bg-slate-50">
                <FileText className="w-12 h-12 text-slate-300 mb-3" />
                <p className="text-sm">{tDocs("preview_not_supported")}</p>
                <a
                  href={previewDoc.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-3 text-[#0F5132] hover:underline text-sm font-bold"
                >
                  {tActions("open")}
                </a>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
