"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import { localizePath } from "@/translations/config";
import { getSubmitPath } from "@/lib/get-submit-path";
import { FaLock } from "react-icons/fa6";
import AdvisorActionsCard from "@/components/ui/advisor-actions-card";
import NavigationButton from "@/components/ui/navigation-button";
import { DotsLoader } from "@/components/ui/button";
import { PageBackground } from "@/components/utils/page-background";
import type {
  MarriageField,
  MarriageFieldValue,
  MarriageMatchSummary,
  MarriagePhoneFieldValue,
} from "@/hooks/marriage/types";
import { useMarriageProfileQuery } from "@/hooks/marriage/use-profile-main";
import { useI18n } from "@/translations/provider";
import { useViewPaddings } from "@/hooks/use-view-paddings";

const advisorAvatars = [
  { id: "advisor-primary", src: "/assets/images/Avatar Image.png" },
  { id: "advisor-secondary", src: "/assets/images/Ellipse 370.png" },
  { id: "advisor-tertiary", src: "/assets/images/Avatar Image.png" },
];

const fieldCandidates = {
  name: ["name", "full_name", "fullname", "first_name", "display_name"],
  occupation: ["occupation", "job", "profession", "career", "work", "education", "highest_level_of_education"],
  age: ["age"],
  city: ["city", "current_city", "residence_city", "location", "residence", "birth_city"],
  maritalStatus: ["marital_status", "maritalstatus", "relationship_status", "current_marital_status"],
  cityPreference: [
    "city_preference",
    "citypreference",
    "preferred_city",
    "preferred_location",
    "future_residence",
  ],
} as const;

type DisplayField = {
  id: string;
  label: string;
  value: string;
};

function normalizeFieldName(value: string) {
  return value
    .toLowerCase()
    .replace(/^q\d+[_-]?/, "")
    .replace(/[^a-z0-9]/g, "");
}

function formatFieldValue(value: MarriageFieldValue) {
  if (value === null || value === "") {
    return null;
  }

  if (isMarriagePhoneFieldValue(value)) {
    return `+${value.countryCode}${value.phoneNumber}`;
  }

  if (typeof value === "boolean") {
    return value ? "Yes" : "No";
  }

  return String(value);
}

function isMarriagePhoneFieldValue(
  value: unknown,
): value is MarriagePhoneFieldValue {
  if (!value || typeof value !== "object") {
    return false;
  }

  const phoneValue = value as Partial<MarriagePhoneFieldValue>;

  return (
    typeof phoneValue.countryCode === "string" &&
    typeof phoneValue.phoneNumber === "string"
  );
}

function titleFromKey(key: string) {
  return key
    .replace(/^q\d+[_-]?/i, "")
    .replace(/[_-]+/g, " ")
    .replace(/\s+/g, " ")
    .trim()
    .replace(/\b\w/g, (letter) => letter.toUpperCase());
}

function toDisplayField(field: MarriageField): DisplayField | null {
  const value = formatFieldValue(field.value);

  if (!value) {
    return null;
  }

  return {
    id: field.key || field.label || value,
    label: field.label || titleFromKey(field.key),
    value,
  };
}

function pickField(
  fields: MarriageField[],
  candidates: readonly string[],
  usedIndexes: Set<number>,
) {
  const candidateSet = new Set(candidates.map(normalizeFieldName));
  for (const [fieldIndex, field] of fields.entries()) {
    if (usedIndexes.has(fieldIndex)) {
      continue;
    }

    const displayField = toDisplayField(field);

    if (
      displayField &&
      [field.key, field.label].some((value) =>
        candidateSet.has(normalizeFieldName(value)),
      )
    ) {
      usedIndexes.add(fieldIndex);
      return displayField;
    }
  }

  return null;
}

function useMatchSummaryDisplay(matchSummary: MarriageMatchSummary | null) {
  return useMemo(() => {
    const fields = matchSummary?.public_info ?? [];
    const usedIndexes = new Set<number>();
    const name = pickField(fields, fieldCandidates.name, usedIndexes);
    const occupation = pickField(
      fields,
      fieldCandidates.occupation,
      usedIndexes,
    );
    const age = pickField(fields, fieldCandidates.age, usedIndexes);
    const city = pickField(fields, fieldCandidates.city, usedIndexes);
    const maritalStatus = pickField(
      fields,
      fieldCandidates.maritalStatus,
      usedIndexes,
    );
    const cityPreference = pickField(
      fields,
      fieldCandidates.cityPreference,
      usedIndexes,
    );
    const extraFields = fields
      .filter((_, index) => !usedIndexes.has(index))
      .map(toDisplayField)
      .filter((field): field is DisplayField => Boolean(field))
      .slice(0, 4);

    return {
      age,
      city,
      cityPreference,
      extraFields,
      maritalStatus,
      name:
        name?.value ??
        (matchSummary?.id ? `Profile #${matchSummary.id}` : null),
      occupation,
    };
  }, [matchSummary]);
}

function FieldLine({ field }: { field: DisplayField }) {
  return (
    <p className="break-words text-[10px] leading-[1.85] font-medium text-white">
      <span>{field.label}: </span>
      <span>{field.value}</span>
    </p>
  );
}

