"use client";

import { useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import StartConsultationModal from "@/app/components/consultation/StartConsultationModal";

export default function AstrologerCard({ astrologer }: any) {
  const router = useRouter();
  const [showModal, setShowModal] = useState(false);
  // Live-confirmed via /precheck at click time — overrides the list's
  // own (sometimes stale) isOnline/isBusy fields once known, per the
  // "precheck is the authority" rule in CLAUDE.md.
  // Tagged with the list values it was observed against: when the
  // periodic list refresh reports a different isOnline/isBusy, the
  // list is newer than this precheck result and wins again (otherwise
  // an astrologer who comes back online would stay "Offline" here).
  const listState = `${!!astrologer.isOnline}|${!!astrologer.isBusy}`;
  const [liveStatusEntry, setLiveStatusEntry] = useState<{
    status: "BUSY" | "OFFLINE";
    listState: string;
  } | null>(null);
  const liveStatus = liveStatusEntry?.listState === listState ? liveStatusEntry.status : null;
  /*
   * ==========================================
   * CREATE ASTROLOGER SLUG
   * ==========================================
   */
  const createSlug = (name: string) => {
    return name
      ?.toLowerCase()
      ?.trim()
      ?.replace(/[^a-z0-9]+/g, "-")
      ?.replace(/^-+|-+$/g, "");
  };

  const slug = createSlug(astrologer.name);

  /*
   * ==========================================
   * PROFILE CLICK
   * ==========================================
   */
  const handleCardClick = () => {
    if (!slug) return;

    router.push(`/best-astrologer/${slug}`);
  };

  /*
   * ==========================================
   * CHAT CLICK
   * ==========================================
   *
   * Keep your existing consultation modal.
   */
  const handleChatClick = (
    e: React.MouseEvent<HTMLButtonElement>
  ) => {
    e.stopPropagation();

    if (isOffline) return;

    setShowModal(true);
  };

  /*
   * ==========================================
   * BUTTON STATE
   * ==========================================
   *
   * Confirmed real field on getAstrologers()'s response: isBusy is
   * distinct from isOnline (an astrologer can be online but already
   * in another consultation) — /precheck already treats
   * ASTROLOGER_BUSY as its own blocked_reason, so the card should
   * make that same distinction instead of only ever showing
   * "Online"/"Offline".
   */
  const isOffline = liveStatus === "OFFLINE" || (!liveStatus && !astrologer.isOnline);
  const isBusy = liveStatus === "BUSY" || (!liveStatus && astrologer.isOnline && astrologer.isBusy);
  const isAvailable = !isOffline && !isBusy;

  const chatButtonLabel = isAvailable ? "Chat" : isBusy ? "Join Queue" : "Offline";
  const chatButtonTitle = isAvailable
    ? ""
    : isBusy
      ? "Busy with another consultation — join the waiting queue"
      : "This astrologer is currently offline";
  const chatButtonStyle: React.CSSProperties = isAvailable
    ? { height: "35px" }
    : {
        height: "35px",
        background: "transparent",
        color: isBusy ? "#EF4444" : "#7E775F",
        borderColor: isBusy ? "#EF4444" : "#7E775F",
      };

  const image =
    astrologer.profileImage
      ? `${astrologer.profileImage}`
      : "../../public/images/astrologer-placeholder.png";

  return (
    <div
      className="card rounded-4 h-100 p-3"
      style={{
        background: "#2D2420",
        borderColor: "rgba(255, 255, 255, 0.1)",
        cursor: "pointer",
      }}
      onClick={handleCardClick}
    >
      <div className="card-body p-0">

        <div className="row">

          {/* Image */}

          <div className="col-4 text-center">

            <div className="position-relative d-inline-block">

              <Image
                src={image}
                alt={astrologer.name}
                width={80}
                height={80}
                className="rounded-circle"
                unoptimized
                priority
                style={{
                  objectFit: "cover",
                  boxSizing: "border-box",
                  border: `2px solid ${astrologer.isOnline ? "#22C55E" : "#7E775F"}`,
                  padding: "2px",
                }}
              />

              <span
                title={astrologer.isOnline ? "Online" : "Offline"}
                style={{
                  position: "absolute",
                  bottom: 4,
                  right: 4,
                  width: 14,
                  height: 14,
                  borderRadius: "50%",
                  background: astrologer.isOnline ? "#22C55E" : "#7E775F",
                  border: "2px solid #2D2420",
                }}
              />

            </div>

            <div
              className="mt-1"
              style={{
                fontSize: "11px",
                fontWeight: 600,
                color: astrologer.isOnline ? "#22C55E" : "#7E775F",
              }}
            >
              {astrologer.isOnline ? "Online" : "Offline"}
            </div>

            <div className="mt-2">

              {[1, 2, 3, 4, 5].map((i) => (
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" key={i}>
                  <path d="M7.23879 2.34166C7.47879 1.60486 8.52119 1.60486 8.76039 2.34166L9.61639 4.97526C9.72367 5.30427 10.0303 5.52701 10.3764 5.52726H13.146C13.9212 5.52726 14.2428 6.51926 13.6164 6.97526L11.3764 8.60246C11.0958 8.80602 10.9782 9.16713 11.0852 9.49686L11.9412 12.1305C12.1812 12.8673 11.3372 13.4809 10.7092 13.0249L8.46919 11.3977C8.1889 11.1942 7.80948 11.1942 7.52919 11.3977L5.28919 13.0249C4.66199 13.4809 3.81879 12.8673 4.05799 12.1305L4.91399 9.49686C5.02095 9.16713 4.90338 8.80602 4.62279 8.60246L2.38359 6.97606C1.75719 6.52006 2.07959 5.52806 2.85399 5.52806H5.62279C5.96914 5.52815 6.27622 5.30535 6.38359 4.97606L7.23959 2.34246L7.23879 2.34166Z" fill="#FFD700"/>
                </svg>
              ))}

            </div>

            <div
              className="mt-2"
              style={{
                color: "#7E775F",
                fontSize: "12px",
              }}
            >
              {astrologer.totalOrder || 0}+ orders
            </div>

          </div>

          {/* Details */}

          <div className="col-8">

            <div className="d-flex justify-content-between">

              <h3 className="astrologer-name">
                {astrologer.name}
              </h3>

              {astrologer.isVerified && (
                
                <svg width="20" height="20" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path fill-rule="evenodd" clip-rule="evenodd" d="M8 16C12.4153 16 16 12.4153 16 8C16 3.58468 12.4153 0 8 0C3.58468 0 0 3.58468 0 8C0 12.4153 3.58468 16 8 16V16M11.707 6.707C12.086 6.31462 12.0806 5.69092 11.6948 5.30518C11.3091 4.91945 10.6854 4.91403 10.293 5.293L7 8.586L5.707 7.293C5.31462 6.91403 4.69092 6.91945 4.30518 7.30518C3.91945 7.69092 3.91403 8.31462 4.293 8.707L6.293 10.707C6.6835 11.0974 7.3165 11.0974 7.707 10.707L11.707 6.707V6.707" fill="#00FF5E"/>
                </svg>

              )}

            </div>

            <div
              className="mb-1"
              style={{
                color: "#7E775F",
                fontSize: "14px",
                lineHeight: "20px",
              }}
            >
              {astrologer.allSkill || "Vedic"}
            </div>

            <div
              className="mb-2"
              style={{
                color: "#7E775F",
                fontSize: "14px",
                lineHeight: "20px",
              }}
            >
              {astrologer.languageKnown || "Hindi"}
            </div>

            <div
              className="mb-3"
              style={{
                color: "#7E775F",
                fontSize: "14px",
                lineHeight: "20px",
              }}
            >
              Exp: {astrologer.experience} Years
            </div>
            <div className="d-flex align-items-center justify-content-between">
              <div className="d-flex align-items-center gap-2">

                <span
                  style={{
                    color: "#7E775F",
                    textDecoration: "line-through",
                    fontSize: "14px",
                  }}
                >
                  ₹{Number(astrologer.charge) + 6}
                </span>

                <span
                  className="fw-bold"
                  style={{
                    color: "#01BF47",
                    fontSize: "18px",
                    fontWeight: "bold",
                    lineHeight: 1,
                  }}
                >
                  {astrologer.charge}
                </span>

                <span
                  className=""
                  style={{
                    color: "#7E775F",
                    fontSize: "12px",
                  }}
                >
                  /min
                </span>

              </div>

              <button
                className={`btn py-1 px-4 ${isAvailable ? "btn-primary rounded-3" : "rounded-pill border"}`}
                style={chatButtonStyle}
                onClick={handleChatClick}
                disabled={isOffline}
                title={chatButtonTitle}
              >
                {chatButtonLabel}
              </button>
            </div>

          </div>

        </div>

      </div>

      <StartConsultationModal
        show={showModal}
        onClose={() => setShowModal(false)}
        astrologer={{ id: astrologer.id, name: astrologer.name, charge: astrologer.charge, callRate: astrologer.callRate }}
        medium="CHAT"
        onUnavailable={(reason) =>
          setLiveStatusEntry({
            status: reason === "ASTROLOGER_BUSY" ? "BUSY" : "OFFLINE",
            listState,
          })
        }
      />
    </div>
  );
}