/**
 * Token Validator Component
 * Validates interview booking token and displays job/applicant info
 */

"use client";

import { useState, useEffect } from "react";
import { UI, type Lang } from "@/lib/config";

interface TokenData {
  valid: boolean;
  applicationId?: string;
  jobId?: string;
  jobTitle?: string;
  jobTitleAr?: string;
  jobDepartment?: string;
  jobLocation?: string;
  applicantName?: string;
  applicantEmail?: string;
  expiresAt?: string;
  error?: "expired" | "used" | "invalid" | "revoked";
}

interface TokenValidatorProps {
  token: string;
  language: Lang;
  onValidated: (data: TokenData) => void;
}

export default function TokenValidator({
  token,
  language,
  onValidated,
}: TokenValidatorProps) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [tokenData, setTokenData] = useState<TokenData | null>(null);

  const t = UI[language].t;
  const dir = UI[language].dir;

  useEffect(() => {
    async function validateToken() {
      setLoading(true);
      setError(null);

      try {
        const response = await fetch(
          `/api/careers/interview/validate-token?token=${encodeURIComponent(token)}`,
          {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
          },
        );

        const data = await response.json();

        if (!response.ok) {
          // Handle specific error types
          if (data.error === "expired") {
            setError(t.tokenExpiredMessage);
            setTokenData({ valid: false, error: "expired" });
          } else if (data.error === "used") {
            setError(t.tokenUsedMessage);
            setTokenData({ valid: false, error: "used" });
          } else if (data.error === "revoked") {
            setError(t.tokenRevokedMessage);
            setTokenData({ valid: false, error: "revoked" });
          } else {
            setError(t.tokenInvalidMessage);
            setTokenData({ valid: false, error: "invalid" });
          }
          onValidated({ valid: false, error: data.error });
          return;
        }

        // Token is valid
        const validData: TokenData = {
          valid: true,
          applicationId: data.applicationId,
          jobId: data.jobId,
          jobTitle: data.jobTitle,
          jobTitleAr: data.jobTitleAr,
          jobDepartment: data.jobDepartment,
          jobLocation: data.jobLocation,
          applicantName: data.applicantName,
          applicantEmail: data.applicantEmail,
          expiresAt: data.expiresAt,
        };

        setTokenData(validData);
        onValidated(validData);
      } catch (err) {
        console.error("Token validation error:", err);
        setError(t.tokenInvalidMessage);
        setTokenData({ valid: false, error: "invalid" });
        onValidated({ valid: false, error: "invalid" });
      } finally {
        setLoading(false);
      }
    }

    if (token) {
      validateToken();
    }
  }, [token, language]); // Exclude t and onValidated to prevent infinite loop

  // Loading state
  if (loading) {
    return (
      <div
        className="max-w-2xl mx-auto bg-white dark:bg-brand-ink rounded-2xl shadow-lg p-8"
        dir={dir}
      >
        <div className="flex flex-col items-center justify-center space-y-4">
          <div className="w-12 h-12 border-4 border-brand-green/30 border-t-brand-green rounded-full animate-spin" />
          <p className="text-brand-ink/70 dark:text-white/70 text-lg">
            {t.tokenValidating}
          </p>
        </div>
      </div>
    );
  }

  // Error state
  if (error || !tokenData?.valid) {
    const errorTitle =
      tokenData?.error === "expired"
        ? t.tokenExpired
        : tokenData?.error === "used"
          ? t.tokenUsed
          : tokenData?.error === "revoked"
            ? t.tokenRevoked
            : t.tokenInvalid;

    return (
      <div
        className="max-w-2xl mx-auto bg-white dark:bg-brand-ink rounded-2xl shadow-lg p-8"
        dir={dir}
      >
        <div className="flex flex-col items-center space-y-6 text-center">
          {/* Error Icon */}
          <div className="w-16 h-16 rounded-full bg-red-50 dark:bg-red-900/20 flex items-center justify-center">
            <svg
              className="w-8 h-8 text-red-600 dark:text-red-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
              />
            </svg>
          </div>

          {/* Error Title */}
          <h2 className="text-2xl font-bold text-brand-ink dark:text-white">
            {errorTitle}
          </h2>

          {/* Error Message */}
          <p className="text-brand-ink/70 dark:text-white/70 text-lg leading-relaxed">
            {error}
          </p>

          {/* Contact Button */}
          <a
            href={`mailto:careers@mawidi.app?subject=${encodeURIComponent(
              language === "ar"
                ? "مساعدة في جدولة المقابلة"
                : "Interview Scheduling Help",
            )}`}
            className="
              px-6
              py-3
              rounded-lg
              bg-brand-green
              text-white
              font-semibold
              hover:bg-brand-green/90
              transition-colors
              focus:outline-none
              focus:ring-4
              focus:ring-brand-green/20
            "
          >
            {language === "ar" ? "تواصل معنا" : "Contact Us"}
          </a>
        </div>
      </div>
    );
  }

  // Valid state - show job and applicant info
  return (
    <div
      className="max-w-2xl mx-auto bg-white dark:bg-brand-ink rounded-2xl shadow-lg p-8 mb-8"
      dir={dir}
    >
      <div className="space-y-6">
        {/* Success Icon */}
        <div className="flex items-center gap-4">
          <div className="w-12 h-12 rounded-full bg-brand-green/10 flex items-center justify-center flex-shrink-0">
            <svg
              className="w-6 h-6 text-brand-green"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <div>
            <h2 className="text-2xl font-bold text-brand-ink dark:text-white">
              {t.interviewScheduleTitle}
            </h2>
            <p className="text-brand-ink/60 dark:text-white/60">
              {t.interviewScheduleSubtitle}
            </p>
          </div>
        </div>

        {/* Job Details */}
        <div className="border-t border-brand-ink/10 dark:border-white/10 pt-6 space-y-4">
          <div>
            <label className="text-sm font-medium text-brand-ink/60 dark:text-white/60 block mb-1">
              {t.interviewScheduleJobLabel}
            </label>
            <p className="text-lg font-semibold text-brand-ink dark:text-white">
              {language === "ar" && tokenData.jobTitleAr
                ? tokenData.jobTitleAr
                : tokenData.jobTitle}
            </p>
            {tokenData.jobDepartment && (
              <p className="text-sm text-brand-ink/60 dark:text-white/60">
                {tokenData.jobDepartment}
                {tokenData.jobLocation && ` • ${tokenData.jobLocation}`}
              </p>
            )}
          </div>

          <div>
            <label className="text-sm font-medium text-brand-ink/60 dark:text-white/60 block mb-1">
              {t.interviewScheduleApplicantLabel}
            </label>
            <p className="text-lg font-semibold text-brand-ink dark:text-white">
              {tokenData.applicantName}
            </p>
            <p className="text-sm text-brand-ink/60 dark:text-white/60">
              {tokenData.applicantEmail}
            </p>
          </div>
        </div>

        {/* Expiry Notice */}
        {tokenData.expiresAt && (
          <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-700 rounded-lg p-4">
            <div className="flex items-start gap-3">
              <svg
                className="w-5 h-5 text-yellow-600 dark:text-yellow-400 mt-0.5 flex-shrink-0"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
              <p className="text-sm text-yellow-800 dark:text-yellow-200">
                {language === "ar" ? (
                  <>
                    ينتهي هذا الرابط في{" "}
                    <span className="font-semibold">
                      {new Date(tokenData.expiresAt).toLocaleDateString(
                        "ar-SA",
                        {
                          month: "long",
                          day: "numeric",
                          hour: "numeric",
                          minute: "numeric",
                        },
                      )}
                    </span>
                  </>
                ) : (
                  <>
                    This link expires on{" "}
                    <span className="font-semibold">
                      {new Date(tokenData.expiresAt).toLocaleDateString(
                        "en-US",
                        {
                          month: "long",
                          day: "numeric",
                          hour: "numeric",
                          minute: "numeric",
                        },
                      )}
                    </span>
                  </>
                )}
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
