/**
 * Security Tab Component
 * Password management, active sessions, security events
 */

"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";
import {
  validatePasswordStrength,
  getPasswordStrengthColor,
} from "@/lib/validators/password-validator";

interface SecurityTabProps {
  lang: Lang;
  onUnsavedChanges?: (hasChanges: boolean) => void;
  onClose?: () => void;
}

interface Session {
  id: string;
  deviceName: string;
  deviceType: string;
  location: string | null;
  ipAddress: string;
  lastActive: string;
  createdAt: string;
  isCurrent: boolean;
}

interface AuditEvent {
  id: string;
  type: string;
  action: string;
  success: boolean;
  ipAddress: string;
  timestamp: string;
  metadata: any;
}

export default function SecurityTab({ lang }: SecurityTabProps) {
  const isAr = lang === "ar";

  // User authentication state
  const [hasPassword, setHasPassword] = useState<boolean | null>(null);
  const [loadingAuthStatus, setLoadingAuthStatus] = useState(true);

  // Password change state
  const [passwordForm, setPasswordForm] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
  const [passwordError, setPasswordError] = useState<string | null>(null);
  const [passwordSuccess, setPasswordSuccess] = useState(false);
  const [changingPassword, setChangingPassword] = useState(false);

  // Sessions state
  const [sessions, setSessions] = useState<Session[]>([]);
  const [loadingSessions, setLoadingSessions] = useState(true);

  // Audit log state
  const [auditEvents, setAuditEvents] = useState<AuditEvent[]>([]);
  const [loadingAudit, setLoadingAudit] = useState(true);
  const [auditFilter, setAuditFilter] = useState<string>("");

  // Fetch user authentication status
  useEffect(() => {
    fetchAuthStatus();
  }, []);

  // Load sessions and audit log on mount
  useEffect(() => {
    fetchSessions();
    fetchAuditLog();
  }, []);

  const fetchAuthStatus = async () => {
    try {
      const response = await fetch("/api/user/profile");
      const data = await response.json();
      if (data.success && data.user) {
        setHasPassword(data.user.hasPassword || false);
      }
    } catch (err) {
      console.error("Failed to fetch auth status:", err);
    } finally {
      setLoadingAuthStatus(false);
    }
  };

  const fetchSessions = async () => {
    try {
      const response = await fetch("/api/user/sessions");
      const data = await response.json();
      if (data.success) {
        setSessions(data.sessions || []);
      }
    } catch (err) {
      console.error("Failed to fetch sessions:", err);
    } finally {
      setLoadingSessions(false);
    }
  };

  const fetchAuditLog = async (type?: string) => {
    try {
      setLoadingAudit(true);
      const url = type
        ? `/api/user/audit-log?type=${type}`
        : "/api/user/audit-log";
      const response = await fetch(url);
      const data = await response.json();
      if (data.success) {
        setAuditEvents(data.events || []);
      }
    } catch (err) {
      console.error("Failed to fetch audit log:", err);
    } finally {
      setLoadingAudit(false);
    }
  };

  const handlePasswordChange = async (e: React.FormEvent) => {
    e.preventDefault();
    setPasswordError(null);
    setPasswordSuccess(false);

    // Validate passwords match
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      setPasswordError(
        isAr ? "كلمات المرور الجديدة لا تتطابق" : "New passwords do not match",
      );
      return;
    }

    // Validate password strength
    const validation = validatePasswordStrength(passwordForm.newPassword);
    if (!validation.valid) {
      setPasswordError(
        validation.feedback[0] ||
          (isAr ? "كلمة المرور ضعيفة" : "Password is too weak"),
      );
      return;
    }

    setChangingPassword(true);

    try {
      const csrfResponse = await fetch("/api/csrf");
      const { csrfToken } = await csrfResponse.json();

      const response = await fetch("/api/user/change-password", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify(passwordForm),
      });

      const data = await response.json();

      if (data.success) {
        setPasswordSuccess(true);
        setPasswordForm({
          currentPassword: "",
          newPassword: "",
          confirmPassword: "",
        });
        // Refresh sessions since others were logged out
        fetchSessions();
        setTimeout(() => setPasswordSuccess(false), 5000);
      } else {
        setPasswordError(
          data.error ||
            (isAr ? "فشل تغيير كلمة المرور" : "Failed to change password"),
        );
      }
    } catch (err) {
      console.error("Failed to change password:", err);
      setPasswordError(isAr ? "حدث خطأ" : "An error occurred");
    } finally {
      setChangingPassword(false);
    }
  };

  const handleRevokeSession = async (sessionId: string) => {
    if (
      !confirm(
        isAr
          ? "هل أنت متأكد من إلغاء هذه الجلسة؟"
          : "Are you sure you want to revoke this session?",
      )
    ) {
      return;
    }

    try {
      const csrfResponse = await fetch("/api/csrf");
      const { csrfToken } = await csrfResponse.json();

      const response = await fetch(`/api/user/sessions/${sessionId}`, {
        method: "DELETE",
        headers: {
          "x-csrf-token": csrfToken,
        },
      });

      const data = await response.json();

      if (data.success) {
        // Refresh sessions list
        fetchSessions();
      } else {
        alert(
          data.error ||
            (isAr ? "فشل إلغاء الجلسة" : "Failed to revoke session"),
        );
      }
    } catch (err) {
      console.error("Failed to revoke session:", err);
      alert(isAr ? "حدث خطأ" : "An error occurred");
    }
  };

  // Calculate password strength
  const passwordStrength = passwordForm.newPassword
    ? validatePasswordStrength(passwordForm.newPassword)
    : null;
  const strengthColor = passwordStrength
    ? getPasswordStrengthColor(passwordStrength.score)
    : "gray";

  return (
    <div className="space-y-8">
      {/* Change Password Section - Only show if user has a password */}
      {loadingAuthStatus ? (
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-green mx-auto"></div>
        </div>
      ) : hasPassword ? (
        <div>
          <h2 className="text-lg font-semibold text-slate-900 mb-1">
            {isAr ? "تغيير كلمة المرور" : "Change Password"}
          </h2>
          <p className="text-sm text-slate-600 mb-4">
            {isAr
              ? "تحديث كلمة المرور الخاصة بك لتعزيز أمان الحساب"
              : "Update your password to enhance account security"}
          </p>

          {passwordError && (
            <div className="mb-4 rounded-lg bg-red-50 border border-red-200 p-4">
              <p className="text-sm text-red-700">{passwordError}</p>
            </div>
          )}

          {passwordSuccess && (
            <div className="mb-4 rounded-lg bg-emerald-50 border border-emerald-200 p-4">
              <p className="text-sm text-emerald-700">
                ✓{" "}
                {isAr
                  ? "تم تغيير كلمة المرور بنجاح. تم تسجيل خروج الجلسات الأخرى."
                  : "Password changed successfully. Other sessions have been logged out."}
              </p>
            </div>
          )}

          <form onSubmit={handlePasswordChange} className="space-y-4 max-w-md">
            <div>
              <label className="text-sm font-medium text-slate-700 block mb-2">
                {isAr ? "كلمة المرور الحالية" : "Current Password"}
              </label>
              <input
                type="password"
                value={passwordForm.currentPassword}
                onChange={(e) =>
                  setPasswordForm({
                    ...passwordForm,
                    currentPassword: e.target.value,
                  })
                }
                required
                className="w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
                placeholder={
                  isAr ? "أدخل كلمة المرور الحالية" : "Enter current password"
                }
              />
            </div>

            <div>
              <label className="text-sm font-medium text-slate-700 block mb-2">
                {isAr ? "كلمة المرور الجديدة" : "New Password"}
              </label>
              <input
                type="password"
                value={passwordForm.newPassword}
                onChange={(e) =>
                  setPasswordForm({
                    ...passwordForm,
                    newPassword: e.target.value,
                  })
                }
                required
                className="w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
                placeholder={
                  isAr ? "أدخل كلمة مرور قوية" : "Enter a strong password"
                }
              />
              {/* Password strength meter */}
              {passwordForm.newPassword && passwordStrength && (
                <div className="mt-2">
                  <div className="h-2 w-full rounded-full bg-slate-200 overflow-hidden">
                    <div
                      className={`h-full bg-${strengthColor}-500 transition-all duration-300`}
                      style={{ width: `${passwordStrength.score}%` }}
                    ></div>
                  </div>
                  <p className="text-xs text-slate-600 mt-1">
                    {isAr ? "القوة:" : "Strength:"} {passwordStrength.score}%
                  </p>
                </div>
              )}
            </div>

            <div>
              <label className="text-sm font-medium text-slate-700 block mb-2">
                {isAr ? "تأكيد كلمة المرور الجديدة" : "Confirm New Password"}
              </label>
              <input
                type="password"
                value={passwordForm.confirmPassword}
                onChange={(e) =>
                  setPasswordForm({
                    ...passwordForm,
                    confirmPassword: e.target.value,
                  })
                }
                required
                className="w-full rounded-lg border border-slate-300 px-4 py-2.5 text-sm focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
                placeholder={
                  isAr
                    ? "أعد إدخال كلمة المرور الجديدة"
                    : "Re-enter new password"
                }
              />
            </div>

            {/* Password Requirements */}
            {passwordStrength && (
              <div className="rounded-lg bg-slate-50 p-4 text-xs space-y-1.5">
                <p className="font-semibold text-slate-700 mb-2">
                  {isAr ? "متطلبات كلمة المرور:" : "Password Requirements:"}
                </p>
                {Object.entries(passwordStrength.requirements).map(
                  ([key, met]) => (
                    <div
                      key={key}
                      className={`flex items-center gap-2 ${met ? "text-emerald-600" : "text-slate-500"}`}
                    >
                      <span>{met ? "✓" : "○"}</span>
                      <span>
                        {key === "minLength" &&
                          (isAr
                            ? "الحد الأدنى 12 حرفًا"
                            : "Minimum 12 characters")}
                        {key === "hasUppercase" &&
                          (isAr
                            ? "حرف كبير واحد على الأقل"
                            : "At least 1 uppercase letter")}
                        {key === "hasLowercase" &&
                          (isAr
                            ? "حرف صغير واحد على الأقل"
                            : "At least 1 lowercase letter")}
                        {key === "hasNumber" &&
                          (isAr ? "رقم واحد على الأقل" : "At least 1 number")}
                        {key === "hasSpecialChar" &&
                          (isAr
                            ? "رمز خاص واحد (@$!%*?&)"
                            : "At least 1 special character")}
                        {key === "notCommon" &&
                          (isAr
                            ? "ليست كلمة مرور شائعة"
                            : "Not a common password")}
                      </span>
                    </div>
                  ),
                )}
              </div>
            )}

            <button
              type="submit"
              disabled={changingPassword}
              className="w-full rounded-lg bg-brand-green px-6 py-3 text-sm font-semibold text-white hover:bg-brand-greenHover shadow-md hover:shadow-lg transition-all disabled:opacity-50"
            >
              {changingPassword
                ? isAr
                  ? "جاري التغيير..."
                  : "Changing..."
                : isAr
                  ? "تغيير كلمة المرور"
                  : "Change Password"}
            </button>
          </form>
        </div>
      ) : (
        <div className="rounded-lg bg-blue-50 border border-blue-200 p-6">
          <div className="flex items-start gap-4">
            <div className="text-3xl">🔐</div>
            <div>
              <h3 className="text-lg font-semibold text-slate-900 mb-2">
                {isAr
                  ? "تسجيل الدخول بدون كلمة مرور"
                  : "Passwordless Authentication"}
              </h3>
              <p className="text-sm text-slate-700 mb-3">
                {isAr
                  ? "أنت تستخدم طريقة تسجيل الدخول الآمنة بدون كلمة مرور (OTP). لا تحتاج إلى تعيين كلمة مرور."
                  : "You're using secure passwordless authentication (OTP). No password needed."}
              </p>
              <p className="text-xs text-slate-600">
                {isAr
                  ? "💡 نوصي بالاستمرار في استخدام OTP للحصول على أمان أفضل. إذا كنت ترغب في تعيين كلمة مرور، يرجى الاتصال بالدعم."
                  : "💡 We recommend continuing to use OTP for better security. If you wish to set a password, please contact support."}
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Active Sessions Section */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">
              {isAr ? "الجلسات النشطة" : "Active Sessions"} ({sessions.length})
            </h2>
            <p className="text-sm text-slate-600">
              {isAr
                ? "إدارة الأجهزة المتصلة بحسابك"
                : "Manage devices connected to your account"}
            </p>
          </div>
        </div>

        {loadingSessions ? (
          <div className="text-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-green mx-auto"></div>
          </div>
        ) : sessions.length === 0 ? (
          <div className="rounded-lg border-2 border-dashed border-slate-200 p-8 text-center">
            <p className="text-sm text-slate-500">
              {isAr ? "لا توجد جلسات نشطة" : "No active sessions"}
            </p>
          </div>
        ) : (
          <div className="space-y-3">
            {sessions.map((session) => (
              <div
                key={session.id}
                className="flex items-center justify-between rounded-lg border border-slate-200 p-4 hover:border-slate-300 transition-colors"
              >
                <div className="flex items-start gap-3 flex-1">
                  <div className="text-2xl">
                    {session.deviceType === "mobile"
                      ? "📱"
                      : session.deviceType === "tablet"
                        ? "📲"
                        : "💻"}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <p className="text-sm font-medium text-slate-900">
                        {session.deviceName}
                      </p>
                      {session.isCurrent && (
                        <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-semibold text-emerald-700">
                          {isAr ? "الحالية" : "Current"}
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-slate-600 mt-0.5">
                      {session.location ||
                        (isAr ? "موقع غير معروف" : "Unknown location")}
                    </p>
                    <p className="text-xs text-slate-500 mt-0.5">
                      {session.ipAddress} •{" "}
                      {isAr ? "آخر نشاط:" : "Last active:"}{" "}
                      {new Date(session.lastActive).toLocaleString(
                        isAr ? "ar-SA" : "en-US",
                      )}
                    </p>
                  </div>
                </div>
                {!session.isCurrent && (
                  <button
                    onClick={() => handleRevokeSession(session.id)}
                    className="rounded-lg border border-red-200 px-3 py-1.5 text-xs font-medium text-red-600 hover:bg-red-50 transition-colors"
                  >
                    {isAr ? "إلغاء" : "Revoke"}
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Security Events Section */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-semibold text-slate-900">
              {isAr ? "الأحداث الأمنية" : "Security Events"}
            </h2>
            <p className="text-sm text-slate-600">
              {isAr ? "آخر 20 حدث أمني" : "Recent 20 security events"}
            </p>
          </div>
          <select
            value={auditFilter}
            onChange={(e) => {
              setAuditFilter(e.target.value);
              fetchAuditLog(e.target.value || undefined);
            }}
            className="rounded-lg border border-slate-300 px-3 py-1.5 text-sm"
          >
            <option value="">{isAr ? "الكل" : "All"}</option>
            <option value="security">{isAr ? "أمان" : "Security"}</option>
            <option value="account">{isAr ? "حساب" : "Account"}</option>
            <option value="billing">{isAr ? "فوترة" : "Billing"}</option>
          </select>
        </div>

        {loadingAudit ? (
          <div className="text-center py-8">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-green mx-auto"></div>
          </div>
        ) : auditEvents.length === 0 ? (
          <div className="rounded-lg border-2 border-dashed border-slate-200 p-8 text-center">
            <p className="text-sm text-slate-500">
              {isAr ? "لا توجد أحداث" : "No events found"}
            </p>
          </div>
        ) : (
          <div className="space-y-2">
            {auditEvents.map((event) => (
              <div
                key={event.id}
                className="flex items-start gap-3 rounded-lg border border-slate-100 p-3 text-sm"
              >
                <span
                  className={
                    event.success ? "text-emerald-500" : "text-red-500"
                  }
                >
                  {event.success ? "✅" : "❌"}
                </span>
                <div className="flex-1">
                  <p className="font-medium text-slate-900">
                    {event.action.replace(/_/g, " ")}
                  </p>
                  <p className="text-xs text-slate-600 mt-0.5">
                    {event.ipAddress} •{" "}
                    {new Date(event.timestamp).toLocaleString(
                      isAr ? "ar-SA" : "en-US",
                    )}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
