/**
 * Interview Scheduler Component
 * Main scheduler with date/time picker, timezone selector, and notes
 */

"use client";

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

interface InterviewSchedulerProps {
  token: string;
  language: Lang;
  jobData: {
    jobTitle: string;
    jobTitleAr?: string;
    applicantName: string;
  };
  onSuccess: (bookingData: BookingData) => void;
  onError: (error: string) => void;
}

interface BookingData {
  preferredDate: string;
  preferredTime: string;
  timezone: string;
  additionalNotes?: string;
}

const TIMEZONES = [
  { value: "Asia/Qatar", label: "Qatar (UTC+3)" },
  { value: "Asia/Dubai", label: "UAE (UTC+4)" },
  { value: "Asia/Riyadh", label: "Saudi Arabia (UTC+3)" },
  { value: "Asia/Kuwait", label: "Kuwait (UTC+3)" },
  { value: "Asia/Bahrain", label: "Bahrain (UTC+3)" },
  { value: "Asia/Muscat", label: "Oman (UTC+4)" },
];

export default function InterviewScheduler({
  token,
  language,
  jobData,
  onSuccess,
  onError,
}: InterviewSchedulerProps) {
  const t = UI[language].t;
  const dir = UI[language].dir;

  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [selectedTime, setSelectedTime] = useState<string | null>(null);
  const [timezone, setTimezone] = useState("Asia/Qatar");
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!selectedDate) {
      newErrors.date = t.interviewScheduleDatePlaceholder;
    }

    if (!selectedTime) {
      newErrors.time = t.interviewScheduleTimePlaceholder;
    }

    if (notes && notes.length > 500) {
      newErrors.notes =
        language === "ar"
          ? "يجب ألا تتجاوز الملاحظات 500 حرف"
          : "Notes must be 500 characters or less";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setSubmitting(true);
    setErrors({});

    try {
      const response = await fetch("/api/careers/interview/book", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          token,
          preferredDate: selectedDate,
          preferredTime: selectedTime,
          timezone,
          additionalNotes: notes.trim() || undefined,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to schedule interview");
      }

      // Success
      const bookingData: BookingData = {
        preferredDate: selectedDate!,
        preferredTime: selectedTime!,
        timezone,
        additionalNotes: notes.trim() || undefined,
      };

      onSuccess(bookingData);
    } catch (err) {
      console.error("Interview booking error:", err);
      const errorMessage =
        err instanceof Error ? err.message : t.interviewScheduleErrorMessage;
      onError(errorMessage);
      setErrors({ submit: errorMessage });
    } finally {
      setSubmitting(false);
    }
  };

  const canSubmit = selectedDate && selectedTime && !submitting;

  return (
    <form onSubmit={handleSubmit} className="space-y-8" dir={dir}>
      {/* Date and Time Picker */}
      <DateTimePickerExtended
        selectedDate={selectedDate}
        selectedTime={selectedTime}
        onDateChange={(date) => {
          setSelectedDate(date);
          setErrors((prev) => ({ ...prev, date: "" }));
        }}
        onTimeChange={(time) => {
          setSelectedTime(time);
          setErrors((prev) => ({ ...prev, time: "" }));
        }}
        language={language}
        timezone={timezone}
      />

      {/* Timezone Selector */}
      <div>
        <label
          htmlFor="timezone"
          className="block text-lg font-semibold text-brand-ink dark:text-white mb-4"
        >
          {t.interviewScheduleTimezoneLabel}
        </label>
        <select
          id="timezone"
          value={timezone}
          onChange={(e) => setTimezone(e.target.value)}
          className="
            w-full
            px-4
            py-3
            rounded-lg
            border-2
            border-brand-ink/10
            dark:border-white/10
            bg-white
            dark:bg-brand-ink
            text-brand-ink
            dark:text-white
            focus:outline-none
            focus:ring-4
            focus:ring-brand-green/20
            focus:border-brand-green
            transition-colors
          "
        >
          {TIMEZONES.map((tz) => (
            <option key={tz.value} value={tz.value}>
              {tz.label}
            </option>
          ))}
        </select>
      </div>

      {/* Additional Notes */}
      <div>
        <label
          htmlFor="notes"
          className="block text-lg font-semibold text-brand-ink dark:text-white mb-2"
        >
          {t.interviewScheduleNotesLabel}
        </label>
        <p className="text-sm text-brand-ink/60 dark:text-white/60 mb-4">
          {t.interviewScheduleNotesHelp}
        </p>
        <textarea
          id="notes"
          value={notes}
          onChange={(e) => {
            setNotes(e.target.value);
            setErrors((prev) => ({ ...prev, notes: "" }));
          }}
          placeholder={t.interviewScheduleNotesPlaceholder}
          maxLength={500}
          rows={4}
          className={`
            w-full
            px-4
            py-3
            rounded-lg
            border-2
            ${
              errors.notes
                ? "border-red-500 focus:ring-red-500/20"
                : "border-brand-ink/10 dark:border-white/10 focus:ring-brand-green/20 focus:border-brand-green"
            }
            bg-white
            dark:bg-brand-ink
            text-brand-ink
            dark:text-white
            placeholder:text-brand-ink/40
            dark:placeholder:text-white/40
            focus:outline-none
            focus:ring-4
            transition-colors
            resize-none
          `}
        />
        <div className="flex items-center justify-between mt-2">
          {errors.notes && (
            <p className="text-sm text-red-600 dark:text-red-400">
              {errors.notes}
            </p>
          )}
          <p className="text-sm text-brand-ink/60 dark:text-white/60 ml-auto">
            {notes.length}/500
          </p>
        </div>
      </div>

      {/* Error Message */}
      {errors.submit && (
        <div className="p-4 bg-red-50 dark:bg-red-900/20 border-2 border-red-200 dark:border-red-800 rounded-lg">
          <div className="flex items-start gap-3">
            <svg
              className="w-6 h-6 text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
            <div className="flex-1">
              <h4 className="font-semibold text-red-800 dark:text-red-300 mb-1">
                {t.interviewScheduleErrorTitle}
              </h4>
              <p className="text-sm text-red-700 dark:text-red-400">
                {errors.submit}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Submit Button */}
      <div className="flex items-center gap-4">
        <button
          type="submit"
          disabled={!canSubmit}
          className={`
            flex-1
            px-6
            py-4
            rounded-lg
            font-semibold
            text-lg
            transition-all
            focus:outline-none
            focus:ring-4
            ${
              canSubmit
                ? "bg-brand-green text-white hover:bg-brand-green/90 focus:ring-brand-green/20"
                : "bg-brand-ink/10 dark:bg-white/10 text-brand-ink/40 dark:text-white/40 cursor-not-allowed"
            }
          `}
        >
          {submitting ? (
            <span className="flex items-center justify-center gap-2">
              <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              {t.interviewScheduleSubmitting}
            </span>
          ) : (
            t.interviewScheduleSubmitButton
          )}
        </button>
      </div>

      {/* Selected Summary (shown when both date and time are selected) */}
      {selectedDate && selectedTime && (
        <div className="bg-brand-green/10 border-2 border-brand-green/20 rounded-xl p-6">
          <h3 className="font-semibold text-brand-ink dark:text-white mb-3">
            {t.interviewScheduledDetails}
          </h3>
          <div className="space-y-2 text-sm">
            <div className="flex items-center gap-2">
              <svg
                className="w-5 h-5 text-brand-green"
                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>
              <span className="text-brand-ink/70 dark:text-white/70">
                {new Date(selectedDate).toLocaleDateString(
                  language === "ar" ? "ar-SA" : "en-US",
                  {
                    weekday: "long",
                    year: "numeric",
                    month: "long",
                    day: "numeric",
                  },
                )}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <svg
                className="w-5 h-5 text-brand-green"
                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>
              <span className="text-brand-ink/70 dark:text-white/70">
                {selectedTime} ({timezone})
              </span>
            </div>
          </div>
        </div>
      )}
    </form>
  );
}