export default function NewMatchPage() {
  const router = useRouter();
  const { dictionary: t, locale } = useI18n();
  const { top, bottom } = useViewPaddings();
  const { data: profile, isError, isLoading } = useMarriageProfileQuery();

  useEffect(() => {
    if (!profile) {
      return;
    }
    const targetPath = getSubmitPath(profile);
    if (targetPath !== "/new-match") {
      router.replace(localizePath(targetPath, locale));
    }
  }, [profile, locale, router]);

  const matchSummary = profile?.match_summary ?? null;
  const matchDisplay = useMatchSummaryDisplay(matchSummary);
  const pairedFields = [matchDisplay.age, matchDisplay.city].filter(
    (field): field is DisplayField => Boolean(field),
  );

  const isFemaleProfile = profile?.gender === "female";
  const matchHeadingTitle = isFemaleProfile
    ? "پیشنهاد ازدواج جدید"
    : "YOU HAVE A NEW MATCH!";
  const matchHeadingDescription = isFemaleProfile
    ? "یک گزینه‌ی مناسب برای شما پیدا شده است. در صورت تایید، مشخصات شما جهت ادامه فرآیند معرفی ارزیابی خواهد شد."
    : "A matching profile has been found. Information is provided by the candidate's family or introducers. If you approve, we'll share your profile with her family.";

  return (
    <>
      <PageBackground />

      <main
        style={{ paddingBottom: `${20 + bottom}px`, paddingTop: `${Math.max(12, top + 4)}px` }}
        className="-mx-[17px] min-h-screen h-full text-center px-4"
      >
        <header className="flex items-center justify-between pb-3">
          <NavigationButton icon="back" />
          <h1 className="font-faminela">{t.common.appName}</h1>
          <NavigationButton icon="support" iconLabel={t.common.support} />
        </header>

        <div className="">
          <section className="flex flex-col items-center mt-9">
            <div
              aria-hidden="true"
              className="relative flex h-[60px] w-[60px] items-center justify-center rounded-full bg-[#FF4E67] shadow-[0_12px_28px_rgba(240,68,91,0.22)]"
            >
              <Image
                src={"/assets/images/Ellipse 1210.svg"}
                width={70}
                height={70}
                alt="notification"
              />
            </div>
            <h2 className="text-[22px] font-bold mt-3.5">{matchHeadingTitle}</h2>
            <p className="mt-[11px] max-w-[322px] text-[12px] leading-[1.35] font-semibold text-[#7C7C7C]">
              {matchHeadingDescription}
            </p>
          </section>
          <div className="flex h-full flex-col justify-between">
            <section className="mt-[36px] rounded-[15px] bg-[linear-gradient(180deg,#F0445B_0%,#F4556E_100%)] px-[17px] pt-[18px] pb-[17px] text-white shadow-[0_18px_38px_rgba(240,68,91,0.25)]">
              {isLoading ? (
                <div className="flex items-center justify-center py-8">
                  <DotsLoader />
                </div>
              ) : isError ? (
                <p className="py-8 text-[13px] font-semibold">
                  Unable to load match summary.
                </p>
              ) : matchSummary ? (
                <>
                  <h2 className="break-words text-[13px] leading-[1.4] font-bold">
                    <span>Name: </span>
                    <span>{matchDisplay.name}</span>
                  </h2>

                  <div className="mt-[3px] min-h-[48px]">
                    {matchDisplay.occupation ? (
                      <FieldLine field={matchDisplay.occupation} />
                    ) : null}

                    {pairedFields.length ? (
                      <p className="break-words text-[10px] leading-[1.85] font-medium text-white">
                        {pairedFields.map((field, index) => (
                          <span key={field.id}>
                            {index > 0 ? <span> | </span> : null}
                            <span>
                              {field.label}: {field.value}
                            </span>
                          </span>
                        ))}
                      </p>
                    ) : null}

                    {matchDisplay.maritalStatus ? (
                      <FieldLine field={matchDisplay.maritalStatus} />
                    ) : null}
                    {matchDisplay.cityPreference ? (
                      <FieldLine field={matchDisplay.cityPreference} />
                    ) : null}
                  </div>

                  <Link
                    href={localizePath("/new-match/profile", locale)}
                    className="mt-[15px] inline-flex w-full items-center justify-center rounded-[10px] border-none bg-white py-[12px] text-[16px] font-semibold text-[#F0445B] no-underline shadow-none hover:bg-white/95 transition-colors"
                  >
                    View Profile
                  </Link>
                </>
              ) : (
                <p className="py-8 text-[13px] font-semibold">
                  No match summary is available yet.
                </p>
              )}
            </section>
            <div className="w-full space-y-3">
              <AdvisorActionsCard
                className="mt-[36px]"
                title={t.findingMatch.advisorTitle}
                description={t.findingMatch.advisorDescription}
                avatars={advisorAvatars}
                extraCount={7}
                getAdvisorLabel={t.findingMatch.getAdvisor}
                getAdvisorHref="/questions-list"
              />

                <div className="flex cursor-not-allowed w-full items-center justify-center rounded-[11px] border-none bg-[#DBDBDB] px-6 py-3.5 text-[#747474] no-underline shadow-none">
                  <span className="flex items-center gap-1">
                    <FaLock className="size-6 shrink-0 text-[#747474]" />
                    <span className="leading-none font-semibold tracking-[-0.03em]">
                      Profile locked
                    </span>
                  </span>
              </div>
            </div>
          </div>
        </div>
      </main>
    </>
  );
}
