"use client";

import ProfileAvatar from "@/components/main/ProfileAvatar";
import VerificationBadge from "@/components/main/VerificationBadge";
import AcademyPackageItem from "@/components/academy/AcademyPackageItem";
import {
  AcademyPackageListSkeleton,
  AcademyProfileHeadSkeleton,
} from "@/components/academy/AcademySkeletons";
import Container from "@/components/elements/Container";
import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { useUserById } from "@/hooks/getUserById";
import { Course, IContactInfo } from "@/types/types";
import { profileActionBtnClass } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import Image from "next/image";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

interface AcademyStats {
  packagesCount: number;
  soldCount: number;
  totalVideos: number;
}

interface AcademyOwner {
  _id: string;
  user_name?: string;
  first_name?: string;
  last_name?: string;
  is_verified?: string;
  verify_badge?: string;
  is_Register?: string | boolean;
  user_score?: string | number;
}

interface AcademyData {
  _id: string;
  userId?: string;
  academy_name?: string;
  academy_image?: string;
  bio?: string;
  tag?: string;
  rate?: number;
  number_of_rate?: number;
  stats?: AcademyStats;
  owner?: AcademyOwner;
  contactInfo?: IContactInfo;
}

function openContact(
  type: "mobile" | "whatsapp" | "telegram" | "instagram",
  contact: IContactInfo | undefined,
  t: (key: string) => string
) {
  if (!contact) {
    toast.error(t("academy.profile.contact.none"));
    return;
  }

  if (type === "mobile") {
    const phone = contact.mobile || contact.phone;
    if (!phone) {
      toast.error(t("academy.profile.contact.mobileMissing"));
      return;
    }
    window.open(`tel:${phone}`, "_self");
    return;
  }

  if (type === "whatsapp") {
    if (!contact.whatsappNumber) {
      toast.error(t("academy.profile.contact.whatsappMissing"));
      return;
    }
    window.open(
      `https://wa.me/${contact.whatsappNumber.replace(/\D/g, "")}`,
      "_blank"
    );
    return;
  }

  if (type === "telegram") {
    if (!contact.telegramLink) {
      toast.error(t("academy.profile.contact.telegramMissing"));
      return;
    }
    window.open(`https://t.me/${contact.telegramLink.replace("@", "")}`, "_blank");
    return;
  }

  if (!contact.instagramLink) {
    toast.error(t("academy.profile.contact.instagramMissing"));
    return;
  }
  window.open(
    `https://instagram.com/${contact.instagramLink.replace("@", "")}`,
    "_blank"
  );
}

function isContactAvailable(
  type: "mobile" | "whatsapp" | "telegram" | "instagram",
  contact?: IContactInfo
): boolean {
  if (!contact) return false;
  if (type === "mobile") return Boolean(contact.mobile || contact.phone);
  if (type === "whatsapp") return Boolean(contact.whatsappNumber);
  if (type === "telegram") return Boolean(contact.telegramLink);
  return Boolean(contact.instagramLink);
}

