"use client";

import Image from "next/image";
import { Card, CardBody, CardHeader } from "@nextui-org/react";
import { FaLinkedin, FaUsers } from "react-icons/fa6";
import { FaEnvelope } from "react-icons/fa";
import Link from "next/link";
import { useState } from "react";
import {
  useParams,
  usePathname,
  useRouter,
  useSearchParams,
} from "next/navigation";

import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import PFRDefaultLogo from "@/components/common/sprites/pfr-default-logo-sprite";
import { Opportunity } from "@/types/opportunities/opportunity-types";
import { formatIncentives } from "@/utils/format-incentive";
import { Options } from "@/types/options/options-data-types";
import Button from "@/components/common/button";

type ExpiredOppScreenProps = {
  currencyOptions: Options;
  listOfOpps: Opportunity[];
};

function ExpiredOppCampaignScreen({
  currencyOptions,
  listOfOpps,
}: ExpiredOppScreenProps) {
  const router = useRouter();
  const pathname = usePathname();
  const { slug } = useParams();
  const searchParams = useSearchParams();
  const queryString = searchParams.toString();
  const BASE_URL = process.env.NEXT_PUBLIC_PFR_WEBSITE_BASE_URL_CAMPAIGNS_ONLY;
  const [loadingButton, setLoadingButton] = useState<string | null>(null);

  const handleContinue = (selection: string) => {
    setLoadingButton(selection);

    if (selection === "linkedin") {
      handleLinkedInAuth();
    } else {
      router.push(
        `${INTERNAL_PAGES.participant.campaign}/${slug}/signup?${queryString}`,
      );
    }
  };

  const handleLinkedInAuth = () => {
    const state = encodeURIComponent(
      JSON.stringify({
        returnTo: pathname,
      }),
    );
    const linkedinAuthUrl = `https://www.linkedin.com/oauth/v2/authorization?${new URLSearchParams(
      {
        response_type: "code",
        client_id: process.env.NEXT_PUBLIC_LINKEDIN_CLIENT_ID!,
        redirect_uri: `${BASE_URL}${INTERNAL_PAGES.participant.linkedInCallback}`,
        scope: "openid profile email",
        state,
      },
    )}`;
    window.location.href = linkedinAuthUrl;
    // this doesn't need a dispatch; it's handled in the callback from linkedin
  };

  const hrefCoookies = `${BASE_URL}${INTERNAL_PAGES.participant.howItWorks.policies}/cookies-policy`;
  const hrefTerms = `${BASE_URL}${INTERNAL_PAGES.participant.howItWorks.policies}/general-terms-and-contact-details`;

  return (
    <div className="flex items-center justify-center p-0 sm:p-4 m-auto sm:min-h-screen sm:my-8 lg:my-16 relative">
      <div className="w-full max-w-4xl mx-0 sm:mx-4 lg:mx-16 relative">
        <div className="hidden sm:block sm:absolute -top-6 lg:-top-10 left-1/2 -translate-x-1/2 z-30 bg-participant-dark rounded-full p-3 sm:p-4 ring-4 ring-participant-cerulean/20 ring-offset-2">
          <FaUsers className="w-6 h-6 sm:w-8 sm:h-8 lg:w-10 lg:h-10 text-white" />
        </div>
        <Card className="shadow border-0 p-4 sm:p-6 md:p-8 lg:p-10 rounded-none sm:rounded-3xl  text-gray-900 dark:text-gray-100">
          <CardHeader className="text-center flex flex-col pt-6 sm:pt-8">
            <div>
              <div className="flex items-center justify-center sm:hidden">
                <PFRDefaultLogo fill="text-black" width={100} />
              </div>
              <h1 className="text-2xl lg:text-4xl font-black mb-3 font-inter">
                This opportunity has closed.
              </h1>
              <p className="text-sm lg:text-base px-2 sm:px-0">
                View a sneak peek of current opportunities below. Create an
                account to access the full catalog of research studies.
              </p>
            </div>
          </CardHeader>

          <CardBody className="space-y-4 mb-6 sm:mb-8 px-2 sm:px-6">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-1.5">
              {listOfOpps.map((opportunity, index) => {
                const { title, thumbnail, incentives } = opportunity;

                return (
                  <Card
                    key={index}
                    isPressable
                    className="shadow-sm hover:shadow-md transition-shadow rounded light overflow-hidden"
                  >
                    <CardBody className="p-0 relative">
                      <div className="relative h-[250px] w-full">
                        <Image
                          alt={`Image for ${title}`}
                          className="object-cover w-full h-full"
                          height={250}
                          src={
                            thumbnail
                              ? `data:image/png;base64,${thumbnail}`
                              : "/images/default-thumbnail.png"
                          }
                          width={250}
                        />

                        <div className="absolute top-3 right-3 z-20 bg-white/70 backdrop-blur-sm rounded-full px-3 py-1.5">
                          <span className="font-inter font-extrabold text-base sm:text-lg">
                            {formatIncentives(incentives, currencyOptions)}
                          </span>
                          {incentives.length > 1 && (
                            <span className="text-xs text-gray-600 ml-1">
                              +{incentives.length - 1}
                            </span>
                          )}
                        </div>

                        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent z-10 pt-8 pb-3 px-3">
                          <p className="font-semibold text-sm text-white line-clamp-2 drop-shadow-md">
                            {title}
                          </p>
                        </div>
                      </div>
                    </CardBody>
                  </Card>
                );
              })}
            </div>

            <div className="flex flex-col justify-center text-black dark:text-white overflow-visible p-3">
              <Button
                customVariant="linkedin"
                isDisabled={loadingButton !== null}
                size="lg"
                startContent={
                  loadingButton !== "linkedin" && (
                    <FaLinkedin className="w-4 h-4 sm:w-5 sm:h-5" />
                  )
                }
                onClick={() => handleContinue("linkedin")}
              >
                <span className="text-sm sm:text-base">
                  {loadingButton === "linkedin"
                    ? "Redirecting..."
                    : "Continue with LinkedIn"}
                </span>
              </Button>

              <div className="relative my-4">
                <div className="absolute inset-0 flex items-center">
                  <div className="w-full border-t border-gray-300 dark:border-gray-700"></div>
                </div>
                <div className="relative flex justify-center text-sm">
                  <span className="bg-white dark:bg-zinc-900 px-3 text-gray-500 dark:text-gray-400">
                    or
                  </span>
                </div>
              </div>

              <Button
                customVariant="primary"
                isDisabled={loadingButton !== null}
                isLoading={loadingButton === "email"}
                size="lg"
                startContent={
                  loadingButton !== "email" && (
                    <FaEnvelope className="w-4 h-4 sm:w-5 sm:h-5" />
                  )
                }
                onClick={() => handleContinue("email")}
              >
                <span className="text-sm sm:text-base">
                  {loadingButton === "email"
                    ? "Redirecting..."
                    : "Continue with email"}
                </span>
              </Button>

              <p className="text-xs text-gray-600 dark:text-gray-400 text-center leading-relaxed mt-8">
                By signing up, you agree to People for Research&apos;s{" "}
                <Link
                  className="text-black dark:text-blue-400 underline underline-offset-2 decoration-dotted cursor-pointer font-semibold"
                  href={hrefCoookies}
                  rel="noopener noreferrer"
                  target="_blank"
                >
                  Cookies Policy
                </Link>{" "}
                and{" "}
                <Link
                  className="text-black dark:text-blue-400 underline underline-offset-2 decoration-dotted cursor-pointer font-semibold"
                  href={hrefTerms}
                  rel="noopener noreferrer"
                  target="_blank"
                >
                  General Terms and Conditions
                </Link>{" "}
                .
              </p>
            </div>
          </CardBody>
        </Card>
      </div>
    </div>
  );
}

export default ExpiredOppCampaignScreen;
