"use client";

import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "@/app/components/LocaleLink";
import toast from "react-hot-toast";

import DashboardSidebar from "@/app/components/astrologer/DashboardSidebar";
import NotificationBell from "@/app/components/notifications/NotificationBell";
import {
  getAstrologerDashboard,
  getAstrologerProfile,
  getConsultationRequests,
  acceptConsultation,
  rejectConsultation,
  setOnlineStatus,
  setChatStatus,
  setCallStatus,
  setBusyStatus,
  setQuickDnd,
  updateOffer,
  isRequiredToggleOffError,
  friendlyErrorMessage,
  AstrologerOfferInput,
  ConsultationRequest,
} from "@/app/lib/astrologer";
interface DashboardData {
  name: string;
  profile_image?: string;
  current_status: string;
  is_online: boolean;
  is_chat_online: boolean;
  is_call_online: boolean;
  quick_dnd: boolean;
  wallet_balance: number;
  today_earning: number;
  today_calls: number;
  today_chats: number;
  today_call_minutes: number;
  today_chat_minutes: number;
}

type ToggleField = "online" | "chat" | "call" | "busy" | "dnd";

function formatMinutes(totalMinutes: number): string {
  const hours = Math.floor(totalMinutes / 60);
  const minutes = totalMinutes % 60;
  return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
}

function greeting(): string {
  const hour = new Date().getHours();
  if (hour < 12) return "Good morning";
  if (hour < 17) return "Good afternoon";
  return "Good evening";
}

function Toggle({
  checked,
  disabled,
  onChange,
}: {
  checked: boolean;
  disabled?: boolean;
  onChange: () => void;
}) {
  return (
    <label className="astrologer-switch">
      <input
        type="checkbox"
        checked={checked}
        disabled={disabled}
        onChange={onChange}
      />
      <span className="astrologer-switch-track" />
    </label>
  );
}

