"use client";

import { Avatar, Card, CardBody, CardHeader, Chip } from "@nextui-org/react";
import { useRouter } from "next/navigation";
import { format, parse } from "date-fns";

import ProgressBar from "@/components/common/progress-bar";
import { generateUserGreeting } from "@/utils/userGreeting";
import ProfileLayout from "@/components/pages/participant/profile/partials/profile-layout";
import {
  ACCOUNT_MANAGEMENT_CATEGORIES,
  PROFILE_CATEGORIES,
} from "@/constants/ui-helpers";

type ProfileCategoryProps = {
  label: string;
  description: string;
  href: string;
  percentage: number;
  sectionLabel: string;
  isSeniorProfessional: boolean;
  icon: React.ReactNode;
};

type AccountManagementCategoryProps = {
  label: string;
  description: string;
  href: string;
  icon: React.ReactNode;
};

function ProfileCategoryCard({
  label,
  description,
  href,
  sectionLabel,
  percentage,
  isSeniorProfessional,
  icon,
}: ProfileCategoryProps) {
  const router = useRouter();
  const isCompleted = percentage === 100;
  let chipTitle = "";
  let chipColor = "";

  if (sectionLabel === "companyInformation" && isSeniorProfessional) {
    chipTitle = isCompleted ? "Completed" : "In progress";
  } else if (sectionLabel === "companyInformation" && !isSeniorProfessional) {
    chipTitle = "Not required";
  } else {
    chipTitle = isCompleted ? "Completed" : "In progress";
  }

  if (sectionLabel === "companyInformation" && isSeniorProfessional) {
    chipColor = isCompleted ? "bg-slate-100" : "bg-yellow-500/50";
  } else if (sectionLabel === "companyInformation" && !isSeniorProfessional) {
    chipColor = "bg-gray-500/50";
  } else {
    chipColor = isCompleted ? "bg-slate-100" : "bg-yellow-500/50";
  }

  const handleCardClick = (href: string) => {
    router.push(href);
  };

  return (
    <Card
      disableAnimation
      isPressable
      className="hover:bg-gray-100 hover:outline-offset-0 hover:outline-2"
      classNames={{ base: "shadow-none border-2 px-2 py-3" }}
      onPress={() => handleCardClick(href)}
    >
      <CardHeader>
        <div>
          <Avatar
            isBordered
            classNames={{
              base: "size-3 bg-jet ring-1 ring-jet",
            }}
            icon={icon}
            radius="full"
          />
        </div>
        <div className="flex flex-col font-inter ps-3 w-full">
          <div className="flex flex-row justify-between items-center">
            <p className="text-sm font-bold text-start">{label}</p>
            <Chip
              className={`p-2 ${chipColor}`}
              classNames={{
                base: "justify-end",
                content: "text-xs font-semibold font-inter text-black",
              }}
              size="sm"
            >
              {chipTitle}
            </Chip>
          </div>
          <p className="text-sm text-start tracking-tight text-gray-400 font-semibold">{`${
            sectionLabel === "companyInformation" && !isSeniorProfessional
              ? "Not required"
              : `${percentage}%`
          }`}</p>
        </div>
      </CardHeader>

      <CardBody className="px-3 py-1 text-sm text-gray-800 font-noto">
        <p>{description}</p>
      </CardBody>
    </Card>
  );
}

function AccountManagementCard({
  label,
  href,
  icon,
  description,
}: AccountManagementCategoryProps) {
  const router = useRouter();

  const handleCardClick = (href: string) => {
    router.push(href);
  };

  return (
    <Card
      disableAnimation
      isPressable
      className="hover:bg-gray-100 hover:outline-offset-0 hover:outline-2"
      classNames={{ base: "shadow-none border-2 px-2 py-3" }}
      onPress={() => handleCardClick(href)}
    >
      <CardHeader>
        <div>
          <Avatar
            isBordered
            classNames={{
              base: "size-3 bg-jet ring-1 ring-jet",
            }}
            icon={icon}
            radius="full"
          />
        </div>
        <div className="flex flex-col font-inter ps-3 w-full">
          <div className="flex flex-row justify-between items-center">
            <p className="text-sm font-bold text-start">{label}</p>
          </div>
        </div>
      </CardHeader>
      <CardBody className="px-3 py-1 text-sm text-gray-800 font-noto">
        <p>{description}</p>
      </CardBody>
    </Card>
  );
}

