"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import {
  Users,
  Mail,
  Lock,
  User,
  CheckCircle,
  XCircle,
  Loader2,
  Clock,
  Building2,
  Shield,
} from "lucide-react";
import type { Lang } from "@/lib/config";

interface InvitationData {
  email: string;
  name: string | null;
  role: string;
  organizationName: string;
  expiresAt: string;
}

export default function AcceptInvitationPage({
  params,
}: {
  params: { lang: Lang; token: string };
}) {
  const { lang, token } = params;
  const router = useRouter();
  const isAr = lang === "ar";

  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);
  const [invitation, setInvitation] = useState<InvitationData | null>(null);
  const [userExists, setUserExists] = useState(false);

  // Form fields
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const t = {
    pageTitle: isAr ? "قبول الدعوة" : "Accept Invitation",
    loading: isAr ? "جاري التحميل..." : "Loading...",
    invalidToken: isAr ? "رابط الدعوة غير صالح" : "Invalid invitation link",
    expiredToken: isAr ? "انتهت صلاحية الدعوة" : "Invitation has expired",
    alreadyAccepted: isAr
      ? "تم قبول الدعوة مسبقاً"
      : "Invitation already accepted",
    youreInvited: isAr
      ? "لقد تمت دعوتك للانضمام إلى"
      : "You've been invited to join",
    asRole: isAr ? "بصفة" : "as",
    admin: isAr ? "مسؤول" : "Admin",
    staff: isAr ? "موظف" : "Staff Member",
    expiresOn: isAr ? "تنتهي الدعوة في" : "Invitation expires on",
    yourDetails: isAr ? "بياناتك" : "Your Details",
    email: isAr ? "البريد الإلكتروني" : "Email",
    fullName: isAr ? "الاسم الكامل" : "Full Name",
    password: isAr ? "كلمة المرور" : "Password",
    confirmPassword: isAr ? "تأكيد كلمة المرور" : "Confirm Password",
    passwordHint: isAr ? "8 أحرف على الأقل" : "At least 8 characters",
    acceptInvitation: isAr ? "قبول الدعوة" : "Accept Invitation",
    joinExisting: isAr ? "الانضمام للفريق" : "Join Team",
    existingAccount: isAr
      ? "لديك حساب بالفعل. سيتم إضافتك للمنظمة."
      : "You already have an account. You will be added to the organization.",
    success: isAr
      ? "تم قبول الدعوة بنجاح!"
      : "Invitation accepted successfully!",
    redirecting: isAr
      ? "جاري التوجيه للوحة التحكم..."
      : "Redirecting to dashboard...",
    passwordMismatch: isAr
      ? "كلمات المرور غير متطابقة"
      : "Passwords do not match",
    passwordTooShort: isAr ? "كلمة المرور قصيرة جداً" : "Password is too short",
    goToLogin: isAr ? "الذهاب لتسجيل الدخول" : "Go to Login",
    tryAgain: isAr ? "حاول مرة أخرى" : "Try Again",
    backToHome: isAr ? "العودة للرئيسية" : "Back to Home",
  };

  useEffect(() => {
    validateInvitation();
  }, [token]);

  const validateInvitation = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch(
        `/api/organization/invitations/accept?token=${token}`,
      );
      const data = await response.json();

      if (!response.ok) {
        if (data.expired) {
          setError(t.expiredToken);
        } else if (data.status === "ACCEPTED") {
          setError(t.alreadyAccepted);
        } else {
          setError(data.error || t.invalidToken);
        }
        return;
      }

      setInvitation(data.invitation);
      setUserExists(data.userExists);
      if (data.invitation.name) {
        setName(data.invitation.name);
      }
    } catch (err) {
      setError(t.invalidToken);
    } finally {
      setLoading(false);
    }
  };

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

    // Validate for new users
    if (!userExists) {
      if (password.length < 8) {
        setError(t.passwordTooShort);
        return;
      }
      if (password !== confirmPassword) {
        setError(t.passwordMismatch);
        return;
      }
    }

    try {
      setSubmitting(true);
      setError(null);

      const response = await fetch("/api/organization/invitations/accept", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          token,
          password: userExists ? undefined : password,
          name: name || undefined,
        }),
      });

      const data = await response.json();

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

      setSuccess(true);

      // Redirect to dashboard after 2 seconds
      setTimeout(() => {
        router.push(`/${lang}/dashboard?tab=team`);
      }, 2000);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setSubmitting(false);
    }
  };

  const getRoleText = (role: string) => {
    return role === "ADMIN" ? t.admin : t.staff;
  };

  // Loading state
  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-4">
        <div className="text-center">
          <Loader2 className="w-12 h-12 text-brand-green animate-spin mx-auto mb-4" />
          <p className="text-slate-600">{t.loading}</p>
        </div>
      </div>
    );
  }

  // Error state (invalid/expired token)
  if (error && !invitation) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl shadow-xl max-w-md w-full p-8 text-center">
          <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <XCircle className="w-8 h-8 text-red-500" />
          </div>
          <h1 className="text-2xl font-bold text-slate-900 mb-2">{error}</h1>
          <p className="text-slate-600 mb-6">
            {isAr
              ? "قد يكون الرابط غير صالح أو منتهي الصلاحية. يرجى التواصل مع المرسل للحصول على رابط جديد."
              : "The link may be invalid or expired. Please contact the sender for a new invitation."}
          </p>
          <a
            href={`/${lang}`}
            className="inline-flex items-center gap-2 px-6 py-3 bg-brand-green text-white rounded-xl font-medium hover:bg-brand-green/90 transition-colors"
          >
            {t.backToHome}
          </a>
        </div>
      </div>
    );
  }

  // Success state
  if (success) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl shadow-xl max-w-md w-full p-8 text-center">
          <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <CheckCircle className="w-8 h-8 text-green-500" />
          </div>
          <h1 className="text-2xl font-bold text-slate-900 mb-2">
            {t.success}
          </h1>
          <p className="text-slate-600 mb-6">{t.redirecting}</p>
          <Loader2 className="w-6 h-6 text-brand-green animate-spin mx-auto" />
        </div>
      </div>
    );
  }

  // Main form
  return (
    <div
      className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-4"
      dir={isAr ? "rtl" : "ltr"}
    >
      <div className="bg-white rounded-2xl shadow-xl max-w-lg w-full overflow-hidden">
        {/* Header */}
        <div className="bg-gradient-to-r from-brand-green to-emerald-600 px-8 py-6 text-white">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center">
              <Users className="w-6 h-6" />
            </div>
            <div>
              <h1 className="text-xl font-bold">{t.pageTitle}</h1>
              <p className="text-white/80 text-sm">{t.youreInvited}</p>
            </div>
          </div>

          {invitation && (
            <div className="bg-white/10 rounded-xl p-4 space-y-2">
              <div className="flex items-center gap-2">
                <Building2 className="w-5 h-5" />
                <span className="font-semibold">
                  {invitation.organizationName}
                </span>
              </div>
              <div className="flex items-center gap-2">
                <Shield className="w-5 h-5" />
                <span>
                  {t.asRole}{" "}
                  <span className="font-semibold">
                    {getRoleText(invitation.role)}
                  </span>
                </span>
              </div>
              <div className="flex items-center gap-2 text-white/80 text-sm">
                <Clock className="w-4 h-4" />
                <span>
                  {t.expiresOn}{" "}
                  {new Date(invitation.expiresAt).toLocaleDateString(
                    isAr ? "ar-SA" : "en-US",
                  )}
                </span>
              </div>
            </div>
          )}
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-8 space-y-6">
          {userExists && (
            <div className="bg-blue-50 border border-blue-200 rounded-xl p-4 text-blue-800 text-sm">
              <CheckCircle className="w-5 h-5 inline-block mr-2" />
              {t.existingAccount}
            </div>
          )}

          <h2 className="text-lg font-semibold text-slate-900">
            {t.yourDetails}
          </h2>

          {/* Email (readonly) */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              {t.email}
            </label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
              <input
                type="email"
                value={invitation?.email || ""}
                readOnly
                className="w-full pl-11 pr-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-slate-600"
              />
            </div>
          </div>

          {/* Name */}
          {!userExists && (
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                {t.fullName}
              </label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder={isAr ? "أدخل اسمك" : "Enter your name"}
                  className="w-full pl-11 pr-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
                />
              </div>
            </div>
          )}

          {/* Password fields (only for new users) */}
          {!userExists && (
            <>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">
                  {t.password}
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                  <input
                    type="password"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="********"
                    required
                    minLength={8}
                    className="w-full pl-11 pr-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
                  />
                </div>
                <p className="text-xs text-slate-500 mt-1">{t.passwordHint}</p>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">
                  {t.confirmPassword}
                </label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />
                  <input
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    placeholder="********"
                    required
                    minLength={8}
                    className="w-full pl-11 pr-4 py-3 border border-slate-200 rounded-xl focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green transition-colors"
                  />
                </div>
              </div>
            </>
          )}

          {/* Error message */}
          {error && (
            <div className="bg-red-50 border border-red-200 rounded-xl p-4 text-red-700 text-sm">
              {error}
            </div>
          )}

          {/* Submit button */}
          <button
            type="submit"
            disabled={submitting}
            className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-brand-green to-emerald-600 text-white rounded-xl font-medium shadow-lg shadow-brand-green/25 hover:shadow-xl hover:shadow-brand-green/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {submitting ? (
              <Loader2 className="w-5 h-5 animate-spin" />
            ) : (
              <CheckCircle className="w-5 h-5" />
            )}
            {userExists ? t.joinExisting : t.acceptInvitation}
          </button>
        </form>
      </div>
    </div>
  );
}