export default function AstrologerDashboardPage() {
  const router = useRouter();

  const [dashboard, setDashboard] = useState<DashboardData | null>(null);
  const [astrologerToken, setAstrologerToken] = useState<string | null>(null);
  const [chatRate, setChatRate] = useState<string | number>("--");
  const [callRate, setCallRate] = useState<string | number>("--");
  const [loading, setLoading] = useState(true);
  const [savingField, setSavingField] = useState<ToggleField | null>(null);

  const [offer, setOffer] = useState({ po5_enabled: false, free_chat_enabled: false });
  const [savingOffer, setSavingOffer] = useState<string | null>(null);
  const [waitingRequests, setWaitingRequests] = useState<
    ConsultationRequest[]
  >([]);

  const [requestLoading, setRequestLoading] =
    useState(false);

  const [requestSeconds, setRequestSeconds] =
    useState<Record<number, number>>({});

  const [actingRequestId, setActingRequestId] = useState<number | null>(null);

  const refreshWaitingRequests = useCallback(
    async (token: string) => {
      try {
        setRequestLoading(true);

        const response =
          await getConsultationRequests(token);

        if (!response?.success) {
          return;
        }

        const data =
          response?.data ?? response;

        const items = Array.isArray(data?.items)
          ? data.items
          : [];

        setWaitingRequests(items);

        /*
        |--------------------------------------------------------------------------
        | Initialize countdown values
        |--------------------------------------------------------------------------
        */

        setRequestSeconds((previous) => {
          const next = {
            ...previous,
          };

          items.forEach(
            (item: ConsultationRequest) => {
              if (
                item.consultation_id != null &&
                item.seconds_to_expiry != null
              ) {
                next[item.consultation_id] =
                  Number(item.seconds_to_expiry);
              }
            },
          );

          return next;
        });
      } catch (error) {
        console.error(
          "Waiting consultation request error:",
          error,
        );
      } finally {
        setRequestLoading(false);
      }
    },
    [],
  );

  // Same accept/reject flow as app/astrologer/requests/page.tsx — this
  // panel is a live preview of the same ringing queue, not a separate
  // feature, so accepting here must land on the same real session page.
  const handleAcceptWaiting = async (request: ConsultationRequest) => {
    if (!astrologerToken) return;

    const consultationId = request.consultation_id;

    try {
      setActingRequestId(consultationId);
      const response = await acceptConsultation(consultationId, astrologerToken, request);

      if (!response.success) {
        const silent = [
          "this consultation is no longer available",
          "you are already in a consultation",
          "the customer no longer has sufficient balance",
        ];

        if (!silent.some((m) => (response.message || "").toLowerCase().includes(m))) {
          toast.error(response.message || "Unable to accept this request.");
        }

        setWaitingRequests((prev) =>
          prev.filter((r) => r.consultation_id !== consultationId),
        );
        return;
      }

      router.push(`/astrologer/consultation/${consultationId}`);
    } finally {
      setActingRequestId(null);
    }
  };

  const handleDeclineWaiting = async (consultationId: number) => {
    if (!astrologerToken) return;

    try {
      setActingRequestId(consultationId);
      await rejectConsultation(consultationId, "Not available right now", astrologerToken);
      setWaitingRequests((prev) =>
        prev.filter((r) => r.consultation_id !== consultationId),
      );
    } finally {
      setActingRequestId(null);
    }
  };

  const refreshDashboard = useCallback(async (token: string) => {
    const response = await getAstrologerDashboard(token);
    if (response.success) {
      setDashboard(response.data ?? response);
    }
    return response;
  }, []);

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

    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    setAstrologerToken(token);

    Promise.all([refreshDashboard(token), getAstrologerProfile(token)])
      .then(([, profileResponse]) => {
        const p = profileResponse?.data ?? profileResponse;
        setChatRate(p?.ChatRate ?? p?.chat_rate ?? "--");
        setCallRate(p?.AudioCallRate ?? p?.call_rate ?? "--");
      })
      .catch(() => toast.error("Unable to load your dashboard."))
      .finally(() => setLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

    if (!token) {
      return;
    }

    let cancelled = false;
    let timer: ReturnType<typeof setTimeout>;

    const poll = async () => {
      if (cancelled) {
        return;
      }

      await refreshWaitingRequests(token);

      if (!cancelled) {
        timer = setTimeout(
          poll,
          3000,
        );
      }
    };

    poll();

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

  useEffect(() => {
    if (!waitingRequests.length) {
      return;
    }

    const timer =
      setInterval(() => {
        setRequestSeconds((previous) => {
          const next = {
            ...previous,
          };

          waitingRequests.forEach(
            (request) => {
              const id =
                request.consultation_id;

              const current =
                Number(
                  next[id] ??
                  request.seconds_to_expiry ??
                  0,
                );

              next[id] =
                Math.max(current - 1, 0);
            },
          );

          return next;
        });
      }, 1000);

    return () => clearInterval(timer);
  }, [waitingRequests]);

  useEffect(() => {
    setWaitingRequests((previous) =>
      previous.filter((request) => {
        const seconds =
          requestSeconds[
            request.consultation_id
          ];

        return seconds === undefined ||
          seconds > 0;
      }),
    );
  }, [requestSeconds]);

  const handleToggle = async (field: ToggleField) => {
    if (!dashboard || savingField) return;

    const token = localStorage.getItem("astrologerToken");
    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    const isBusyNow = (dashboard.current_status || "").toLowerCase() === "busy";

    const nextValue = {
      online: !dashboard.is_online,
      chat: !dashboard.is_chat_online,
      call: !dashboard.is_call_online,
      busy: !isBusyNow,
      dnd: !dashboard.quick_dnd,
    }[field];

    setSavingField(field);

    try {
      const response = await {
        online: () => setOnlineStatus(nextValue, token),
        chat: () => setChatStatus(nextValue, token),
        call: () => setCallStatus(nextValue, token),
        busy: () => setBusyStatus(nextValue, token),
        dnd: () => setQuickDnd(nextValue, token),
      }[field]();

      if (!response.success) {
        toast.error(
          isRequiredToggleOffError(response.message)
            ? "Turning this off isn't supported by the server right now. Please try again later."
            : friendlyErrorMessage(response.message, "Unable to update.")
        );
      }
    } catch (error: any) {
      toast.error(
        friendlyErrorMessage(error.response?.data?.message, "Unable to update.")
      );
    } finally {
      await refreshDashboard(token);
      setSavingField(null);
    }
  };

  const handleOfferToggle = async (key: "po5_enabled" | "free_chat_enabled") => {
    const token = localStorage.getItem("astrologerToken");
    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    const nextValue = !offer[key];
    setSavingOffer(key);

    const payload: AstrologerOfferInput = {
      po5_enabled: key === "po5_enabled" ? nextValue : offer.po5_enabled,
      po5_amount: 5,
      free_chat_enabled: key === "free_chat_enabled" ? nextValue : offer.free_chat_enabled,
      free_chat_minutes: 5,
      free_call_enabled: false,
      free_call_minutes: 0,
      campaign_enabled: false,
      campaign_title: "",
      campaign_description: "",
      start_date: new Date().toISOString().slice(0, 10),
      end_date: new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 10),
    };

    try {
      const response = await updateOffer(payload, token);

      if (!response.success) {
        toast.error(
          isRequiredToggleOffError(response.message)
            ? "Turning this off isn't supported by the server right now. Please try again later."
            : friendlyErrorMessage(response.message, "Unable to update offer.")
        );
        return;
      }

      setOffer((prev) => ({ ...prev, [key]: nextValue }));
      toast.success("Offer updated");
    } catch (error: any) {
      toast.error(
        friendlyErrorMessage(error.response?.data?.message, "Unable to update offer.")
      );
    } finally {
      setSavingOffer(null);
    }
  };

  if (loading || !dashboard) {
    return (
      <section className="py-5 d-flex align-items-center justify-content-center min-vh-100">
        <p className="text-white">Loading your dashboard...</p>
      </section>
    );
  }

  const isBusy = (dashboard.current_status || "").toLowerCase() === "busy";
  const avatarUrl = dashboard.profile_image;
  const initial = (dashboard.name || "A").trim().charAt(0).toUpperCase();
  const talkTime = formatMinutes(
    (dashboard.today_call_minutes || 0) + (dashboard.today_chat_minutes || 0)
  );
  const sessions = (dashboard.today_calls || 0) + (dashboard.today_chats || 0);

  return (
    <div className="astrologer-dashboard-shell">
      <DashboardSidebar active="Home" />

      <main className="astrologer-dashboard-main">
        <div className="astrologer-dashboard-topbar">
          <div>
            <div className="astrologer-dashboard-greeting">{greeting()},</div>
            <div className="astrologer-dashboard-name">{dashboard.name}</div>
          </div>

          <div className="astrologer-dashboard-actions">
            <NotificationBell
              audience="astrologer"
              token={astrologerToken}
              notificationsHref="/astrologer/notifications"
              dark
            />
            {avatarUrl ? (
              <img src={avatarUrl} alt="" className="astrologer-dashboard-avatar" />
            ) : (
              <div
                className="astrologer-dashboard-avatar d-flex align-items-center justify-content-center bg-warning text-dark fw-bold"
              >
                {initial}
              </div>
            )}
          </div>
        </div>

        <div className="row g-4">
          <div className="col-lg-8">
            <div className="astrologer-online-card card-bg-primary">
              <div className="d-flex align-items-center gap-3">
                <span className="astrologer-online-icon">⏻</span>
                <div>
                  <div className="text-white fw-semibold">
                    You're {dashboard.is_online ? "online" : "offline"}
                  </div>
                  <div className="terms-text-color small">
                    Visible in the astrologer list
                  </div>
                </div>
              </div>
              <Toggle
                checked={dashboard.is_online}
                disabled={savingField === "online"}
                onChange={() => handleToggle("online")}
              />
            </div>

            <div className="astrologer-stat-row">
              <div className="astrologer-stat-card card-bg-primary">
                <div className="astrologer-stat-label">📅 Today</div>
                <div className="astrologer-stat-value">
                  ₹{Math.round(dashboard.today_earning || 0).toLocaleString("en-IN")}
                </div>
              </div>

              <div className="astrologer-stat-card card-bg-primary">
                <div className="astrologer-stat-label">🕐 Talk time</div>
                <div className="astrologer-stat-value">{talkTime}</div>
              </div>

              <div className="astrologer-stat-card card-bg-primary">
                <div className="astrologer-stat-label">👥 Sessions</div>
                <div className="astrologer-stat-value">{sessions}</div>
              </div>
            </div>

            <div className="astrologer-panel card-bg-primary">
              <div className="astrologer-panel-head">
                <div className="d-flex align-items-center gap-2">
                  <span className="astrologer-panel-title">
                    Waiting now
                  </span>

                  {waitingRequests.length > 0 && (
                    <span className="waiting-request-count">
                      {waitingRequests.length}
                    </span>
                  )}
                </div>

                <Link
                  href="/astrologer/requests"
                  className="astrologer-panel-link"
                >
                  View all
                </Link>
              </div>

              {requestLoading &&
              waitingRequests.length === 0 ? (
                <div className="waiting-loading">
                  <span className="waiting-spinner" />
                  Checking requests...
                </div>
              ) : waitingRequests.length === 0 ? (
                <p className="astrologer-empty-hint mb-0">
                  No one is waiting right now.
                </p>
              ) : (
                <div className="waiting-request-list">
                  {waitingRequests.map((request) => {
                    const seconds =
                      requestSeconds[
                        request.consultation_id
                      ] ??
                      request.seconds_to_expiry ??
                      0;

                    const displayName =
                      request.consultee_name ||
                      request.user_name ||
                      "User";

                    const topic =
                      request.medium === "CHAT"
                        ? "Chat consultation"
                        : "Call consultation";

                    return (
                      <div
                        key={request.consultation_id}
                        className="waiting-request-card"
                      >
                        <div className="waiting-request-top">
                          <div className="waiting-user-avatar">
                            {displayName
                              .charAt(0)
                              .toUpperCase()}
                          </div>

                          <div className="waiting-request-info">
                            <div className="waiting-user-name">
                              {displayName}
                            </div>

                            <div className="waiting-request-topic">
                              <span>
                                {request.medium ===
                                "CHAT"
                                  ? "★"
                                  : "📞"}
                              </span>

                              {topic}
                            </div>

                            <div className="waiting-request-time">
                              <span>◷</span>

                              Requested now
                            </div>
                          </div>

                          <div
                            className={`waiting-expiry ${
                              seconds <= 10
                                ? "danger"
                                : ""
                            }`}
                          >
                            {seconds}s
                          </div>
                        </div>

                        <div className="waiting-request-meta">
                          {request.is_free_chat ? (
                            <span className="waiting-free-badge">
                              FREE {request.free_minutes ?? 0} min
                            </span>
                          ) : (
                            <span>
                              ₹
                              {Number(
                                request.rate_per_minute ??
                                  0,
                              )}
                              /min
                            </span>
                          )}

                          {request.consultee_birth_place && (
                            <span>
                              📍{" "}
                              {request.consultee_birth_place}
                            </span>
                          )}
                        </div>

                        <div className="waiting-request-actions">
                          <button
                            type="button"
                            className="waiting-decline-btn"
                            disabled={actingRequestId === request.consultation_id}
                            onClick={() =>
                              handleDeclineWaiting(request.consultation_id)
                            }
                          >
                            {actingRequestId === request.consultation_id
                              ? "..."
                              : "Decline"}
                          </button>

                          <button
                            type="button"
                            className="waiting-accept-btn"
                            disabled={actingRequestId === request.consultation_id}
                            onClick={() =>
                              handleAcceptWaiting(request)
                            }
                          >
                            <span>{request.medium === "AUDIO" ? "📞" : "💬"}</span>
                            {actingRequestId === request.consultation_id
                              ? "Accepting..."
                              : "Accept"}
                          </button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>

            <div className="astrologer-panel card-bg-primary">
              <div className="astrologer-panel-head">
                <span className="astrologer-panel-title">Offers</span>
              </div>

              <div className="astrologer-offer-row">
                <div>
                  <div className="astrologer-avail-title">Free 5 min chat</div>
                  <div className="astrologer-avail-sub">Run for new users only</div>
                </div>
                <Toggle
                  checked={offer.free_chat_enabled}
                  disabled={savingOffer === "free_chat_enabled"}
                  onChange={() => handleOfferToggle("free_chat_enabled")}
                />
              </div>

              <div className="astrologer-offer-row">
                <div>
                  <div className="astrologer-avail-title">PO5 boost</div>
                  <div className="astrologer-avail-sub">5% per qualifying order</div>
                </div>
                <Toggle
                  checked={offer.po5_enabled}
                  disabled={savingOffer === "po5_enabled"}
                  onChange={() => handleOfferToggle("po5_enabled")}
                />
              </div>
            </div>
          </div>

          <div className="col-lg-4">
            <div className="astrologer-panel card-bg-primary">
              <div className="astrologer-panel-head">
                <span className="astrologer-panel-title">Availability</span>
              </div>

              <div className="astrologer-avail-row">
                <div className="d-flex align-items-center gap-3">
                  <span className="astrologer-avail-icon">💬</span>
                  <div>
                    <div className="astrologer-avail-title">Chat</div>
                    <div className="astrologer-avail-sub">₹{chatRate}/min</div>
                  </div>
                </div>
                <Toggle
                  checked={dashboard.is_chat_online}
                  disabled={savingField === "chat"}
                  onChange={() => handleToggle("chat")}
                />
              </div>

              <div className="astrologer-avail-row">
                <div className="d-flex align-items-center gap-3">
                  <span className="astrologer-avail-icon">📞</span>
                  <div>
                    <div className="astrologer-avail-title">Call</div>
                    <div className="astrologer-avail-sub">₹{callRate}/min</div>
                  </div>
                </div>
                <Toggle
                  checked={dashboard.is_call_online}
                  disabled={savingField === "call"}
                  onChange={() => handleToggle("call")}
                />
              </div>

              <div className="astrologer-avail-row">
                <div className="d-flex align-items-center gap-3">
                  <span className="astrologer-avail-icon">🚫</span>
                  <div>
                    <div className="astrologer-avail-title">Busy</div>
                    <div className="astrologer-avail-sub">
                      Pause to avoid consultation before you're available
                    </div>
                  </div>
                </div>
                <Toggle
                  checked={isBusy}
                  disabled={savingField === "busy"}
                  onChange={() => handleToggle("busy")}
                />
              </div>

              <div className="astrologer-avail-row">
                <div className="d-flex align-items-center gap-3">
                  <span className="astrologer-avail-icon">🌙</span>
                  <div>
                    <div className="astrologer-avail-title">Do not disturb</div>
                    <div className="astrologer-avail-sub">Mute every incoming request</div>
                  </div>
                </div>
                <Toggle
                  checked={dashboard.quick_dnd}
                  disabled={savingField === "dnd"}
                  onChange={() => handleToggle("dnd")}
                />
              </div>
            </div>

            <div className="astrologer-panel card-bg-primary">
              <div className="astrologer-panel-head">
                <span className="astrologer-panel-title">Wallet</span>
                <Link href="/astrologer/wallet" className="astrologer-panel-link">
                  Open
                </Link>
              </div>

              <div className="terms-text-color small mb-1">Available to withdraw</div>
              <div className="astrologer-wallet-amount">
                ₹{Math.round(dashboard.wallet_balance || 0).toLocaleString("en-IN")}
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