type ProfileHomeProps = {
  participantFirstName: string;
  percentagesBySection: Record<string, number>;
  totalCompletion: number;
  isSeniorProfessional: boolean;
  memberSince: string;
};

function ProfileHome({
  participantFirstName,
  totalCompletion,
  percentagesBySection,
  isSeniorProfessional,
  memberSince,
}: ProfileHomeProps) {
  const userGreeting = generateUserGreeting();
  const isProfileCompleted = totalCompletion === 100;
  const helperText = isProfileCompleted
    ? "Congratulations, your profile is complete! The data you provided gives you the best chance of being selected for future research. Make sure you frequently check your details and update them when required."
    : "To increase your chances of being selected to take part in research, please ensure your profile is complete and all your information is up to date.";

  return (
    <ProfileLayout>
      <div className="p-8 text-center xl:text-start light text-black w-full min-h-[700px]">
        <span className="font-inter text-3xl font-black tracking-tight">{`${userGreeting}, ${participantFirstName}.`}</span>
        <div className="flex flex-col xl:flex-row mt-12 space-y-4 text-center xl:text-start xl:space-x-4">
          {/* Left section */}
          <div className="flex flex-col">
            <span className="font-inter font-black text-6xl">
              {totalCompletion}%
            </span>
            <span className="font-noto">
              of your profile is complete {isProfileCompleted ? "🎉" : "🚧"}
            </span>
          </div>
          <div className="flex flex-col space-y-4 w-full">
            <ProgressBar
              aria-label={`${totalCompletion}% of your profile is complete`}
              classNames={{
                label: "text-sm font-bold text-black tracking-tight font-inter",
                indicator: isProfileCompleted
                  ? "bg-green-600"
                  : "bg-gradient-to-r dark:from-paleBlue dark:to-participant-cerulean from-peach to-participant-bittersweet",
              }}
              value={totalCompletion}
            />
            <span className="font-noto">{helperText}</span>
          </div>
        </div>
        {/* Profile categories */}
        <div className="my-8">
          <div className="flex flex-col">
            <span className="font-inter text-xl font-black tracking-tight">
              Your profile overview
            </span>
            <span className="font-noto text-gray-600 text-sm">
              People for Research member since{" "}
              {format(
                parse(memberSince, "dd/MM/yyyy", new Date()),
                "MMMM yyyy"
              )}
              .
            </span>
          </div>
        </div>
        <div className="mx-auto grid grid-cols-1 gap-6 sm:grid-cols-2 xl:mx-0 xl:grid-cols-3 xxl:grid-cols-5 xl:gap-4 mb-12">
          {PROFILE_CATEGORIES.map(
            ({ label, description, href, sectionLabel, icon }, index) => {
              const Icon = icon;

              return (
                <ProfileCategoryCard
                  key={`profile-category-${index}`}
                  description={description}
                  href={href}
                  icon={<Icon className="size-6 text-white" />}
                  isSeniorProfessional={isSeniorProfessional}
                  label={label}
                  percentage={percentagesBySection[sectionLabel]}
                  sectionLabel={sectionLabel}
                />
              );
            }
          )}
        </div>
        <div className="my-8 xl:hidden">
          <div className="flex flex-col">
            <span className="font-inter text-xl font-black tracking-tight">
              Account management
            </span>
            <span className="font-noto text-gray-600 text-sm">
              You can manage your account details and preferences here.
            </span>
          </div>
        </div>
        <div className="mx-auto grid grid-cols-1 gap-6 sm:grid-cols-2 xl:mx-0 xl:grid-cols-3 xxl:grid-cols-5 xl:gap-4 mb-12 xl:hidden">
          {ACCOUNT_MANAGEMENT_CATEGORIES.map(
            ({ label, description, href, icon }, index) => {
              const Icon = icon;

              return (
                <AccountManagementCard
                  key={`profile-category-${index}`}
                  description={description}
                  href={href}
                  icon={<Icon className="size-6 text-white" />}
                  label={label}
                />
              );
            }
          )}
        </div>
      </div>
    </ProfileLayout>
  );
}

export default ProfileHome;
