"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
import Button from "@/components/Componentes/button";
import DismissReasonSheet from "@/components/Componentes/dismiss-reason-sheet";
import FemaleConsentSheet from "@/components/Componentes/female-consent-sheet";
import InformationSheet from "@/components/Componentes/information-sheet";
import { LoadingSkeleton } from "@/components/Componentes/loading-skeleton";
import { LoadingThreeDot } from "@/components/Componentes/loading-three-dot";
import NavigationButton from "@/components/Componentes/navigation-button";
import { PageBackground } from "@/components/Componentes/page-background";
import StickyHeader from "@/components/Componentes/sticky-header";
import type {
  MarriageCaseStatus,
  MarriageField,
  MarriageFieldValue,
  MarriageGender,
  MarriagePhoneFieldValue,
} from "@/hooks/marriage/types";
import { useRespondToMarriageCaseMutation } from "@/hooks/marriage/use-case-respond";
import { useMarriageProfileQuery } from "@/hooks/marriage/use-profile-main";
import { getSubmitPath } from "@/lib/get-submit-path";
import { localizePath } from "@/translations/config";
import { useI18n } from "@/translations/provider";

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 isImageField(field: MarriageField) {
  return /(avatar|image|photo|picture|portrait|upload)/i.test(
    `${field.key} ${field.label}`,
  );
}

function canAcceptProfile(
  gender: MarriageGender | null | undefined,
  status: MarriageCaseStatus | null | undefined,
) {
  if (!gender || !status) {
    return false;
  }

  if (gender === "female") {
    return status === "introduced" || status === "male_accepted";
  }

  return status === "introduced";
}

function MatchField({
  field,
  isCandidateFemale,
}: {
  field: MarriageField;
  isCandidateFemale: boolean;
}) {
  const value = formatFieldValue(field.value);

  if (!value || isImageField(field)) {
    return null;
  }

  const label = field.label || titleFromKey(field.key);

  if (isCandidateFemale) {
    return (
      <div className="flex flex-col items-start w-full border-b border-black/10 pb-[14px] mt-[14px]">
        <p
          className="text-[12px] font-semibold leading-[17px] text-[#978787]"
          style={{ fontFamily: "'Segoe UI', sans-serif" }}
        >
          {label}
        </p>
        <p
          className="text-[16px] font-bold leading-[20px] text-[#111111] mt-[7px] text-left"
          style={{ fontFamily: "'Segoe UI', sans-serif" }}
        >
          {value}
        </p>
      </div>
    );
  }

  return (
    <div className="mb-3 space-y-1 border-b border-[#000000]/08 pb-2.5 text-left">
      <p className="text-[11px] font-semibold text-[#8E8E93]">{label}</p>
      <p className="group-14 font-semibold text-[#1C1C1E]">{value}</p>
    </div>
  );
}

function MatchPublicProfileFields({
  publicInfo,
  isCandidateFemale,
}: {
  publicInfo: MarriageField[] | null | undefined;
  isCandidateFemale: boolean;
}) {
  const visibleFields = useMemo(() => {
    if (!publicInfo) return [];
    return publicInfo.filter((field) => {
      if (field.value === null || field.value === "" || isImageField(field)) {
        return false;
      }
      if ((field as any).private === true) {
        return false;
      }
      return true;
    });
  }, [publicInfo]);

  if (!visibleFields.length) {
    return (
      <div className="mt-6 rounded-[16px] bg-white/70 p-5 text-center shadow-xs">
        <p className="group-12 font-medium text-[#747474]">
          اطلاعات عمومی قابل نمایشی ثبت نشده است.
        </p>
      </div>
    );
  }

  if (isCandidateFemale) {
    return (
      <div className="flex flex-col w-full mt-6" style={{ gap: "14px" }}>
        {visibleFields.map((field) => (
          <MatchField key={field.key} field={field} isCandidateFemale={true} />
        ))}
      </div>
    );
  }

  return (
    <div className="mt-6 space-y-3 rounded-[18px] bg-white/80 p-4 shadow-xs">
      <h3 className="border-b border-[#F0445B]/15 pb-2 text-right group-12 font-bold text-[#F0445B]">
        اطلاعات عمومی و مشخصات فردی
      </h3>
      <div className="space-y-2.5">
        {visibleFields.map((field) => (
          <MatchField key={field.key} field={field} isCandidateFemale={false} />
        ))}
      </div>
    </div>
  );
}

