"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import { useTranslations } from "next-intl";
import { FileText, Award, Download, Eye, ExternalLink } from "lucide-react";

const extractUrl = (v: any): string => {
  if (!v) return "";
  if (typeof v === "string") return v;
  if (typeof v === "object" && typeof v.url === "string") return v.url;
  return "";
};

export default function DocumentsSection({
  data,
  onOpenDocumentPreview,
}: {
  data: any;
  onOpenDocumentPreview: (url: string, title: string) => void;
}) {
  const t = useTranslations("HORSES_DETAILS");
  const [previewDoc, setPreviewDoc] = useState<{
    title: string;
    url: string;
  } | null>(null);

  const docs = [
    {
      key: "owner_document",
      name: t("ownerDoc"),
      hint: t("doc_hint_owner"),
      url: extractUrl(data?.media_files?.owner_document),
      icon: FileText,
    },
    {
      key: "info_certificate",
      name: t("infoCert"),
      hint: t("doc_hint_info"),
      url: extractUrl(data?.media_files?.info_certificate),
      icon: Award,
    },
    {
      key: "medical_exam_certificate",
      name: t("medicalCert"),
      hint: t("doc_hint_medical"),
      url: extractUrl(data?.media_files?.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) => {
    const a = document.createElement("a");
    a.href = url;
    a.download = "";
    document.body.appendChild(a);
    a.click();
    a.remove();
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: 0.3 }}
      className="space-y-4"
    >
      {/* Documents Section Card */}
      <div className="bg-white rounded-2xl border border-slate-200/60 shadow-lg 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-[#16C172] shadow-[0_0_0_4px_rgba(22,193,114,0.15)]" />
            {t("documents")}
          </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-2 bg-gradient-to-b from-[#16C172] to-[#0FB766] 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-[#16C172]" />
                    </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">{t("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">{t("open")}</span>
                    </a>
                    <button
                      onClick={() => handleDownload(d.url)}
                      className="h-8 px-2.5 rounded-full border-0 bg-gradient-to-b from-[#16C172] to-[#0FB766] text-white font-bold text-xs flex items-center gap-1.5 shadow-[0_8px_16px_rgba(22,193,114,0.22)] transition-all hover:-translate-y-0.5 active:scale-95"
                    >
                      <Download className="w-3.5 h-3.5" />
                      <span className="hidden sm:inline">{t("download")}</span>
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <p className="text-slate-500 text-sm py-4 text-center">{t("notAvailable")}</p>
        )}
      </div>

      {/* Inline Document Preview (same page) */}
      {previewDoc && (
        <div className="bg-white rounded-2xl border border-slate-200/60 shadow-lg 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-gradient-to-br from-[#16C172] to-[#0FB766] 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">{t("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" />
                {t("open")}
              </a>
              <button
                onClick={() => handleDownload(previewDoc.url)}
                className="h-8 px-3 rounded-full bg-gradient-to-b from-[#16C172] to-[#0FB766] text-white font-bold text-xs flex items-center gap-1.5 shadow-md transition-all"
              >
                <Download className="w-3.5 h-3.5" />
                {t("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">{t("preview_not_supported")}</p>
                <a
                  href={previewDoc.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="mt-3 text-[#16C172] hover:underline text-sm font-bold"
                >
                  {t("open_in_new_window")}
                </a>
              </div>
            )}
          </div>
        </div>
      )}
    </motion.div>
  );
}
