"use client";

import Image from "next/image";
import Link from "next/link";
import { useAppSelector } from "@/store/hooks";
import {
  selectSearchResults,
  selectSearchQuery,
  selectSearchLoading,
  selectSearchTotal,
} from "@/store/slices/searchSlice";
import type { SearchContentItem } from "@/types/api/search.types";

function isValidImg(url?: string) {
  return !!url && !url.includes("no_img");
}
function fmtRelTime(dateStr: string) {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60_000);
  const hrs = Math.floor(mins / 60);
  if (mins < 60) return `${mins}m ago`;
  if (hrs < 24) return `${hrs}h ago`;
  return `${Math.floor(hrs / 24)}d ago`;
}
function fmtViews(n: number) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
  return String(n);
}
function getHref(item: SearchContentItem): string {
  if (item.type === 3 && item.live_url) return item.live_url;
  if (item.type === 4) return `/channel/${item.channel_id}`;
  return `/detail/${item.id}`;
}
function getTypeBadge(type: number) {
  if (type === 3) return { label: "LIVE", color: "var(--live)" };
  if (type === 4) return { label: "SHOW", color: "#6d28d9" };
  return null;
}

function ResultCard({ item }: { item: SearchContentItem }) {
  const href = getHref(item);
  const img = isValidImg(item.web_image) ? item.web_image
    : isValidImg(item.landscape_img) ? item.landscape_img
    : null;
  const badge = getTypeBadge(item.type);
  const isExternal = href.startsWith("http");

  const content = (
    <>
      {/* Thumbnail */}
      <div
        style={{
          flexShrink: 0,
          width: 120,
          height: 80,
          borderRadius: 8,
          overflow: "hidden",
          position: "relative",
          background: "#e5e7eb",
        }}
      >
        {img ? (
          <Image src={img} alt="" fill style={{ objectFit: "cover" }} unoptimized />
        ) : (
          <div
            style={{
              width: "100%",
              height: "100%",
              background: item.type === 3 ? "#1e1b4b" : item.type === 4 ? "#1a1a2e" : "#f3f4f6",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            {item.type === 3 && (
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="1.5">
                <rect x="2" y="5" width="20" height="14" rx="2" />
              </svg>
            )}
            {item.type === 4 && (
              <svg width="20" height="20" viewBox="0 0 24 24" fill="rgba(255,255,255,0.5)">
                <polygon points="6 4 20 12 6 20" />
              </svg>
            )}
          </div>
        )}
        {badge && (
          <span
            style={{
              position: "absolute",
              top: 6,
              left: 6,
              background: badge.color,
              color: "#fff",
              fontSize: 9,
              fontWeight: 800,
              letterSpacing: "0.07em",
              padding: "2px 6px",
              borderRadius: 3,
              display: "flex",
              alignItems: "center",
              gap: 3,
            }}
          >
            {item.type === 3 && (
              <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#fff", animation: "pulse 1.5s infinite" }} />
            )}
            {badge.label}
          </span>
        )}
        {item.is_premium === 1 && (
          <span
            style={{
              position: "absolute",
              bottom: 6,
              right: 6,
              background: "#b45309",
              color: "#fff",
              fontSize: 8,
              fontWeight: 700,
              padding: "1px 5px",
              borderRadius: 3,
            }}
          >
            PREMIUM
          </span>
        )}
      </div>

      {/* Content */}
      <div style={{ flex: 1, minWidth: 0 }}>
        {(item.category || item.type !== 1) && (
          <span
            style={{
              display: "inline-block",
              fontSize: 10,
              fontWeight: 700,
              letterSpacing: "0.08em",
              textTransform: "uppercase",
              color: item.type === 3 ? "var(--live)" : item.type === 4 ? "#6d28d9" : "var(--brand)",
              marginBottom: 5,
            }}
          >
            {item.type === 1 ? item.category : item.type === 3 ? "Live News" : "Show"}
          </span>
        )}
        <h3
          style={{
            fontSize: "0.9375rem",
            fontWeight: 600,
            lineHeight: 1.4,
            margin: "0 0 6px",
            color: "var(--ink)",
            display: "-webkit-box",
            WebkitLineClamp: 2,
            WebkitBoxOrient: "vertical",
            overflow: "hidden",
          }}
        >
          {item.title}
        </h3>
        {item.short_description && (
          <p
            style={{
              fontSize: "0.8125rem",
              color: "var(--text-secondary)",
              lineHeight: 1.5,
              margin: "0 0 6px",
              display: "-webkit-box",
              WebkitLineClamp: 2,
              WebkitBoxOrient: "vertical",
              overflow: "hidden",
            }}
          >
            {item.short_description}
          </p>
        )}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: "0.625rem",
            fontSize: "0.75rem",
            fontFamily: "var(--mono)",
            color: "var(--text-tertiary)",
            flexWrap: "wrap",
          }}
        >
          <span>{fmtRelTime(item.created_at)}</span>
          {item.total_view > 0 && (
            <>
              <span>·</span>
              <span>{fmtViews(item.total_view)} views</span>
            </>
          )}
          {item.language && (
            <>
              <span>·</span>
              <span>{item.language}</span>
            </>
          )}
          {item.type === 1 && Array.isArray(item.hashtag) && item.hashtag.length > 0 && (
            <>
              <span>·</span>
              {item.hashtag.slice(0, 2).map((h) => (
                <span key={h.id} style={{ color: "var(--brand)" }}>#{h.name}</span>
              ))}
            </>
          )}
          {isExternal && (
            <>
              <span>·</span>
              <span style={{ display: "flex", alignItems: "center", gap: 2 }}>
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
                  <polyline points="15 3 21 3 21 9" />
                  <line x1="10" y1="14" x2="21" y2="3" />
                </svg>
                External
              </span>
            </>
          )}
        </div>
      </div>
    </>
  );

  const sharedStyle: React.CSSProperties = {
    display: "flex",
    gap: "1rem",
    alignItems: "flex-start",
    padding: "1rem 0",
    borderBottom: "1px solid var(--border)",
    textDecoration: "none",
    color: "inherit",
  };

  if (isExternal) {
    return (
      <a href={href} target="_blank" rel="noopener noreferrer" style={sharedStyle}>
        {content}
      </a>
    );
  }
  return (
    <Link href={href} style={sharedStyle}>
      {content}
    </Link>
  );
}