function NewMatchProfileSkeleton({
  hideBackButton = false,
}: {
  hideBackButton?: boolean;
}) {
  const { dictionary: t } = useI18n();

  return (
    <>
      <PageBackground />
      <main className="-mx-[17px] flex min-h-screen flex-col bg-[#F5F5F5] pb-10">
        <StickyHeader>
          <div className="flex items-center justify-between gap-3">
            {!hideBackButton ? (
              <NavigationButton
                variant="transparent"
                icon="close"
                iconLabel={t["Go back"]}
              />
            ) : (
              <div className="size-10 shrink-0" />
            )}
            <h1 className="min-w-0 flex-1 text-center group-16 font-bold text-white">
              {t["New Match"]}
            </h1>
            <div className="size-10 shrink-0" />
          </div>
        </StickyHeader>

        <section className="px-[17px] pb-32 pt-5">
          <div className="flex flex-col items-center justify-center w-full">
            <LoadingSkeleton className="size-[90px] rounded-full shadow-sm" />
            <LoadingSkeleton className="mt-3.5 h-7 w-44 rounded-xl shadow-xs" />
          </div>

          <div className="mt-6 space-y-4 rounded-[18px] bg-white/80 p-5 shadow-xs">
            <LoadingSkeleton className="h-4 w-44 rounded-md" />

            <div className="space-y-4 pt-1">
              <div className="space-y-1.5 border-b border-[#000000]/05 pb-3">
                <LoadingSkeleton className="h-3 w-24" />
                <LoadingSkeleton className="h-4 w-48" />
              </div>

              <div className="space-y-1.5 border-b border-[#000000]/05 pb-3">
                <LoadingSkeleton className="h-3 w-28" />
                <LoadingSkeleton className="h-4 w-36" />
              </div>

              <div className="space-y-1.5 border-b border-[#000000]/05 pb-3">
                <LoadingSkeleton className="h-3 w-20" />
                <LoadingSkeleton className="h-4 w-56" />
              </div>

              <div className="space-y-1.5 border-b border-[#000000]/05 pb-3">
                <LoadingSkeleton className="h-3 w-32" />
                <LoadingSkeleton className="h-4 w-40" />
              </div>
            </div>
          </div>
        </section>

        <div
          style={{ paddingBottom: `var(--safe-bottom)` }}
          className="fixed inset-x-0 bottom-0 z-30 px-[17px]"
        >
          <div className="mx-auto w-full sm:max-w-[375px] rounded-t-[24px] bg-white px-4 py-4 shadow-[0_12px_30px_rgba(0,0,0,0.14)]">
            <div className="flex gap-3">
              <LoadingSkeleton className="w-1/3 h-[46px] rounded-[12px]" />
              <LoadingSkeleton className="w-2/3 h-[46px] rounded-[12px]" />
            </div>
          </div>
        </div>
      </main>
    </>
  );
}

function formatBoldText(text: string) {
  if (!text) return "";
  const parts = text.split(/\*\*([^*]+)\*\*/g);
  return parts.map((part, index) => {
    if (index % 2 === 1) {
      return (
        <strong key={index} className="font-bold text-[#111111]">
          {part}
        </strong>
      );
    }
    return part;
  });
}

