import BlueBackground from "@/components/cards/blueBack";
import CountryGrid from "@/components/countries/countryGrid";
import CountryHero from "@/components/countries/countryHero";
import InfoCard from "@/components/countries/infoCard";
import VideoGuide from "@/components/countries/videoGuide";
import { Breadcrumb } from "antd";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useMemo, useState } from "react";
import { getFirebaseText } from "@/lib/firebase";
import MainHero from "@/components/mainHero";
import ServicesGrid from "@/components/cards/landingCards";
import Image from "next/image";
import Head from "next/head";
import type { GetServerSideProps } from "next";
import { codeFromSlug, countrySlug } from "@/lib/countrySlug";

type GuideMapOut = {
  agent: string;
  attentionEn: string;
  attentionMn: string;
  commission: string;
  countryName: string;
  depoType: string;
  description: string | null;
  descriptionEn: string | null;
  durationEn: string;
  durationMn: string;
  oneTimeLimit: string;
};

type Country = {
  desc_en: string;
  desc_mn: string;
  name_en: string;
  name_mn: string;
  title_en: string;
  title_mn: string;
};

type HeroCopy = {
  easyRemit: string;
  easyRemitd: string;
  more: string;
  threeDesc: string;
  threeo: string;
};

type CountriesRemitProps = {
  code: string;
  countries: Country;
  textData: HeroCopy | null;
  rows: GuideMapOut[];
};

export default function CountriesRemit({
  code,
  countries,
  textData,
  rows,
}: CountriesRemitProps) {
  const router = useRouter();
  const lang = router.locale || "en";
  const isEn = lang.toLowerCase().startsWith("en");

  // Filters
  const [selectedDepo, setSelectedDepo] = useState<string>("");
  const [selectedAgent, setSelectedAgent] = useState<string>("");

  const uniqJoin = (vals: Array<string | null | undefined>, sep = ", ") => {
    const v = Array.from(new Set(vals.filter(Boolean) as string[]));
    return v.join(sep);
  };

  const depoTypes = useMemo(
    () =>
      Array.from(
        new Set((rows ?? []).map((r) => r.depoType).filter(Boolean) as string[])
      ),
    [rows]
  );

  useEffect(() => {
    if (!depoTypes.length) return;
    setSelectedDepo((prev) => (depoTypes.includes(prev) ? prev : depoTypes[0]));
  }, [depoTypes]);

  const agentOptions = useMemo(() => {
    const base = (rows ?? []).filter(
      (r) => !selectedDepo || r.depoType === selectedDepo
    );
    return Array.from(
      new Set(base.map((r) => r.agent).filter(Boolean) as string[])
    );
  }, [rows, selectedDepo]);

  useEffect(() => {
    if (!agentOptions.length) {
      setSelectedAgent("");
      return;
    }
    setSelectedAgent((prev) =>
      agentOptions.includes(prev) ? prev : agentOptions[0]
    );
  }, [agentOptions]);

  const filteredRows = useMemo(() => {
    let list = rows ?? [];
    if (selectedDepo) list = list.filter((r) => r.depoType === selectedDepo);
    if (selectedAgent) list = list.filter((r) => r.agent === selectedAgent);
    return list;
  }, [rows, selectedDepo, selectedAgent]);

  const agent = useMemo(
    () => uniqJoin(filteredRows.map((r) => r.agent)),
    [filteredRows]
  );
  const depoType = useMemo(
    () => uniqJoin(filteredRows.map((r) => r.depoType)),
    [filteredRows]
  );
  const oneTimeLimit = useMemo(
    () =>
      uniqJoin(
        filteredRows.map((r) => r.oneTimeLimit),
        " / "
      ),
    [filteredRows]
  );
  const commission = useMemo(
    () =>
      uniqJoin(
        filteredRows.map((r) => r.commission),
        " / "
      ),
    [filteredRows]
  );
  const duration = useMemo(
    () =>
      uniqJoin(
        filteredRows.map((r) => (isEn ? r.durationEn : r.durationMn)),
        " / "
      ),
    [filteredRows, isEn]
  );
  const attention = useMemo(
    () =>
      uniqJoin(
        filteredRows.map((r) => (isEn ? r.attentionEn : r.attentionMn)),
        " • "
      ),
    [filteredRows, isEn]
  );

  return (
    <div className="relative min-h-screen overflow-x-hidden">
      <Head>
        <title>
          {lang == "en"
            ? `Send Money from Mongolia to ${countries?.title_en} | SendMN`
            : `${countries?.title_mn} руу мөнгө илгээх | SendMN`}
        </title>
        <meta
          name="description"
          content={
            lang == "en"
              ? `Transfer money from Mongolia to ${countries?.title_en} with SendMN — low fees, great exchange rates, and fast delivery.`
              : `${countries?.title_mn} улсад амьдарч буй гэр бүл, найз нөхөд рүүгээ SendMN аппаар өрсөлдөхүйц ханш бага шимтгэлээр, түргэн, найдвартай гадаад шилжүүлэг илгээгээрэй.`
          }
        />
      </Head>
      <BlueBackground>
        <div className="bg-cyan pl-6 md:pl-32 pt-10 bg-skywhite">
          <Breadcrumb
            separator="›"
            className="text-[14px]"
            items={[
              {
                title: (
                  <Link href="/" className="hover:underline">
                    <span className="text-[#051973] font-sans">
                      {isEn ? "Home" : "Нүүр хуудас"}
                    </span>
                  </Link>
                ),
              },
              {
                title: (
                  <span className="text-main font-sans">
                    {isEn ? countries?.title_en : countries?.title_mn}
                  </span>
                ),
              },
            ]}
          />
        </div>

        <CountryHero countries={countries} isEn={lang} code={code} />

        <div className="mt-16">
          <div className="max-w-6xl mx-auto px-4 py-10 space-y-6">
            {(depoTypes.length > 0 || agentOptions.length > 0) && (
              <div className="flex flex-wrap items-center gap-6">
                {depoTypes.length > 1 && (
                  <div className="flex flex-col">
                    <label
                      htmlFor="depoType"
                      className="mb-1 text-xs font-medium text-main"
                    >
                      {isEn ? "Send type:" : "Илгээх хэлбэр:"}
                    </label>

                    <div className="relative w-full">
                      <select
                        id="depoType"
                        value={selectedDepo}
                        onChange={(e) => setSelectedDepo(e.target.value)}
                        className="h-11 w-full rounded-xl border border-border bg-slate-50 px-4 pr-10 text-sm text-slate-800 shadow-sm outline-none transition-all duration-200 appearance-none focus:border-sky-300 focus:ring-2 focus:ring-sky-200 hover:bg-white disabled:opacity-60 disabled:cursor-not-allowed"
                      >
                        {depoTypes.map((t) => (
                          <option key={t} value={t}>
                            {t}
                          </option>
                        ))}
                      </select>
                      <span className="pointer-events-none absolute inset-y-0 right-3 flex items-center text-slate-400">
                        <Image
                          src="/images/chevron-down.svg"
                          alt="Select"
                          width={14}
                          height={14}
                        />
                      </span>
                    </div>
                  </div>
                )}

                {agentOptions.length > 1 && (
                  <div className="flex flex-col">
                    <label
                      htmlFor="agent"
                      className="mb-1 text-xs font-medium text-main"
                    >
                      {isEn ? "Agent:" : "Агент:"}
                    </label>

                    <div className="relative w-full">
                      <select
                        id="agent"
                        value={selectedAgent}
                        onChange={(e) => setSelectedAgent(e.target.value)}
                        className="h-11 w-full rounded-xl border border-border bg-slate-50 px-4 pr-10 text-sm text-slate-800 shadow-sm outline-none transition-all duration-200 appearance-none focus:border-sky-300 focus:ring-2 focus:ring-sky-200 hover:bg-white disabled:opacity-60 disabled:cursor-not-allowed"
                      >
                        {agentOptions.map((a) => (
                          <option key={a} value={a}>
                            {a}
                          </option>
                        ))}
                      </select>
                      <span className="pointer-events-none absolute inset-y-0 right-3 flex items-center text-slate-400">
                        <Image
                          src="/images/chevron-down.svg"
                          alt="Select"
                          width={14}
                          height={14}
                        />
                      </span>
                    </div>
                  </div>
                )}
              </div>
            )}

            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
              <InfoCard
                label={isEn ? "Send type:" : "Илгээх хэлбэр:"}
                value={depoType || "-"}
              />
              <InfoCard label={isEn ? "Agent:" : "Агент:"} value={agent || "-"} />
              <InfoCard
                label={isEn ? "One-time limit:" : "Нэг удаагийн лимит:"}
                value={oneTimeLimit || "-"}
              />
              <InfoCard
                label={isEn ? "Commission:" : "Шимтгэл:"}
                value={commission || "-"}
              />
            </div>

            <div>
              <h2 className="font-semibold text-[#051973]">
                {isEn ? "Attention:" : "Анхаарах:"}
              </h2>
              <p className="text-sm text-gray-600 mt-2 max-w-3xl">
                {attention || "-"}
              </p>
              <h2 className="font-semibold text-[#051973] mt-6">
                {isEn ? "Duration:" : "Хугацаа:"}
              </h2>
              <p className="text-sm text-gray-600 mt-2 max-w-3xl">
                {duration || "-"}
              </p>
            </div>
          </div>
        </div>
        <VideoGuide />
        <CountryGrid />
        <MainHero
          title="SendMN Application"
          description={textData?.threeDesc ?? ""}
          text={textData?.threeo ?? ""}
          variant="primary"
          headingLevel="h2"
        >
          <div>
            <ServicesGrid />
          </div>
        </MainHero>
      </BlueBackground>
    </div>
  );
}

