// File: monorepo/web/maplefile-frontend/src/pages/Anonymous/Recovery/CompleteRecovery.jsx
import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useNavigate, Link } from "react-router";
import { useServices } from "../../../services/Services";
import {
  Button,
  Input,
  Alert,
  Card,
  Spinner,
  useUIXTheme,
} from "../../../components/UIX";
import {
  ArrowRightIcon,
  ArrowLeftIcon,
  LockClosedIcon,
  ShieldCheckIcon,
  CheckIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
  KeyIcon,
  EyeIcon,
  EyeSlashIcon,
  CheckCircleIcon,
  ArrowPathIcon,
  LockOpenIcon,
} from "@heroicons/react/24/outline";

const CompleteRecovery = () => {
  const navigate = useNavigate();
  const { recoveryManager } = useServices();
  const { getThemeClasses } = useUIXTheme();
  const isMountedRef = useRef(true);

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [recoveryPhrase, setRecoveryPhrase] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [email, setEmail] = useState("");
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // Cleanup on unmount
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  useEffect(() => {
    // Check if we have completed verification
    const recoveryEmail = recoveryManager.getRecoveryEmail();
    const isVerified = recoveryManager.isVerificationComplete();

    if (!recoveryEmail || !isVerified) {
      if (import.meta.env.DEV) {
        console.log("[CompleteRecovery] No verified recovery session, redirecting");
      }
      navigate("/recovery/initiate");
      return;
    }

    setEmail(recoveryEmail);
  }, [navigate, recoveryManager]);

  const handleSubmit = useCallback(async (e) => {
    e.preventDefault();

    if (!isMountedRef.current) return;

    setLoading(true);
    setError("");

    try {
      // Validate passwords
      if (!newPassword) {
        throw new Error("Password is required");
      }

      if (newPassword.length < 8) {
        throw new Error("Password must be at least 8 characters long");
      }

      if (newPassword !== confirmPassword) {
        throw new Error("Passwords do not match");
      }

      // Validate recovery phrase again
      const words = recoveryPhrase.trim().toLowerCase().split(/\s+/);
      if (words.length !== 12) {
        throw new Error("Recovery phrase must be exactly 12 words");
      }

      // Join words with single space
      const normalizedPhrase = words.join(" ");

      if (import.meta.env.DEV) {
        console.log("[CompleteRecovery] Completing recovery with new password");
      }

      // Complete recovery with both recovery phrase and new password
      await recoveryManager.completeRecoveryWithPhrase(
        normalizedPhrase,
        newPassword,
      );

      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.log("[CompleteRecovery] Recovery completed successfully");
      }

      // Show success modal or alert
      alert(
        "Account recovery completed successfully! You can now log in with your new password.",
      );

      // Navigate to login
      navigate("/login");
    } catch (err) {
      if (!isMountedRef.current) return;

      if (import.meta.env.DEV) {
        console.error("[CompleteRecovery] Recovery completion failed:", err);
      }
      setError(err.message);
    } finally {
      if (isMountedRef.current) {
        setLoading(false);
      }
    }
  }, [newPassword, confirmPassword, recoveryPhrase, recoveryManager, navigate]);

  const handleBackToVerify = useCallback(() => {
    navigate("/recovery/verify");
  }, [navigate]);

  // Memoize word count calculation
  const wordCount = useMemo(() => {
    return recoveryPhrase.trim() ? recoveryPhrase.trim().split(/\s+/).length : 0;
  }, [recoveryPhrase]);

  // Memoize password toggle buttons
  const newPasswordSuffix = useMemo(() => (
    <button
      type="button"
      onClick={() => setShowNewPassword(!showNewPassword)}
      className="flex items-center touch-manipulation"
      tabIndex={-1}
    >
      {showNewPassword ? (
        <EyeSlashIcon className={`h-5 w-5 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")}`} />
      ) : (
        <EyeIcon className={`h-5 w-5 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")}`} />
      )}
    </button>
  ), [showNewPassword, getThemeClasses]);

  const confirmPasswordSuffix = useMemo(() => (
    <button
      type="button"
      onClick={() => setShowConfirmPassword(!showConfirmPassword)}
      className="flex items-center touch-manipulation"
      tabIndex={-1}
    >
      {showConfirmPassword ? (
        <EyeSlashIcon className={`h-5 w-5 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")}`} />
      ) : (
        <EyeIcon className={`h-5 w-5 ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")}`} />
      )}
    </button>
  ), [showConfirmPassword, getThemeClasses]);

  if (!email) {
    return (
      <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")} flex items-center justify-center`}>
        <div className="text-center">
          <Spinner size="lg" className="mx-auto mb-4" />
          <h2 className={`text-2xl font-bold ${getThemeClasses("text-primary")} mb-4`}>Loading...</h2>
          <p className={getThemeClasses("text-secondary")}>Checking recovery session...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")} flex flex-col`}>
      {/* Navigation */}
      <nav className={`${getThemeClasses("bg-card")}/95 backdrop-blur-sm border-b ${getThemeClasses("border-muted")}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-4">
            <Link to="/" className="flex items-center group">
              <div className={`flex items-center justify-center h-10 w-10 ${getThemeClasses("bg-gradient-secondary")} rounded-lg mr-3 group-hover:scale-105 transition-transform duration-200`}>
                <LockClosedIcon className="h-6 w-6 text-white" />
              </div>
              <span className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                MapleFile
              </span>
            </Link>
            <div className="flex items-center space-x-6">
              <span className={`text-base font-medium ${getThemeClasses("text-secondary")}`}>
                Step 3 of 3
              </span>
            </div>
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <div className="flex-1 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
        <div className="max-w-2xl w-full space-y-8">
          {/* Progress Indicator */}
          <div className="flex items-center justify-center mb-8">
            <div className="flex items-center space-x-4">
              <div className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 ${getThemeClasses("bg-success")} rounded-full text-white text-sm font-bold`}>
                  <CheckIcon className="h-4 w-4" />
                </div>
                <span className={`ml-2 text-sm font-semibold ${getThemeClasses("text-success")}`}>
                  Email
                </span>
              </div>
              <div className={`w-12 h-0.5 ${getThemeClasses("bg-success")}`}></div>
              <div className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 ${getThemeClasses("bg-success")} rounded-full text-white text-sm font-bold`}>
                  <CheckIcon className="h-4 w-4" />
                </div>
                <span className={`ml-2 text-sm font-semibold ${getThemeClasses("text-success")}`}>
                  Verify
                </span>
              </div>
              <div className={`w-12 h-0.5 ${getThemeClasses("bg-success")}`}></div>
              <div className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 ${getThemeClasses("bg-gradient-secondary")} rounded-full text-white text-sm font-bold`}>
                  3
                </div>
                <span className={`ml-2 text-sm font-semibold ${getThemeClasses("text-primary")}`}>
                  Reset
                </span>
              </div>
            </div>
          </div>

          {/* Header */}
          <div className="text-center animate-fade-in-up">
            <div className="flex justify-center mb-6">
              <div className="relative">
                <div className={`flex items-center justify-center h-16 w-16 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl shadow-lg animate-pulse`}>
                  <LockOpenIcon className="h-8 w-8 text-white" />
                </div>
                <div className={`absolute -inset-1 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl blur opacity-20 animate-pulse`}></div>
              </div>
            </div>
            <h2 className={`text-3xl font-black ${getThemeClasses("text-primary")} mb-2`}>
              Set Your New Password
            </h2>
            <p className={`${getThemeClasses("text-secondary")} mb-2`}>
              Final step: Create a new password for {email}
            </p>
            <div className={`flex items-center justify-center space-x-2 text-sm ${getThemeClasses("text-secondary")}`}>
              <ArrowPathIcon className={`h-4 w-4 ${getThemeClasses("text-success")}`} />
              <span>
                Your encryption keys will be re-encrypted with the new password
              </span>
            </div>
          </div>

          {/* Form Card */}
          <Card className="shadow-2xl p-8 animate-fade-in-up-delay">
            {/* Error Message */}
            {error && (
              <Alert
                type="error"
                dismissible
                onDismiss={() => setError("")}
                className="mb-6 animate-fade-in"
              >
                <div>
                  <strong className="font-semibold">Recovery Error</strong>
                  <p className="mt-1">{error}</p>
                </div>
              </Alert>
            )}

            {/* Security Notice */}
            <Alert type="info" className="mb-6">
              <div>
                <strong className="font-semibold">Why enter your recovery phrase again?</strong>
                <p className="mt-1">
                  We need your recovery phrase to decrypt your master key and
                  re-encrypt it with your new password. This ensures
                  continuous access to your encrypted files.
                </p>
              </div>
            </Alert>

            {/* Form */}
            <form onSubmit={handleSubmit} className="space-y-6">
              {/* Recovery Phrase */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label
                    htmlFor="recoveryPhrase"
                    className={`block text-sm font-semibold ${getThemeClasses("text-primary")}`}
                  >
                    Recovery Phrase (Required Again)
                  </label>
                  <span
                    className={`text-xs font-medium ${
                      wordCount === 12
                        ? getThemeClasses("text-success")
                        : wordCount > 0
                          ? getThemeClasses("text-warning")
                          : getThemeClasses("text-secondary")
                    }`}
                  >
                    {wordCount}/12 words
                  </span>
                </div>
                <div className="relative">
                  <textarea
                    id="recoveryPhrase"
                    value={recoveryPhrase}
                    onChange={(e) => setRecoveryPhrase(e.target.value)}
                    placeholder="Re-enter your 12-word recovery phrase"
                    rows={3}
                    required
                    disabled={loading}
                    className={`w-full px-4 py-3 border rounded-lg focus:ring-2 ${getThemeClasses("focus:ring-accent")} ${getThemeClasses("focus:border-accent")} transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed ${getThemeClasses("text-primary")} ${getThemeClasses("placeholder-secondary")} font-mono text-sm leading-relaxed resize-none ${getThemeClasses("bg-card")} ${
                      wordCount === 12
                        ? `${getThemeClasses("border-success")} ${getThemeClasses("bg-success-light")}`
                        : getThemeClasses("border-muted")
                    }`}
                  />
                </div>
              </div>

              {/* New Password Section */}
              <div className={`space-y-4 p-4 ${getThemeClasses("bg-success-light")} rounded-lg border ${getThemeClasses("border-success")}`}>
                <h3 className={`text-sm font-semibold ${getThemeClasses("text-primary")} flex items-center`}>
                  <KeyIcon className="h-4 w-4 mr-2" />
                  Create Your New Password
                </h3>

                {/* New Password */}
                <Input
                  label="New Password"
                  type={showNewPassword ? "text" : "password"}
                  name="newPassword"
                  placeholder="Enter your new password"
                  value={newPassword}
                  onChange={(value) => setNewPassword(value)}
                  disabled={loading}
                  required
                  autoComplete="new-password"
                  icon={LockClosedIcon}
                  suffix={newPasswordSuffix}
                  helperText="Password must be at least 8 characters long"
                  error={error && error.includes("password") ? error : null}
                />

                {/* Confirm Password */}
                <div>
                  <Input
                    label="Confirm New Password"
                    type={showConfirmPassword ? "text" : "password"}
                    name="confirmPassword"
                    placeholder="Confirm your new password"
                    value={confirmPassword}
                    onChange={(value) => setConfirmPassword(value)}
                    disabled={loading}
                    required
                    autoComplete="new-password"
                    icon={LockClosedIcon}
                    suffix={confirmPasswordSuffix}
                  />
                  {confirmPassword && newPassword === confirmPassword && (
                    <p className={`mt-1 text-xs ${getThemeClasses("text-success")} flex items-center`}>
                      <CheckIcon className="h-3 w-3 mr-1" />
                      Passwords match
                    </p>
                  )}
                </div>
              </div>

              <div className="space-y-3">
                <Button
                  type="submit"
                  variant="primary"
                  fullWidth
                  disabled={
                    loading ||
                    wordCount !== 12 ||
                    !newPassword ||
                    newPassword !== confirmPassword
                  }
                  loading={loading}
                  className="py-3"
                >
                  {!loading && (
                    <span className="inline-flex items-center gap-2">
                      <CheckCircleIcon className="h-4 w-4" />
                      <span>Complete Recovery</span>
                      <ArrowRightIcon className="h-4 w-4" />
                    </span>
                  )}
                  {loading && "Setting New Password..."}
                </Button>

                <Button
                  type="button"
                  variant="secondary"
                  fullWidth
                  onClick={handleBackToVerify}
                  disabled={loading}
                >
                  <span className="inline-flex items-center gap-2">
                    <ArrowLeftIcon className="h-4 w-4" />
                    <span>Back to Verification</span>
                  </span>
                </Button>
              </div>
            </form>
          </Card>

          {/* What Happens Next */}
          <div className={`${getThemeClasses("bg-info-light")} rounded-lg border ${getThemeClasses("border-info")} p-6 animate-fade-in-up-delay-2`}>
            <h3 className={`text-sm font-semibold ${getThemeClasses("text-primary")} mb-3 flex items-center`}>
              <InformationCircleIcon className={`h-4 w-4 mr-2 ${getThemeClasses("text-info")}`} />
              What Happens Next?
            </h3>
            <ul className={`text-sm ${getThemeClasses("text-secondary")} space-y-2`}>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-accent")} mr-2 mt-0.5`}>•</span>
                Your master key will be decrypted using your recovery key
              </li>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-accent")} mr-2 mt-0.5`}>•</span>
                New encryption keys will be generated
              </li>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-accent")} mr-2 mt-0.5`}>•</span>
                All keys will be re-encrypted with your new password
              </li>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-accent")} mr-2 mt-0.5`}>•</span>
                Your recovery phrase remains the same for future use
              </li>
              <li className="flex items-start">
                <span className={`${getThemeClasses("text-accent")} mr-2 mt-0.5`}>•</span>
                You'll be able to log in immediately with your new password
              </li>
            </ul>
          </div>

          {/* Security Notes */}
          <div className={`${getThemeClasses("bg-muted")} rounded-lg border ${getThemeClasses("border-muted")} p-4 animate-fade-in-up-delay-3`}>
            <h4 className={`text-xs font-semibold ${getThemeClasses("text-primary")} mb-2 flex items-center`}>
              <ShieldCheckIcon className="h-4 w-4 mr-1" />
              Security Notes
            </h4>
            <div className={`text-xs ${getThemeClasses("text-secondary")} space-y-1`}>
              <p>• Choose a strong, unique password</p>
              <p>• Your new password will be used to encrypt your keys</p>
              <p>• Keep your recovery phrase safe - it hasn't changed</p>
              <p>• All your encrypted data remains accessible</p>
            </div>
          </div>
        </div>
      </div>

      {/* Footer */}
      <footer className={`${getThemeClasses("bg-card")} border-t ${getThemeClasses("border-muted")} py-8`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className={`text-center text-sm ${getThemeClasses("text-secondary")}`}>
            <p>&copy; 2025 MapleFile Inc. All rights reserved.</p>
            <div className="mt-2 space-x-4">
              <Link
                to="/privacy"
                className={`${getThemeClasses("hover:text-accent")} transition-colors duration-200`}
              >
                Privacy Policy
              </Link>
              <Link
                to="/terms"
                className={`${getThemeClasses("hover:text-accent")} transition-colors duration-200`}
              >
                Terms of Service
              </Link>
              <Link
                to="/support"
                className={`${getThemeClasses("hover:text-accent")} transition-colors duration-200`}
              >
                Support
              </Link>
            </div>
          </div>
        </div>
      </footer>

      {/* CSS Animations */}
      <style>{`
        @keyframes fade-in {
          from {
            opacity: 0;
            transform: translateY(10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        @keyframes fade-in-up {
          from {
            opacity: 0;
            transform: translateY(30px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }

        .animate-fade-in {
          animation: fade-in 0.4s ease-out;
        }

        .animate-fade-in-up {
          animation: fade-in-up 0.6s ease-out;
        }

        .animate-fade-in-up-delay {
          animation: fade-in-up 0.6s ease-out 0.2s both;
        }

        .animate-fade-in-up-delay-2 {
          animation: fade-in-up 0.6s ease-out 0.4s both;
        }

        .animate-fade-in-up-delay-3 {
          animation: fade-in-up 0.6s ease-out 0.6s both;
        }
      `}</style>
    </div>
  );
};

export default CompleteRecovery;
