"use client"

import styles from "./asset-details.module.scss"
import PageIntro from "../PageIntro"
import logo from "../../../../images/btc-logo.svg"
import { useEffect, useRef, useState } from "react"
import CryptoNews from "../CryptoNews"

const AssetDetails: React.FC = () => {
  const containerRef = useRef<HTMLDivElement | null>(null)
  const [asset, setAsset] = useState<string>("")
  const [slug, setSlug] = useState<string>("")

  // Parse URL params safely (only on client)
  useEffect(() => {
    if (typeof window !== "undefined") {
      const urlParams = new URLSearchParams(window.location.search)
      const assetParam = urlParams.get("asset") || ""
      const result = assetParam.split("?")[1]
      const slugValue = result ? new URLSearchParams(result).get("slug") || "" : ""
      const assetValue = assetParam.split("?")[0]

      setAsset(assetValue)
      setSlug(slugValue)
    }
  }, [])

  // Initialize TradingView widget when slug is available
  useEffect(() => {
    if (!slug || !containerRef.current) return

    const container = containerRef.current
    container.innerHTML = "" // Clear existing widget

    const script = document.createElement("script")
    script.src = "https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js"
    script.type = "text/javascript"
    script.async = true

    script.innerHTML = JSON.stringify({
      width: "100%",
      height: "100%",
      symbol: `${slug}USD`,
      interval: "D",
      timezone: "Etc/UTC",
      theme: "dark",
      style: "1",
      locale: "en",
      withdateranges: true,
      allow_symbol_change: true,
      calendar: false,
      support_host: "https://www.tradingview.com",
    })

    container.appendChild(script)
  }, [slug])

  return (
    <div className={styles["asset__details"]}>
      {/* TOP SECTION */}
      <div className={styles["asset__details__top"]}>
        {/* LEFT SIDE */}
        <div className={styles["asset__details__top--left"]}>
          <PageIntro
            title={`Meta Information - ${asset || "N/A"}`}
            description={`See some current trends and activities involving ${asset || "this asset"}.`}
          />

          <div className={styles["asset__details__top--left--intro"]}>
            <h6>
              Cryptocurrencies <span>{">"}</span>
            </h6>
            <span className={styles["asset__details__top--left--intro--header"]}>
              <img src={logo} alt="asset_logo" width={35} height={35} />
              <h2>{asset || "Unknown Asset"}</h2>
              <span>Price</span>
            </span>
            <h1>$81,756.03</h1>
          </div>

          <div className={styles["asset__details__top--left--border"]}></div>

          {/* DETAILS */}
          <div className={styles["asset__details__top--left--details"]}>
            {[
              { title: "Market Cap", value: "$1,621,819,223,563" },
              { title: "Fully Diluted Valuation", value: "$1,621,819,223" },
              { title: "24 Hour Trading Volume", value: "$1,621,819" },
              { title: "Circulating Supply", value: "$10,621" },
              { title: "Max Supply", value: "$10,621" },
            ].map((item, idx) => (
              <div
                key={idx}
                className={styles["asset__details__top--left--details--item"]}
              >
                <h2>{item.title}</h2>
                <h4>{item.value}</h4>
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT SIDE - TRADINGVIEW WIDGET */}
        <div className={styles["asset__details__top--right"]}>
          <div
            style={{
              width: "600px",
              height: "500px",
              borderRadius: "10px",
              overflow: "hidden",
              border: "1px solid #2B2B2B",
              boxShadow: "0 4px 20px rgba(0, 0, 0, 0.3)",
            }}
          >
            <div
              id="tradingview-widget-container"
              ref={containerRef}
              style={{ height: "100%" }}
            />
          </div>
        </div>
      </div>

      {/* CRYPTO NEWS SECTION */}
      <div className={styles["asset__details__news"]}>
        <CryptoNews />
      </div>
    </div>
  )
}

export default AssetDetails
