"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import Link from "@/app/components/LocaleLink";

import { useLanguage } from "@/app/context/LanguageContext";
import { getAstrologers } from "@/app/lib/auth";
import StartConsultationModal from "@/app/components/consultation/StartConsultationModal";

interface HomeAstrologer {
  id: number;
  name: string;
  profileImage?: string;
  charge: number;
  callRate?: number;
  rating: number;
  isOnline?: boolean;
  allSkill?: string;
  experience?: number;
  totalOrder?: number;
}

const FALLBACK_IMAGE = "/images/astrologer.png";

export default function Astrologers() {
  const { t } = useLanguage();
  const router = useRouter();

  const [astrologers, setAstrologers] = useState<HomeAstrologer[]>([]);
  const [loggedIn, setLoggedIn] = useState(false);
  const [loading, setLoading] = useState(true);
  const [modal, setModal] = useState<{
    astrologer: { id: number; name: string; charge: number; callRate?: number };
    medium: "CHAT" | "AUDIO";
  } | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function load() {
      const token = localStorage.getItem("token");

      if (!token) {
        // Logged out — real top astrologers from the public
        // /user/astrologers/top endpoint (no auth needed). Every click
        // on these cards (card or button) goes straight to sign in,
        // never a real consultation attempt, per explicit request.
        setLoggedIn(false);

        try {
          const response = await fetch("/api/astrologers/top?limit=3");
          const data = await response.json();

          if (!cancelled && Array.isArray(data?.recordList)) {
            setAstrologers(
              data.recordList.slice(0, 3).map((a: any) => ({
                id: a.id,
                name: a.name,
                profileImage: a.profileImage,
                charge: a.chatRate,
                callRate: a.callRate,
                rating: typeof a.rating === "number" ? a.rating : 0,
                isOnline: !!a.isOnline,
                allSkill: a.allSkill || a.primarySkill,
                experience: a.experience,
                totalOrder: a.totalOrders,
              })),
            );
          }
        } catch (error) {
          console.error("Homepage top astrologers load error:", error);
        } finally {
          if (!cancelled) setLoading(false);
        }

        return;
      }

      try {
        // GET /user/astrologers/list (via getAstrologers) is the only
        // source with real isOnline/chatRate/callRate, so "online
        // first, then rating" can genuinely be honored here.
        const response = await getAstrologers(token);

        if (!cancelled && response?.status === 200 && Array.isArray(response.recordList)) {
          const list: HomeAstrologer[] = response.recordList.map((a: any) => ({
            id: a.id,
            name: a.name,
            profileImage: a.profileImage,
            charge: a.charge,
            callRate: a.callRate,
            rating: typeof a.rating === "number" ? a.rating : 0,
            isOnline: !!a.isOnline,
            allSkill: a.allSkill,
            experience: a.experience,
            totalOrder: a.totalOrder,
          }));

          list.sort((a, b) => {
            if (a.isOnline !== b.isOnline) return a.isOnline ? -1 : 1;
            return b.rating - a.rating;
          });

          setAstrologers(list.slice(0, 3));
        }
      } catch (error) {
        console.error("Homepage astrologers load error:", error);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    load();

    return () => {
      cancelled = true;
    };
  }, []);

  // Honest: no fabricated placeholder cards if the real fetch comes
  // back empty — the section simply doesn't render.
  if (!loading && astrologers.length === 0) {
    return null;
  }

  const goToSignin = () => router.push("/signin");

  return (
    <section className="astrologer-section py-5">
      <div className="container">
        <span className="live-badge">
          <span className="dot"></span>
          {t("home.astrologers.liveNow", "LIVE NOW")}
        </span>

        <div className="d-flex justify-content-between align-items-center mb-5">
          <div>
            <h2 className="section-title mt-3">
              {t("home.astrologers.heading", "13,000+ expert astrologers, ready now.")}
            </h2>
          </div>

          <Link
            href="/chat-with-astrologer"
            className="more-link d-none d-lg-flex align-items-center gap-2"
          >
            {t("home.astrologers.moreAstrologers", "More Astrologers")}
            <svg width="7" height="12" viewBox="0 0 7 12" fill="none">
              <path
                d="M4.6 5.65382L0 1.05382L1.05382 0L6.70764 5.65382L1.05382 11.3076L0 10.2538L4.6 5.65382Z"
                fill="#FCD400"
              />
            </svg>
          </Link>
        </div>

        <div className="row g-3">

          {loading ? (
            <div className="col-12 text-center py-4" style={{ color: "#fff" }}>
              {t("home.astrologers.loading", "Loading astrologers...")}
            </div>
          ) : (
            astrologers.map((item) => (
              <div className="col-lg-3 col-md-6" key={item.id}>
                <div
                  className="astrologer-card"
                  role={loggedIn ? undefined : "link"}
                  tabIndex={loggedIn ? undefined : 0}
                  style={loggedIn ? undefined : { cursor: "pointer" }}
                  onClick={loggedIn ? undefined : goToSignin}
                  onKeyDown={
                    loggedIn
                      ? undefined
                      : (event) => {
                          if (event.key === "Enter" || event.key === " ") {
                            event.preventDefault();
                            goToSignin();
                          }
                        }
                  }
                >

                  <div className="d-flex justify-content-between">
                    <Image
                      src={item.profileImage || FALLBACK_IMAGE}
                      alt={item.name}
                      width={90}
                      height={90}
                      className="avatar"
                      unoptimized
                    />

                    <div className="text-end">
                      <div className="price-astrologer">
                        ₹{item.charge}/min
                      </div>

                      {!!item.totalOrder && (
                        <small>{item.totalOrder}+ Orders</small>
                      )}
                    </div>
                  </div>

                  {item.isOnline && (
                    <span className="status online">
                      {t("home.astrologers.online", "ONLINE")}
                    </span>
                  )}

                  <h4>{item.name}</h4>

                  <p className="skills">
                    {item.allSkill || "Vedic Astrology"}
                  </p>

                  <div className="info">
                    <span>
                      ⭐ {item.rating.toFixed(2)}
                    </span>

                    {!!item.experience && (
                      <span>
                        {item.experience} Years Exp.
                      </span>
                    )}
                  </div>

                  <div className="d-flex gap-2 mt-4">
                    <button
                      type="button"
                      className="btn chat-btn flex-fill"
                      onClick={(event) => {
                        event.stopPropagation();

                        if (!loggedIn) {
                          goToSignin();
                          return;
                        }

                        setModal({
                          astrologer: {
                            id: item.id,
                            name: item.name,
                            charge: item.charge,
                            callRate: item.callRate,
                          },
                          medium: "CHAT",
                        });
                      }}
                    >
                      💬 {t("home.astrologers.chat", "Chat")}
                    </button>

                    <button
                      type="button"
                      className="btn call-btn flex-fill"
                      onClick={(event) => {
                        event.stopPropagation();

                        if (!loggedIn) {
                          goToSignin();
                          return;
                        }

                        setModal({
                          astrologer: {
                            id: item.id,
                            name: item.name,
                            charge: item.charge,
                            callRate: item.callRate,
                          },
                          medium: "AUDIO",
                        });
                      }}
                    >
                      📞 {t("home.astrologers.call", "Call")}
                    </button>
                  </div>

                </div>
              </div>
            ))
          )}

          {!loading && (
            <div className="col-lg-3 col-md-6">
              <div className="match-card h-100 d-flex flex-column justify-content-center">
                <h3>{t("home.astrologers.matchTitle", "Not sure who to pick?")}</h3>

                <p>
                  {t(
                    "home.astrologers.matchDescription",
                    "Filter by skill, language, or reading style. Our algorithm matches you with the best guide for your energy."
                  )}
                </p>

                <Link
                  href="/chat-with-astrologer"
                  className="btn find-btn mt-3"
                >
                  {t("home.astrologers.findMyMatch", "Find My Match")}
                </Link>
              </div>
            </div>
          )}

        </div>
      </div>

      {loggedIn && modal && (
        <StartConsultationModal
          key={`${modal.astrologer.id}-${modal.medium}`}
          show={!!modal}
          onClose={() => setModal(null)}
          astrologer={modal.astrologer}
          medium={modal.medium}
        />
      )}
    </section>
  );
}
