"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter, useSearchParams } from "next/navigation";

import Header from "@/app/components/layout/Header";
import Footer from "@/app/components/layout/Footer";
import Link from "@/app/components/LocaleLink";

import {
  getWalletTransactionDetails,
  WalletTransactionDetails,
} from "@/app/lib/wallet";
import {
  getConsultationHistory,
  getConsultationMessages,
  ConsultationChatMessage,
  ConsultationHistoryItem,
} from "@/app/lib/consultation";

function formatDate(iso?: string) {
  if (!iso) return "--";
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return iso;

  return date.toLocaleString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function formatDuration(seconds?: number) {
  if (!seconds || seconds <= 0) return "0:00";
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${String(secs).padStart(2, "0")}`;
}

export default function WalletTransactionDetailPage() {
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const search = useSearchParams();

  const id = Number(params?.id);
  const transactionType = search.get("type") || "";

  const [data, setData] = useState<WalletTransactionDetails | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [messages, setMessages] = useState<ConsultationChatMessage[]>([]);

  const isChat = transactionType.toUpperCase() === "CHAT";

  useEffect(() => {
    const token = localStorage.getItem("token");

    if (!token) {
      router.replace(`/signin?redirect=/wallet/transaction/${id}?type=${transactionType}`);
      return;
    }

    if (!id || !transactionType) {
      setError("This transaction link is missing required details.");
      setLoading(false);
      return;
    }

    let cancelled = false;

    (async () => {
      const response = await getWalletTransactionDetails(id, transactionType);

      if (cancelled) return;

      if (!response.authenticated) {
        router.replace(`/signin?redirect=/wallet/transaction/${id}?type=${transactionType}`);
        return;
      }

      if (!response.success) {
        setError(response.message || "Unable to load transaction details.");
      } else {
        setData(response.data);

        // Chat history only, per explicit request. The wallet
        // drill-down's own `id` is the WALLET transaction id, NOT the
        // numeric consultation_id the messages endpoint needs — that
        // assumption was tried and confirmed wrong live (the
        // transcript never loaded for a real ONGOING chat transaction).
        // The drill-down response only ever exposes the consultation's
        // string consultation_no (as `transactionNumber`), so the real
        // numeric id has to be resolved first via the history list,
        // matching by consultation_no — same "no per-id endpoint,
        // re-fetch the list and match client-side" pattern already
        // used elsewhere in this app.
        if (transactionType.toUpperCase() === "CHAT") {
          try {
            const historyResponse = await getConsultationHistory({
              medium: "CHAT",
              page: 1,
              limit: 100,
            });

            if (cancelled) return;

            const historyItems: ConsultationHistoryItem[] =
              historyResponse?.data?.items ?? historyResponse?.data ?? [];

            const match = (Array.isArray(historyItems) ? historyItems : []).find(
              (item) => item.consultation_no === response.data.transactionNumber,
            );

            if (match?.consultation_id) {
              const messagesResponse = await getConsultationMessages(
                match.consultation_id,
                1,
                200,
              );

              if (!cancelled && messagesResponse.success) {
                setMessages(messagesResponse.data?.items ?? []);
              }
            }
          } catch (messagesError) {
            console.error("Chat transcript error:", messagesError);
          }
        }
      }

      setLoading(false);
    })();

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

  if (loading) {
    return (
      <>
        <Header />
        <main className="horoscope-loading">Loading transaction...</main>
        <Footer />
      </>
    );
  }

  return (
    <>
      <Header />
      <section className="wallet-page">
        <div className="container">
          <div className="wallet-wrapper card-bg-primary">
            <div className="d-flex justify-content-between align-items-center mb-3">
              <h4 className="text-white mb-0">Transaction Details</h4>
              <Link href="/wallet" className="btn btn-outline-light btn-sm rounded-pill px-3">
                ← Back to Wallet
              </Link>
            </div>

            {error || !data ? (
              <div className="transaction-card text-center text-muted">
                <p className="mb-0">{error || "Transaction not found."}</p>
              </div>
            ) : (
              <>
                <div className="transaction-card">
                  <div className="d-flex justify-content-between align-items-start">
                    <div>
                      <h5 className="mb-1 text-dark">{data.title}</h5>
                      <small className="text-muted">{formatDate(data.createdAt)}</small>
                    </div>

                    <div className="text-end">
                      <div className={`amount ${data.isCredit ? "text-success" : "text-danger"}`}>
                        {data.isCredit ? "+" : "-"}₹
                        {Math.abs(data.amount).toLocaleString("en-IN")}
                      </div>
                      {data.status && (
                        <small className="text-muted">{data.status}</small>
                      )}
                    </div>
                  </div>

                  <hr />

                  <div className="d-flex justify-content-between small text-muted">
                    <span>Transaction No.</span>
                    <span>{data.transactionNumber}</span>
                  </div>

                  <div className="d-flex justify-content-between small text-muted mt-1">
                    <span>Type</span>
                    <span>{data.transactionType}</span>
                  </div>
                </div>

                {/* CHAT / CALL — astrologer + session */}
                {data.astrologer && (
                  <div className="transaction-card d-flex align-items-center gap-3">
                    {data.astrologer.profileImage && (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={data.astrologer.profileImage}
                        alt={data.astrologer.name}
                        style={{
                          width: 56,
                          height: 56,
                          borderRadius: "50%",
                          objectFit: "cover",
                        }}
                      />
                    )}
                    <div>
                      <div className="fw-bold text-dark">{data.astrologer.name}</div>
                      <small className="text-muted">Astrologer</small>
                    </div>
                  </div>
                )}

                {data.session && (
                  <div className="transaction-card">
                    <h5 className="mb-3 text-dark">Session</h5>
                    <div className="d-flex justify-content-between small text-muted">
                      <span>Medium</span>
                      <span>{data.session.sessionType}</span>
                    </div>
                    <div className="d-flex justify-content-between small text-muted mt-1">
                      <span>Status</span>
                      <span>{data.session.status}</span>
                    </div>
                    <div className="d-flex justify-content-between small text-muted mt-1">
                      <span>Duration</span>
                      <span>{formatDuration(data.session.durationSeconds)}</span>
                    </div>
                  </div>
                )}

                {/* Chat transcript — CHAT transactions only, per explicit
                    request. Read-only history of an already-ended
                    session, so it reuses the same read-only bubble
                    styling as the astrologer's consultation review page. */}
                {isChat && messages.length > 0 && (
                  <div className="astrologer-panel card-bg-primary consult-messages-panel">
                    <h5 className="mb-3">Chat Transcript</h5>

                    {messages.map((m) => {
                      const mine = m.sender_type === "USER";
                      return (
                        <div
                          key={m.client_message_id || m.id}
                          className={`consult-msg-row ${mine ? "mine" : ""}`}
                        >
                          {!mine && (
                            <div className="consult-msg-avatar">
                              {(data.astrologer?.name || "A").charAt(0).toUpperCase()}
                            </div>
                          )}
                          <div className="consult-msg-bubble">
                            {m.body}
                            <div className="consult-msg-time">
                              {(m.sent_at || "").slice(11, 16)}
                            </div>
                          </div>
                          {mine && (
                            <div className="consult-msg-avatar self">
                              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M12 12a5 5 0 1 0-5-5 5 5 0 0 0 5 5Zm0 2c-4.42 0-8 2.24-8 5v1h16v-1c0-2.76-3.58-5-8-5Z" />
                              </svg>
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}

                {/* RECHARGE / others — payment */}
                {data.payment && (
                  <div className="transaction-card">
                    <h5 className="mb-3 text-dark">Payment</h5>
                    {data.payment.paymentMode && (
                      <div className="d-flex justify-content-between small text-muted">
                        <span>Mode</span>
                        <span>{data.payment.paymentMode}</span>
                      </div>
                    )}
                    {data.payment.paymentReference && (
                      <div className="d-flex justify-content-between small text-muted mt-1">
                        <span>Reference</span>
                        <span>{data.payment.paymentReference}</span>
                      </div>
                    )}
                    {data.payment.orderId && (
                      <div className="d-flex justify-content-between small text-muted mt-1">
                        <span>Order ID</span>
                        <span>{data.payment.orderId}</span>
                      </div>
                    )}
                    {data.payment.paymentStatus && (
                      <div className="d-flex justify-content-between small text-muted mt-1">
                        <span>Status</span>
                        <span>{data.payment.paymentStatus}</span>
                      </div>
                    )}
                    {!!data.payment.cashbackAmount && (
                      <div className="d-flex justify-content-between small text-muted mt-1">
                        <span>Cashback</span>
                        <span>₹{data.payment.cashbackAmount}</span>
                      </div>
                    )}
                  </div>
                )}

                {/* ORDER — product + address */}
                {data.product && (
                  <div className="transaction-card d-flex align-items-center gap-3">
                    {data.product.productImage && (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={data.product.productImage}
                        alt={data.product.name}
                        style={{
                          width: 64,
                          height: 64,
                          borderRadius: 12,
                          objectFit: "cover",
                        }}
                      />
                    )}
                    <div>
                      <div className="fw-bold text-dark">{data.product.name}</div>
                      {typeof data.product.sellingPrice === "number" && (
                        <small className="text-muted">
                          ₹{data.product.sellingPrice.toLocaleString("en-IN")}
                        </small>
                      )}
                    </div>
                  </div>
                )}

                {data.address && (
                  <div className="transaction-card">
                    <h5 className="mb-3 text-dark">Delivery Address</h5>
                    <p className="mb-1 fw-bold text-dark">{data.address.name}</p>
                    {data.address.phoneNumber && (
                      <p className="mb-1 small text-muted">{data.address.phoneNumber}</p>
                    )}
                    <p className="mb-0 small text-muted">
                      {[
                        data.address.flatNo,
                        data.address.locality,
                        data.address.landmark,
                        data.address.city,
                        data.address.state,
                        data.address.country,
                        data.address.pincode,
                      ]
                        .filter(Boolean)
                        .join(", ")}
                    </p>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </section>
      <Footer />
    </>
  );
}
