/**
 * Interview Schedule Client Component
 * Client-side wrapper for the interview scheduler with token validation
 */

"use client";

import { useEffect, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { UI, type Lang } from "@/lib/config";
import TokenValidator from "./components/TokenValidator";
import InterviewScheduler from "./components/InterviewScheduler";

interface InterviewScheduleClientProps {
  lang: Lang;
}

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 BookingData {
  preferredDate: string;
  preferredTime: string;
  timezone: string;
  additionalNotes?: string;
}

export default function InterviewScheduleClient({
  lang,
}: InterviewScheduleClientProps) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const t = UI[lang].t;
  const dir = UI[lang].dir;

  const [token, setToken] = useState<string | null>(null);
  const [tokenData, setTokenData] = useState<TokenData | null>(null);
  const [showSuccess, setShowSuccess] = useState(false);
  const [bookingData, setBookingData] = useState<BookingData | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const tokenParam = searchParams.get("token");
    if (!tokenParam) {
      setError(t.tokenInvalidMessage);
    } else {
      setToken(tokenParam);
    }
  }, [searchParams, t.tokenInvalidMessage]);

  const handleTokenValidated = (data: TokenData) => {
    setTokenData(data);
  };

  const handleBookingSuccess = (data: BookingData) => {
    setBookingData(data);
    setShowSuccess(true);

    // Optionally redirect to home after 5 seconds
    setTimeout(() => {
      router.push(`/${lang}`);
    }, 5000);
  };

  const handleBookingError = (errorMessage: string) => {
    setError(errorMessage);
  };

  // No token provided
  if (!token) {
    return (
      <main
        className="min-h-screen bg-gradient-to-b from-white to-brand-sand/20 dark:from-brand-ink dark:to-brand-ink/95"
        dir={dir}
      >
        <div className="container mx-auto px-4 py-24">
          <div className="max-w-2xl mx-auto bg-white dark:bg-brand-ink rounded-2xl shadow-lg p-8">
            <div className="flex flex-col items-center space-y-6 text-center">
              <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>
              <h2 className="text-2xl font-bold text-brand-ink dark:text-white">
                {t.tokenInvalid}
              </h2>
              <p className="text-brand-ink/70 dark:text-white/70 text-lg leading-relaxed">
                {error || t.tokenInvalidMessage}
              </p>
              <a
                href={`/${lang}/careers`}
                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
                "
              >
                {t.interviewScheduledBackButton}
              </a>
            </div>
          </div>
        </div>
      </main>
    );
  }

  // Success state
  if (showSuccess && bookingData) {
    return (
      <main
        className="min-h-screen bg-gradient-to-b from-white to-brand-sand/20 dark:from-brand-ink dark:to-brand-ink/95"
        dir={dir}
      >
        <div className="container mx-auto px-4 py-24">
          <div className="max-w-2xl mx-auto bg-white dark:bg-brand-ink rounded-2xl shadow-lg p-8">
            <div className="flex flex-col items-center space-y-6 text-center">
              {/* Success Icon */}
              <div className="w-20 h-20 rounded-full bg-brand-green/10 flex items-center justify-center">
                <svg
                  className="w-10 h-10 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>

              {/* Success Title */}
              <h2 className="text-3xl font-bold text-brand-ink dark:text-white">
                {t.interviewScheduledTitle}
              </h2>

              {/* Success Message */}
              <p className="text-brand-ink/70 dark:text-white/70 text-lg leading-relaxed">
                {t.interviewScheduledMessage}
              </p>

              {/* Booking Details */}
              <div className="w-full bg-brand-green/5 border-2 border-brand-green/20 rounded-xl p-6 text-left">
                <h3 className="font-semibold text-brand-ink dark:text-white mb-4">
                  {t.interviewScheduledDetails}
                </h3>
                <div className="space-y-3">
                  <div className="flex items-start gap-3">
                    <svg
                      className="w-5 h-5 text-brand-green mt-0.5 flex-shrink-0"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                      />
                    </svg>
                    <div>
                      <p className="text-sm text-brand-ink/60 dark:text-white/60">
                        {t.interviewScheduleJobLabel}
                      </p>
                      <p className="font-semibold text-brand-ink dark:text-white">
                        {lang === "ar" && tokenData?.jobTitleAr
                          ? tokenData.jobTitleAr
                          : tokenData?.jobTitle}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3">
                    <svg
                      className="w-5 h-5 text-brand-green mt-0.5 flex-shrink-0"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
                      />
                    </svg>
                    <div>
                      <p className="text-sm text-brand-ink/60 dark:text-white/60">
                        {t.interviewScheduledDateLabel}
                      </p>
                      <p className="font-semibold text-brand-ink dark:text-white">
                        {new Date(bookingData.preferredDate).toLocaleDateString(
                          lang === "ar" ? "ar-SA" : "en-US",
                          {
                            weekday: "long",
                            year: "numeric",
                            month: "long",
                            day: "numeric",
                          },
                        )}
                      </p>
                    </div>
                  </div>

                  <div className="flex items-start gap-3">
                    <svg
                      className="w-5 h-5 text-brand-green 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>
                    <div>
                      <p className="text-sm text-brand-ink/60 dark:text-white/60">
                        {t.interviewScheduledTimeLabel}
                      </p>
                      <p className="font-semibold text-brand-ink dark:text-white">
                        {bookingData.preferredTime} ({bookingData.timezone})
                      </p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Action Button */}
              <div className="flex flex-col sm:flex-row gap-4 w-full">
                <a
                  href={`/${lang}`}
                  className="
                    flex-1
                    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
                    text-center
                  "
                >
                  {t.interviewScheduledBackButton}
                </a>
              </div>

              {/* Auto-redirect notice */}
              <p className="text-sm text-brand-ink/50 dark:text-white/50">
                {lang === "ar"
                  ? "سيتم توجيهك تلقائيًا خلال 5 ثوانٍ..."
                  : "You will be redirected automatically in 5 seconds..."}
              </p>
            </div>
          </div>
        </div>
      </main>
    );
  }

  // Main scheduling interface
  return (
    <main
      className="min-h-screen bg-gradient-to-b from-white to-brand-sand/20 dark:from-brand-ink dark:to-brand-ink/95"
      dir={dir}
    >
      {/* Hero Section */}
      <section className="container mx-auto px-4 pt-24 pb-12">
        <div className="max-w-3xl mx-auto text-center">
          {/* Badge */}
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-brand-green/10 text-brand-green text-sm font-medium mb-6">
            <svg
              className="w-4 h-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
              />
            </svg>
            {lang === "ar" ? "جدولة المقابلة" : "Interview Scheduling"}
          </div>

          {/* Heading */}
          <h1 className="text-4xl md:text-5xl font-bold text-brand-ink dark:text-white mb-6">
            {lang === "ar" ? "نحن متحمسون للقائك" : "We're Excited to Meet You"}
          </h1>

          {/* Description */}
          <p className="text-lg md:text-xl text-brand-ink/70 dark:text-white/70 mb-4 leading-relaxed">
            {lang === "ar"
              ? "اختر الوقت المناسب لك لإجراء المقابلة. نتطلع للتعرف عليك أكثر ومناقشة كيف يمكنك المساهمة في فريق ماويدي."
              : "Choose a convenient time for your interview. We look forward to learning more about you and discussing how you can contribute to the Mawidi team."}
          </p>
        </div>
      </section>

      {/* Main Content */}
      <section className="container mx-auto px-4 pb-24">
        {/* Token Validator */}
        <TokenValidator
          token={token}
          language={lang}
          onValidated={handleTokenValidated}
        />

        {/* Scheduler (only show if token is valid) */}
        {tokenData?.valid && (
          <div className="max-w-4xl mx-auto">
            <InterviewScheduler
              token={token}
              language={lang}
              jobData={{
                jobTitle: tokenData.jobTitle || "",
                jobTitleAr: tokenData.jobTitleAr,
                applicantName: tokenData.applicantName || "",
              }}
              onSuccess={handleBookingSuccess}
              onError={handleBookingError}
            />
          </div>
        )}
      </section>
    </main>
  );
}
