"use client";

import { 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 {
  getAstrologerProfile,
  getAstrologerDashboard,
  getAstrologerReviews,
  astrologerLogout,
  deleteAstrologerAccount,
  friendlyErrorMessage,
} from "@/app/lib/astrologer";
import { clearAstrologerSession } from "@/app/lib/astrologer-token";

interface Review {
  rating: number;
  text: string;
  reviewer: string;
}

function extractSkillNames(skills: any[]): string[] {
  return (skills ?? [])
    .map((s) => s?.Skill?.name ?? s?.skill_name ?? s?.name)
    .filter(Boolean);
}

function extractLanguageNames(languages: any[]): string[] {
  return (languages ?? [])
    .map((l) => l?.Language?.name ?? l?.language_name ?? l?.name)
    .filter(Boolean);
}

function extractReviews(response: any): Review[] {
  const list = response?.recordList ?? response?.data?.recordList ?? [];

  if (!Array.isArray(list)) return [];

  return list.map((r: any) => ({
    rating: Number(r.rating ?? r.Rating ?? 0),
    text: r.review ?? r.Review ?? r.comment ?? "",
    reviewer:
      r.userName ?? r.user_name ?? r.name ?? r.User?.name ?? "Anonymous",
  }));
}

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

  const [profile, setProfile] = useState<any>(null);
  const [dashboard, setDashboard] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [astrologerToken, setAstrologerToken] = useState<string | null>(null);

  const [reviews, setReviews] = useState<Review[] | null>(null);
  const [reviewsError, setReviewsError] = useState<string | null>(null);

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

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

    setAstrologerToken(token);

    Promise.all([getAstrologerProfile(token), getAstrologerDashboard(token)])
      .then(([profileResponse, dashboardResponse]) => {
        const profileData = profileResponse.data ?? profileResponse;

        setProfile(profileData);
        setDashboard(dashboardResponse.data ?? dashboardResponse);

        const astrologerId = profileData?.ID ?? profileData?.id;

        if (!astrologerId) return;

        getAstrologerReviews(astrologerId, token)
          .then((response) => {
            if (!response.success) {
              setReviewsError(
                friendlyErrorMessage(response.message, "Unable to load reviews.")
              );
              return;
            }

            setReviews(extractReviews(response));
          })
          .catch(() => setReviewsError("Unable to load reviews."));
      })
      .catch(() => {})
      .finally(() => setLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

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

    try {
      if (token) {
        await astrologerLogout(token);
      }
    } catch {
      // fall through — clear the local session regardless
    } finally {
      clearAstrologerSession();
      router.push("/astrologer/signin");
    }
  };

  const handleDelete = async () => {
    if (
      !confirm(
        "Are you sure? This removes your astrologer profile and history."
      )
    ) {
      return;
    }

    const token = localStorage.getItem("astrologerToken");

    if (!token) return;

    try {
      const response = await deleteAstrologerAccount(token);

      if (response.success) {
        toast.success("Account deleted");
        clearAstrologerSession();
        router.push("/astrologer");
      } else {
        toast.error(friendlyErrorMessage(response.message, "Unable to delete account"));
      }
    } catch (error: any) {
      toast.error(
        error.response?.data?.message ?? "Unable to delete account."
      );
    }
  };

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

  // Confirmed live: GET /astrologer/profile returns PascalCase GORM
  // field names (Name, ExperienceYears, ChatRate...), not the
  // snake_case shape the wizard-step endpoints use — alias both. The
  // dashboard endpoint additionally carries live rate/rating fields
  // that don't exist on the profile response at all.
  const name = profile?.Name ?? profile?.display_name ?? profile?.name;
  const primarySkill = profile?.PrimarySkill ?? profile?.primary_skills;
  const experienceYears =
    profile?.ExperienceYears ?? profile?.experience_years ?? 0;
  const status =
    profile?.ProfileStatus ?? profile?.status ?? profile?.profile_status;
  const chatRate = dashboard?.chat_rate ?? profile?.ChatRate ?? profile?.chat_rate;
  const callRate = dashboard?.call_rate ?? profile?.AudioCallRate ?? profile?.call_rate;
  const avatarUrl = profile?.ProfileImage || profile?.profile_image;
  const initial = (name || "A").trim().charAt(0).toUpperCase();

  const rating = Number(dashboard?.average_rating ?? 0);
  const responseRate = Number(dashboard?.response_rate ?? 0);
  const acceptanceRate = Number(dashboard?.acceptance_rate ?? 0);

  const skillNames = extractSkillNames(profile?.skills);
  const languageNames = extractLanguageNames(profile?.languages);

  const bankAccount =
    (profile?.BankAccount ?? profile?.bank_account)?.[0] ?? null;

  const bankHint = bankAccount
    ? `${bankAccount.bank_name} ••••${String(bankAccount.account_number).slice(-4)}`
    : "Add your payout account";

  const documents: any[] = profile?.documents ?? [];

  const documentsHint =
    documents.length === 0
      ? "No documents uploaded yet"
      : documents.every((d) =>
          ["VERIFIED", "APPROVED"].includes((d.verification_status || "").toUpperCase())
        )
      ? `${documents.length} document${documents.length === 1 ? "" : "s"} verified`
      : `${documents.length} document${documents.length === 1 ? "" : "s"} · pending review`;

  const manageLinks = [
    {
      href: "/astrologer/profile/edit/basic",
      label: "Edit profile",
      hint: "Name, bio, city, photo",
      disabled: false,
    },
    {
      href: "/astrologer/profile/edit/availability",
      label: "Availability & rates",
      hint: `₹${chatRate || "--"}/min chat · ₹${callRate || "--"}/min call`,
      disabled: false,
    },
    {
      href: "/astrologer/dashboard",
      label: "Offers & campaigns",
      hint: "Manage your active offers",
      disabled: false,
    },
    {
      href: "/astrologer/profile/edit/skills",
      label: "Skills & languages",
      hint: `${skillNames.length} skill${skillNames.length === 1 ? "" : "s"} · ${languageNames.length} language${languageNames.length === 1 ? "" : "s"}`,
      disabled: false,
    },
    {
      href: "/astrologer/profile/edit/bank",
      label: "Bank account",
      hint: bankHint,
      // Bank and KYC document details are locked from self-editing
      // after approval — changing either needs a support/compliance
      // review, not a silent in-app edit.
      disabled: true,
    },
    {
      href: "/astrologer/profile/edit/documents",
      label: "Documents",
      hint: documentsHint,
      disabled: true,
    },
  ];

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

      <main className="astrologer-dashboard-main">
        <div className="astrologer-dashboard-topbar">
          <div className="astrologer-dashboard-name">Profile</div>
          <div className="astrologer-dashboard-actions">
            <NotificationBell
              audience="astrologer"
              token={astrologerToken}
              notificationsHref="/astrologer/notifications"
              dark
            />
          </div>
        </div>

        <div className="row g-4">
          <div className="col-lg-8">
            <div className="astrologer-panel card-bg-primary">
              <div className="d-flex align-items-center gap-3">
                {avatarUrl ? (
                  <img src={avatarUrl} alt="" className="astrologer-dashboard-avatar" style={{ width: 64, height: 64 }} />
                ) : (
                  <div
                    className="astrologer-dashboard-avatar d-flex align-items-center justify-content-center bg-warning text-dark fw-bold"
                    style={{ width: 64, height: 64, fontSize: 24 }}
                  >
                    {initial}
                  </div>
                )}

                <div className="flex-fill">
                  <div className="d-flex justify-content-between align-items-start">
                    <h5 className="text-white mb-1">{name ?? "Astrologer"}</h5>
                    <span className="badge bg-success">{status ?? "—"}</span>
                  </div>
                  <div className="terms-text-color small">
                    {primarySkill ?? "—"} &bull; {experienceYears} years
                  </div>
                </div>
              </div>
            </div>

            <div className="astrologer-stat-row">
              <div className="astrologer-stat-card card-bg-primary">
                <div className="astrologer-stat-label">⭐ Rating</div>
                <div className="astrologer-stat-value">
                  {rating > 0 ? rating.toFixed(1) : "New"}
                </div>
              </div>

              <div className="astrologer-stat-card card-bg-primary">
                <div className="astrologer-stat-label">💬 Response rate</div>
                <div className="astrologer-stat-value">{responseRate}%</div>
              </div>

              <div className="astrologer-stat-card card-bg-primary">
                <div className="astrologer-stat-label">✅ Acceptance rate</div>
                <div className="astrologer-stat-value">{acceptanceRate}%</div>
              </div>
            </div>

            <div className="astrologer-panel card-bg-primary">
              <div className="astrologer-panel-head">
                <span className="astrologer-panel-title">How users see you</span>
              </div>

              <div className="astrologer-preview-card">
                {avatarUrl ? (
                  <img src={avatarUrl} alt="" className="astrologer-preview-avatar" />
                ) : (
                  <div className="astrologer-preview-avatar d-flex align-items-center justify-content-center bg-warning text-dark fw-bold">
                    {initial}
                  </div>
                )}

                <div className="flex-fill">
                  <div className="text-white fw-semibold">{name ?? "Astrologer"}</div>
                  <div className="terms-text-color small">
                    {[primarySkill, ...skillNames.filter((s) => s !== primarySkill)]
                      .filter(Boolean)
                      .join(", ") || "—"}
                  </div>
                  <div className="terms-text-color small">
                    {languageNames.length > 0 ? languageNames.join(", ") : "—"} · {experienceYears} yrs exp.
                  </div>
                  <div className="terms-text-color small mt-1">
                    {rating > 0 ? `⭐ ${rating.toFixed(1)}` : "New astrologer"}
                  </div>
                </div>

                <div className="text-end">
                  <div className="text-warning fw-bold mb-2">₹{chatRate || "--"}/min</div>
                  <button type="button" className="btn btn-primary btn-sm" disabled>
                    Chat
                  </button>
                </div>
              </div>

              <p className="astrologer-empty-hint mb-0">
                This is a preview of how your card looks to users browsing astrologers.
              </p>
            </div>

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

              {reviewsError && (
                <p className="astrologer-empty-hint mb-0">{reviewsError}</p>
              )}

              {!reviewsError && reviews && reviews.length === 0 && (
                <p className="astrologer-empty-hint mb-0">No reviews yet.</p>
              )}

              {!reviewsError &&
                reviews &&
                reviews.map((review, index) => (
                  <div className="astrologer-review-row" key={index}>
                    <div className="d-flex justify-content-between">
                      <span className="text-white fw-semibold">{review.reviewer}</span>
                      <span className="text-warning">{"★".repeat(Math.round(review.rating))}</span>
                    </div>
                    {review.text && (
                      <div className="terms-text-color small mt-1">{review.text}</div>
                    )}
                  </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">Manage</span>
              </div>

              {manageLinks.map((item) =>
                item.disabled ? (
                  <div
                    key={item.href}
                    className="astrologer-step-row astrologer-step-row-disabled"
                    title="Contact support to update this — it's locked after approval"
                  >
                    <span className="astrologer-step-row-title">
                      <div>{item.label}</div>
                      <small className="terms-text-color">{item.hint}</small>
                    </span>

                    <span className="terms-text-color">🔒</span>
                  </div>
                ) : (
                  <Link
                    key={item.href}
                    href={item.href}
                    className="astrologer-step-row"
                  >
                    <span className="astrologer-step-row-title">
                      <div>{item.label}</div>
                      <small className="terms-text-color">{item.hint}</small>
                    </span>

                    <span className="terms-text-color">&rsaquo;</span>
                  </Link>
                )
              )}
            </div>

            <div className="astrologer-panel card-bg-primary">
              <button
                type="button"
                className="astrologer-step-row w-100 border-0 bg-transparent text-start"
                onClick={handleLogout}
              >
                <span className="astrologer-step-row-title">Log out</span>
              </button>

              <button
                type="button"
                className="astrologer-step-row w-100 border-0 bg-transparent text-start text-danger"
                onClick={handleDelete}
              >
                <span className="astrologer-step-row-title text-danger">
                  Delete account
                </span>
              </button>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