export default function AcademyProfileClient() {
  const { t, i18n } = useTranslation("common");
  const params = useParams();
  const academyId = params?.academyId as string;
  const { request } = useAxios();

  const [academy, setAcademy] = useState<AcademyData | null>(null);
  const [courses, setCourses] = useState<Course[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingCourses, setIsLoadingCourses] = useState(true);

  const ownerUserId = academy?.owner?._id || academy?.userId || "";
  const ownerFromApi = useUserById(ownerUserId);

  useEffect(() => {
    const fetchAcademy = async () => {
      if (!academyId) {
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      try {
        const response = await request("POST", "/academy/findAcademyById", {
          _id: academyId,
        });
        const academyData =
          response?.academy || response?.data?.academy || response;
        setAcademy(academyData);
      } catch {
        toast.error(t("academy.profile.loadError"));
      } finally {
        setIsLoading(false);
      }
    };

    void fetchAcademy();
  }, [academyId, request]);

  useEffect(() => {
    const fetchCourses = async () => {
      if (!academyId) return;
      setIsLoadingCourses(true);
      try {
        const response = await request(
          "GET",
          `/academy/academy/get/getAcademyCourse/${academyId}?page=1&limit=50&status=accept`
        );
        const list =
          response?.data?.courses || response?.courses || [];
        setCourses(list);
      } catch {
        toast.error(t("academy.profile.packagesError"));
        setCourses([]);
      } finally {
        setIsLoadingCourses(false);
      }
    };

    if (academyId) void fetchCourses();
  }, [academyId, request]);

  if (isLoading) {
    return (
      <Container>
        <AcademyProfileHeadSkeleton />
        <AcademyPackageListSkeleton />
      </Container>
    );
  }

  if (!academy) {
    return (
      <Container>
        <div className="py-20 text-center text-neutral-500">
          {t("academy.profile.notFound")}
        </div>
      </Container>
    );
  }

  const academyName = academy.academy_name || t("academy.profile.defaultName");
  const owner = academy.owner;
  const displayUserName = owner?.user_name || ownerFromApi?.user_name;
  const displayUserScore =
    owner?.user_score ?? ownerFromApi?.user_score ?? 0;
  const isVerified = owner?.verify_badge ?? ownerFromApi?.verify_badge;
  const isRegister = owner?.is_Register ?? ownerFromApi?.is_Register;
  const stats = academy.stats;
  const shareUrl = `modstagram.com/academy/profile/${academyId}`;
  const isFa = (i18n.language || "fa").toLowerCase().startsWith("fa");

  return (
    <Container className="pb-28">
      <div className="w-full">
        <button
          type="button"
          className="flex w-full items-center justify-start gap-1.5 py-2 text-xs font-semibold md:text-sm"
          onClick={() => {
            navigator.clipboard.writeText(shareUrl);
            toast.success(t("academy.profile.addressCopied"));
          }}
        >
          <Image
            width={22}
            height={22}
            alt=""
            src="/images/icons/copy.svg"
            className="dark:invert"
          />
          <span>{t("academy.profile.copyAddress")}</span>
        </button>

        <div className="flex w-full flex-row-reverse items-center justify-between py-2">
          <div className="flex flex-col items-center text-xs md:text-sm">
            <div className="flex gap-5 mt-2">
              <div className="font-semibold flex flex-col items-center max-sm:text-[10px]">
                <span>{stats?.totalVideos ?? 0}</span>
                <span>{t("academy.profile.totalVideos")}</span>
              </div>
              <div className="font-semibold flex flex-col items-center text-[#0C8002] max-sm:text-[10px]">
                <span>{stats?.packagesCount ?? 0}</span>
                <span>{t("academy.profile.packageCount")}</span>
              </div>
              <div className="font-semibold flex flex-col items-center text-[#3A59A9] max-sm:text-[10px]">
                <span>{stats?.soldCount ?? 0}</span>
                <span>{t("academy.profile.soldCount")}</span>
              </div>
            </div>
          </div>
          <ProfileAvatar
            src={
              academy.academy_image
                ? `${IMAGE_BASE_URL}${academy.academy_image}`
                : undefined
            }
            alt={academyName}
            userId={owner?._id ?? ownerFromApi?._id}
            verifyBadge={isVerified}
            size="md"
            rounded="xl"
            className="md:h-[120px] md:w-[120px]"
          />
        </div>

        <div className="flex w-full flex-row-reverse items-end justify-between py-2 text-xs font-semibold md:text-sm">
          <div className="flex items-center gap-3">
            <div className="inline-flex items-center gap-1">
              <span>{Number(academy.rate || 0).toFixed(1)}</span>
              <Image
                width={22}
                height={22}
                alt={t("academy.profile.ratingAlt")}
                src="/images/icons/star1.png"
              />
            </div>
            <div className="inline-flex items-center gap-1">
              <span>{displayUserScore || 0}</span>
              <Image
                width={22}
                height={22}
                alt={t("academy.profile.userRatingAlt")}
                src="/images/icons/medal-star.png"
              />
            </div>
          </div>
          <div
            className={cn(
              "flex flex-col",
              isFa ? "items-end text-right" : "items-start text-left"
            )}
          >
            <h3 className="text-base md:text-lg font-bold">{academyName}</h3>
            {displayUserName ? (
              <Link
                href={`/users/${displayUserName}`}
                className={cn(
                  "mt-1 flex items-center gap-1 font-bold text-[#3A59A9] hover:underline",
                  isFa ? "flex-row-reverse" : "flex-row"
                )}
              >
                {displayUserName}
                <VerificationBadge verifyBadge={isVerified} />
              </Link>
            ) : null}
          </div>
        </div>

        <div className="py-2 w-full text-xs md:text-sm font-semibold">
          <p className="leading-relaxed text-neutral-700 dark:text-neutral-300">
            {academy.bio || t("academy.profile.noBio")}
          </p>
        </div>

        <div className="py-2 w-full text-xs md:text-sm font-semibold">
          <div className="mt-2 grid grid-cols-2 gap-1 md:grid-cols-4 md:gap-4">
            <button
              type="button"
              onClick={() => openContact("mobile", academy.contactInfo, t)}
              disabled={!isContactAvailable("mobile", academy.contactInfo)}
              className={cn(
                profileActionBtnClass,
                !isContactAvailable("mobile", academy.contactInfo) &&
                  "opacity-50"
              )}
            >
              {t("academy.profile.contact.mobile")}
            </button>
            <button
              type="button"
              onClick={() => openContact("whatsapp", academy.contactInfo, t)}
              disabled={!isContactAvailable("whatsapp", academy.contactInfo)}
              className={cn(
                profileActionBtnClass,
                !isContactAvailable("whatsapp", academy.contactInfo) &&
                  "opacity-50"
              )}
            >
              {t("academy.profile.contact.whatsapp")}
            </button>
            <button
              type="button"
              onClick={() => openContact("telegram", academy.contactInfo, t)}
              disabled={!isContactAvailable("telegram", academy.contactInfo)}
              className={cn(
                profileActionBtnClass,
                !isContactAvailable("telegram", academy.contactInfo) &&
                  "opacity-50"
              )}
            >
              {t("academy.profile.contact.telegram")}
            </button>
            <button
              type="button"
              onClick={() => openContact("instagram", academy.contactInfo, t)}
              disabled={!isContactAvailable("instagram", academy.contactInfo)}
              className={cn(
                profileActionBtnClass,
                !isContactAvailable("instagram", academy.contactInfo) &&
                  "opacity-50"
              )}
            >
              {t("academy.profile.contact.instagram")}
            </button>
          </div>
        </div>
      </div>

      <div className="mt-6">
        <h2 className="font-bold text-base mb-4">
          {t("academy.profile.trainingPackages")}
        </h2>
        {isLoadingCourses ? (
          <AcademyPackageListSkeleton count={3} />
        ) : courses.length === 0 ? (
          <p className="text-center text-gray-500 py-10">
            {t("academy.profile.noPackages")}
          </p>
        ) : (
          courses.map((course) => (
            <AcademyPackageItem key={course._id} course={course} />
          ))
        )}
      </div>
    </Container>
  );
}