export default function NewMatchProfilePage() {
  const { dictionary: t, locale } = useI18n();
  const router = useRouter();
  const [isRequestSheetOpen, setIsRequestSheetOpen] = useState(false);
  const [isFemaleConsentChecked, setIsFemaleConsentChecked] = useState(false);
  const [isRejectSheetOpen, setIsRejectSheetOpen] = useState(false);
  const [isMaleRejectWarningOpen, setIsMaleRejectWarningOpen] = useState(false);
  const [isDismissReasonSheetOpen, setIsDismissReasonSheetOpen] =
    useState(false);
  const {
    data: profile,
    isLoading,
    refetch: refetchProfile,
  } = useMarriageProfileQuery();

  useEffect(() => {
    if (!profile) {
      return;
    }
    const targetPath = getSubmitPath(profile);
    const caseStatus = profile?.active_case?.status;
    const isProfileMatched = profile?.status === "matched";
    const isViewingAllowed =
      caseStatus === "payment_done" ||
      caseStatus === "contacted" ||
      caseStatus === "finalized" ||
      isProfileMatched;

    if (
      targetPath !== "/new-match" &&
      targetPath !== "/request-sent" &&
      !isViewingAllowed
    ) {
      router.replace(localizePath(targetPath, locale));
    }
  }, [profile, locale, router]);

  const caseId = profile?.active_case?.case_id;
  const caseStatus = profile?.active_case?.status;
  const isFemaleProfile = profile?.gender === "female";
  const respondMutation = useRespondToMarriageCaseMutation(caseId ?? "", {
    onSuccess: async (_, variables) => {
      if (variables.action === "accept") {
        const { data: updatedProfile } = await refetchProfile();
        const nextPath = getSubmitPath(updatedProfile);
        router.replace(localizePath(nextPath, locale));
        return;
      }

      router.replace(localizePath("/finding-match", locale));
    },
  });

  const candidateName = useMemo(() => {
    const publicInfo = profile?.match_summary?.public_info ?? [];
    const nameField = publicInfo.find(
      (f) =>
        f.key === "q1_full_name" ||
        f.key.toLowerCase().includes("name") ||
        f.key.toLowerCase().includes("nam") ||
        f.label.includes("نام"),
    );
    const formatted = formatFieldValue(nameField?.value ?? null);
    if (formatted) return formatted;
    const firstVal = publicInfo.find((f) => Boolean(f.value))?.value ?? null;
    return formatFieldValue(firstVal) || "نامشخص";
  }, [profile?.match_summary?.public_info]);

  const isCandidateFemale =
    profile?.match_summary?.gender === "female" || profile?.gender === "male";
  const avatarSrc = isCandidateFemale
    ? "/assets/images/female_avatar.svg"
    : "/assets/images/Group 1597880481.png";

  const isRedirecting = useMemo(() => {
    if (!profile) return false;
    const targetPath = getSubmitPath(profile);
    const caseStatus = profile?.active_case?.status;
    const isProfileMatched = profile?.status === "matched";
    const isViewingAllowed =
      caseStatus === "payment_done" ||
      caseStatus === "contacted" ||
      caseStatus === "finalized" ||
      isProfileMatched;

    return (
      targetPath !== "/new-match" &&
      targetPath !== "/request-sent" &&
      !isViewingAllowed
    );
  }, [profile]);

  const isSubmitting = respondMutation.isPending;

  if (isLoading || !profile || isRedirecting || isSubmitting) {
    return <NewMatchProfileSkeleton hideBackButton={isSubmitting} />;
  }
  const isAcceptProfileEnabled =
    Boolean(caseId) &&
    !isSubmitting &&
    canAcceptProfile(profile?.gender, caseStatus);
  const isRejectProfileEnabled = isAcceptProfileEnabled;

  const nameParts = candidateName.trim().split(/\s+/);
  const _firstName = nameParts[0] || "";
  const _lastName = nameParts.slice(1).join(" ") || "";

  const mainClass = "-mx-[17px] flex min-h-screen flex-col pb-10";

  const mainStyle = {
    backgroundImage: `url("/assets/images/islamic_pattern_2_2892_3864.svg")`,
    backgroundColor: "#F5F5F5",
    backgroundRepeat: "repeat-y",
    backgroundSize: "100% auto",
  };

  return (
    <>
      <PageBackground />
      {isRequestSheetOpen ? (
        isFemaleProfile ? (
          <FemaleConsentSheet
            title={t["Final Consent"]}
            description={formatBoldText(
              t[
                "Approving this profile will **display your contact number** to the gentleman. Ensure **family consensus** before proceeding."
              ],
            )}
            buttons={({ close }) => (
              <div className="space-y-5">
                <button
                  type="button"
                  onClick={() => setIsFemaleConsentChecked((value) => !value)}
                  className="flex w-full items-start gap-4 rounded-[15px] border-2 border-white bg-white/50 px-5 py-5 text-left shadow-[0_8px_24px_rgba(0,0,0,0.05)]"
                >
                  <span
                    className={[
                      "mt-1 flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full border-1",
                      isFemaleConsentChecked
                        ? "border-[#F0445B] bg-[#F0445B]"
                        : "border-[#2B2B2B] bg-white",
                    ].join(" ")}
                    aria-hidden="true"
                  >
                    {isFemaleConsentChecked ? (
                      <span className="h-3 w-3 rounded-full bg-[#F0445B]" />
                    ) : null}
                  </span>
                  <span className="text-xs leading-[1.35] text-[#3F3F3F]">
                    {formatBoldText(
                      t[
                        "I confirm the family has **reviewed this profile** and **consents to communicate**."
                      ],
                    )}
                  </span>
                </button>

                <div className="grid w-full grid-cols-2 gap-3">
                  <Button
                    variant="outlined"
                    className="py-[18px] text-[18px]"
                    onClick={close}
                  >
                    {t.Cancel}
                  </Button>
                  <Button
                    className="py-[18px] text-[18px]"
                    disabled={
                      !caseId ||
                      isSubmitting ||
                      !isAcceptProfileEnabled ||
                      !isFemaleConsentChecked
                    }
                    onClick={async () => {
                      close();
                      if (!isAcceptProfileEnabled) {
                        return;
                      }

                      await respondMutation.mutateAsync({ action: "accept" });
                    }}
                  >
                    {t.Confirm}
                  </Button>
                </div>
              </div>
            )}
            onClose={() => {
              setIsFemaleConsentChecked(false);
              setIsRequestSheetOpen(false);
            }}
          />
        ) : (
          <InformationSheet
            icon="check"
            title={t["Request to Proceed"]}
            description={
              t[
                "Upon your approval, your request will be sent to the lady, and we must await her response. This process may take between 2 to 4 days. Thank you for your patience."
              ]
            }
            buttons={({ close }) => (
              <div className="grid w-full grid-cols-2 gap-3">
                <Button
                  variant="outlined"
                  className="py-[18px]"
                  onClick={close}
                >
                  {t.Cancel}
                </Button>
                <Button
                  className="py-[18px]"
                  disabled={
                    !isAcceptProfileEnabled || respondMutation.isPending
                  }
                  isLoading={respondMutation.isPending}
                  onClick={async () => {
                    close();
                    if (!isAcceptProfileEnabled) {
                      return;
                    }

                    await respondMutation.mutateAsync({ action: "accept" });
                  }}
                >
                  {t.Confirm}
                </Button>
              </div>
            )}
            onClose={() => setIsRequestSheetOpen(false)}
          />
        )
      ) : null}
      {isRejectSheetOpen ? (
        <InformationSheet
          icon="warning"
          title={t["Reject Profile"]}
          description={
            t[
              "Are you sure you've fully reviewed the profile and want to reject this profile?"
            ]
          }
          buttons={({ close }) => (
            <div className="grid w-full grid-cols-2 gap-3">
              <Button variant="outlined" className="py-[18px]" onClick={close}>
                {t.Cancel}
              </Button>
              <Button
                onClick={() => {
                  close();
                  setIsDismissReasonSheetOpen(true);
                }}
              >
                {t.Reject}
              </Button>
            </div>
          )}
          onClose={() => setIsRejectSheetOpen(false)}
        />
      ) : null}
      {isMaleRejectWarningOpen ? (
        <InformationSheet
          icon="warning"
          title={t["Rejection Warning"]}
          description={
            t[
              "Please review the person’s full profile once more before making your final decision."
            ]
          }
          buttons={({ close }) => (
            <div className="grid w-full grid-cols-2 gap-3">
              <Button variant="outlined" className="py-[18px]" onClick={close}>
                {t.Cancel}
              </Button>
              <Button
                className="py-[18px]"
                onClick={() => {
                  close();
                  setIsDismissReasonSheetOpen(true);
                }}
              >
                {t.Reject}
              </Button>
            </div>
          )}
          onClose={() => setIsMaleRejectWarningOpen(false)}
        />
      ) : null}
      {isDismissReasonSheetOpen ? (
        <DismissReasonSheet
          onClose={() => setIsDismissReasonSheetOpen(false)}
          onSubmit={async (reason) => {
            if (!caseId) {
              return;
            }

            await respondMutation.mutateAsync({
              action: "reject",
              custom_note: reason,
            });
          }}
        />
      ) : null}

      <main className={mainClass} style={mainStyle}>
        <StickyHeader>
          <div className="flex items-center justify-between gap-3">
            <NavigationButton
              variant="transparent"
              icon="close"
              iconLabel={t["Go back"]}
            />
            <h1
              className="min-w-0 flex-1 text-center font-semibold text-[14px] leading-[16px] text-white"
              style={{ fontFamily: "'Segoe UI', sans-serif" }}
            >
              {t["More detail"]}
            </h1>
            <div className="size-10 shrink-0" />
          </div>
        </StickyHeader>

        <section className="px-[17px] pb-32 pt-5">
          <div
            className="mx-auto flex flex-col items-center justify-center"
            style={{
              width: "343px",
              height: isCandidateFemale ? "124px" : "125px",
              gap: "10px",
            }}
          >
            {/* Frame 2095586585 - Avatar Section */}
            <div
              className="flex flex-col items-center justify-center w-full"
              style={{
                height: "125px",
                gap: "8px",
              }}
            >
              {/* Avatar Group */}
              <div className="relative overflow-hidden rounded-full w-[90px] h-[90px]">
                <Image
                  src={avatarSrc}
                  alt=""
                  width={90}
                  height={90}
                  className="w-full h-full object-cover"
                />
              </div>

              {/* Frame 2095586663 - Names Section */}
              <div
                className="flex flex-row items-center justify-center w-full animate-fade-in"
                style={{
                  height: "26px",
                }}
              >
                <span
                  className="font-bold text-[22px] leading-[26px] text-[#F0445B] text-center"
                  style={{
                    fontFamily: "'Segoe UI', sans-serif",
                    WebkitTextStroke: "2px rgba(255, 255, 255, 0.5)",
                    paintOrder: "stroke fill",
                  }}
                >
                  {candidateName}
                </span>
              </div>
            </div>
          </div>

          <MatchPublicProfileFields
            publicInfo={profile?.match_summary?.public_info}
            isCandidateFemale={true}
          />
        </section>

        <div
          style={{ paddingBottom: `var(--safe-bottom)` }}
          className="fixed inset-x-0 bottom-0 z-30 px-[17px]"
        >
          <div className="mx-auto w-full sm:max-w-[375px] rounded-t-[24px] bg-white px-4 py-4 shadow-[0_12px_30px_rgba(0,0,0,0.14)]">
            {caseStatus === "payment_done" ||
            caseStatus === "contacted" ||
            caseStatus === "finalized" ||
            profile?.status === "matched" ? (
              <button
                type="button"
                onClick={() => router.back()}
                className="w-full h-[52px] flex items-center justify-center rounded-[12px] bg-[#F5F5F5] text-[#36363C] font-semibold text-[16px] transition-transform active:scale-[0.98] cursor-pointer hover:bg-[#EBEBEB]"
              >
                {t.Back}
              </button>
            ) : (
              <div className="flex gap-3">
                <button
                  type="button"
                  disabled={!isRejectProfileEnabled || isSubmitting}
                  onClick={() => {
                    if (isFemaleProfile) {
                      setIsRejectSheetOpen(true);
                    } else {
                      setIsMaleRejectWarningOpen(true);
                    }
                  }}
                  className="inline-flex w-1/3 h-[52px] items-center justify-center rounded-[12px] border border-[#BFBFBF] bg-white px-4 text-[16px] font-semibold text-[#9A9A9A] disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {t.Reject}
                </button>
                <button
                  type="button"
                  disabled={!isAcceptProfileEnabled || isSubmitting}
                  onClick={() => {
                    if (!isAcceptProfileEnabled) {
                      return;
                    }

                    if (isFemaleProfile) {
                      setIsFemaleConsentChecked(false);
                    }

                    setIsRequestSheetOpen(true);
                  }}
                  className="inline-flex w-2/3 h-[52px] whitespace-nowrap items-center justify-center gap-1 rounded-[12px] bg-[#F0445B] px-4 text-[16px] font-semibold text-white shadow-[0_8px_16px_rgba(240,68,91,0.24)] disabled:cursor-not-allowed disabled:opacity-50"
                >
                  {isSubmitting ? (
                    <LoadingThreeDot />
                  ) : (
                    <>
                      <Image
                        src="/assets/images/Icfdason.svg"
                        alt=""
                        width={28}
                        height={28}
                      />
                      <span>{t["Accept Profile"]}</span>
                    </>
                  )}
                </button>
              </div>
            )}
          </div>
        </div>
      </main>
    </>
  );
}
