"use client";

import { useState } from "react";
import { Input } from "@nextui-org/react";
import {
  FaCalendarDays,
  FaArrowUpRightFromSquare,
  FaCheck,
} from "react-icons/fa6";

import Section from "@/components/pages/client/participant-list/common/section";
import Button from "@/components/common/button";
import { useClientPortalAuth } from "@/components/pages/client/participant-list/common/client-portal-auth-context";
import {
  FieldConfig,
  Participant,
} from "@/types/participant-list/provisional-types";
import { updateSessionLinkFromPortal } from "@/services/client/participant-list/portal-actions";
import { isFieldVisible } from "@/components/pages/client/participant-list/common/utils";

type SessionIncentiveProps = {
  participant: Participant;
  formattedDate: string;
  startTime: string;
  endTime: string;
  incentiveLabel: string;
  timezoneLabel: string;
  canEdit: boolean;
  visibilityControls: FieldConfig[];
};

function Field({
  label,
  value,
  mono = false,
}: {
  label: string;
  value: React.ReactNode;
  mono?: boolean;
}) {
  return (
    <div className="flex flex-col bg-gray-100 dark:bg-neutral-800 p-4 rounded-lg">
      <span className="text-[10px] font-semibold uppercase tracking-widest text-gray-400 dark:text-gray-300">
        {label}
      </span>

      <span
        className={`text-sm font-semibold text-gray-900 dark:text-white ${
          mono ? "font-mono" : ""
        }`}
      >
        {value}
      </span>
    </div>
  );
}

function JoinSessionButton({ link }: { link: string }) {
  return (
    <Button
      btnLabel="Join session"
      customVariant="client"
      href={link}
      rel="noopener noreferrer"
      size="sm"
      startContent={<FaArrowUpRightFromSquare className="size-3" />}
      target="_blank"
    />
  );
}

function SessionIncentive({
  participant,
  formattedDate,
  startTime,
  endTime,
  incentiveLabel,
  timezoneLabel,
  canEdit,
  visibilityControls,
}: SessionIncentiveProps) {
  const { auth, handlePortalStatus } = useClientPortalAuth();
  const { session } = participant;
  const { location } = session;

  const [savedLink, setSavedLink] = useState(session.link ?? "");
  const [draftLink, setDraftLink] = useState(session.link ?? "");
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [justSaved, setJustSaved] = useState(false);

  const hasChanges = draftLink.trim() !== savedLink.trim();

  const handleSave = async () => {
    if (!auth || !canEdit) return;
    setIsSaving(true);
    setError(null);
    setJustSaved(false);

    try {
      const result = await updateSessionLinkFromPortal(
        auth,
        participant.reference,
        draftLink.trim(),
      );

      if (result.ok) {
        setSavedLink(draftLink.trim());
        setJustSaved(true);
      } else if (!handlePortalStatus(result.status)) {
        setError(
          "Something went wrong saving the session link. Please try again.",
        );
      }
    } catch {
      setError(
        "Something went wrong saving the session link. Please try again.",
      );
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <Section
      icon={<FaCalendarDays className="size-3" />}
      label="Session & incentives"
    >
      <div className="grid grid-cols-2 md:grid-cols-4 gap-1 py-2">
        <Field label="Date" value={formattedDate} />
        <Field
          label="Time"
          value={`${startTime} - ${endTime} (${timezoneLabel})`}
        />
        {location && isFieldVisible("location", visibilityControls) && (
          <Field label="Location" value={location} />
        )}
        <Field label="Incentive" value={incentiveLabel} />
      </div>

      {isFieldVisible("sessionLink", visibilityControls) && (
        <div className="mt-3 border-t border-gray-200 dark:border-neutral-700 pt-3">
          {!canEdit ? (
            savedLink ? (
              <div className="flex items-center justify-between">
                <p className="text-sm text-gray-500 dark:text-neutral-400">
                  Session link available
                </p>
                <JoinSessionButton link={savedLink} />
              </div>
            ) : (
              <p className="text-sm text-gray-500 dark:text-neutral-400">
                No session link has been added yet.
              </p>
            )
          ) : (
            <div className="space-y-2">
              <p className="text-xs text-gray-500 dark:text-neutral-400">
                Session link
              </p>
              <div className="flex items-end gap-2">
                <Input
                  className="flex-1"
                  isDisabled={isSaving}
                  placeholder="https://..."
                  value={draftLink}
                  onChange={(e) => {
                    setDraftLink(e.target.value);
                    setJustSaved(false);
                  }}
                />
                <Button
                  btnLabel="Save"
                  customVariant="client"
                  isDisabled={!hasChanges || isSaving}
                  isLoading={isSaving}
                  size="md"
                  onClick={handleSave}
                />
                {savedLink && <JoinSessionButton link={savedLink} />}
              </div>
              {justSaved && !error && (
                <p className="flex items-center gap-1.5 text-xs text-emerald-600 dark:text-emerald-400">
                  <FaCheck className="size-2.5" />
                  Session link saved.
                </p>
              )}
              {error && (
                <p className="text-xs text-red-600 dark:text-red-400">
                  {error}
                </p>
              )}
            </div>
          )}
        </div>
      )}
    </Section>
  );
}

export default SessionIncentive;