// ── Skeleton loader ──────────────────────────────────────────────────────────
function SkeletonCard() {
  return (
    <div style={{ display: "flex", gap: "1rem", padding: "1rem 0", borderBottom: "1px solid var(--border)" }}>
      <div style={{ flexShrink: 0, width: 120, height: 80, borderRadius: 8, background: "#e5e7eb" }} />
      <div style={{ flex: 1 }}>
        <div style={{ height: 10, width: "30%", borderRadius: 4, background: "#e5e7eb", marginBottom: 8 }} />
        <div style={{ height: 14, width: "90%", borderRadius: 4, background: "#e5e7eb", marginBottom: 6 }} />
        <div style={{ height: 14, width: "70%", borderRadius: 4, background: "#e5e7eb", marginBottom: 10 }} />
        <div style={{ height: 10, width: "40%", borderRadius: 4, background: "#e5e7eb" }} />
      </div>
    </div>
  );
}

export default function SearchResults() {
  const results = useAppSelector(selectSearchResults);
  const query   = useAppSelector(selectSearchQuery);
  const loading = useAppSelector(selectSearchLoading);
  const total   = useAppSelector(selectSearchTotal);

  if (loading) {
    return (
      <section className="results-col">
        {Array.from({ length: 6 }).map((_, i) => <SkeletonCard key={i} />)}
      </section>
    );
  }

  if (!query) {
    return (
      <section className="results-col">
        <div style={{ padding: "3rem 0", textAlign: "center", color: "var(--text-secondary)" }}>
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" style={{ marginBottom: "1rem", opacity: 0.4 }}>
            <circle cx="11" cy="11" r="7" />
            <path d="m20 20-3-3" />
          </svg>
          <p style={{ fontWeight: 600, marginBottom: "0.5rem" }}>Search DTNews</p>
          <p style={{ fontSize: "0.875rem" }}>Type a keyword and press Enter</p>
        </div>
      </section>
    );
  }

  if (results.length === 0) {
    return (
      <section className="results-col">
        <div style={{ padding: "3rem 0", textAlign: "center", color: "var(--text-secondary)" }}>
          <p style={{ fontWeight: 600, marginBottom: "0.5rem" }}>No results for &ldquo;{query}&rdquo;</p>
          <p style={{ fontSize: "0.875rem" }}>Try different keywords or switch to another tab</p>
        </div>
      </section>
    );
  }

  return (
    <section className="results-col">
      <div style={{ fontSize: "0.8125rem", color: "var(--text-secondary)", marginBottom: "0.75rem", fontFamily: "var(--mono)" }}>
        {total.toLocaleString()} results
      </div>
      {results.map((item) => (
        <ResultCard key={`${item.type}-${item.id}`} item={item} />
      ))}
    </section>
  );
}