export const getServerSideProps: GetServerSideProps<
  CountriesRemitProps
> = async (ctx) => {
  const rawSlug = String(ctx.params?.slug ?? "");
  const code = codeFromSlug(rawSlug);

  if (!code) {
    return { notFound: true };
  }

  // Redirect legacy /countries/{code} links (and any non-canonical
  // casing) to the SEO-friendly /countries/send-money-to-{country} URL.
  const canonicalSlug = countrySlug(code);
  if (canonicalSlug && rawSlug.toLowerCase() !== canonicalSlug) {
    const localePrefix =
      ctx.locale && ctx.locale !== ctx.defaultLocale ? `/${ctx.locale}` : "";
    return {
      redirect: {
        destination: `${localePrefix}/countries/${canonicalSlug}`,
        permanent: true,
      },
    };
  }

  const lang = ctx.locale ?? "en";

  const [countries, textData, guideRes] = await Promise.all([
    getFirebaseText(`countries/${code}`) as Promise<Country | null>,
    getFirebaseText(`Hero Page/${lang}`) as Promise<HeroCopy | null>,
    fetch(`https://webback.send.mn/country/guideMapOut/${encodeURIComponent(code)}`, {
      cache: "no-store",
    })
      .then((r) => (r.ok ? (r.json() as Promise<GuideMapOut[]>) : []))
      .catch(() => [] as GuideMapOut[]),
  ]);

  if (!countries) {
    return { notFound: true };
  }

  return {
    props: {
      code,
      countries,
      textData,
      rows: guideRes,
    },
  };
};
