// File: src/pages/Anonymous/Login/SessionExpired.jsx
import React, { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate, useLocation, Link } from "react-router";
import {
  Button,
  Card,
  Alert,
  useUIXTheme,
} from "../../../components/UIX";
import {
  ClockIcon,
  LockClosedIcon,
  ShieldCheckIcon,
  ArrowRightIcon,
  InformationCircleIcon,
  CheckCircleIcon,
  HomeIcon,
} from "@heroicons/react/24/outline";

const SessionExpired = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { getThemeClasses } = useUIXTheme();
  const [countdown, setCountdown] = useState(30);
  const timerRef = useRef(null);
  const isMountedRef = useRef(true);

  // Get the reason and message from location state
  const { reason, from } = location.state || {};

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

  // Determine the appropriate message and icon based on reason
  const getSessionInfo = useCallback(() => {
    switch (reason) {
      case "inactivity_timeout":
        return {
          title: "Session Expired",
          subtitle: "Your session expired due to inactivity",
          description:
            "For your security, we automatically log you out after 60 minutes of inactivity. This helps protect your encrypted files from unauthorized access.",
          icon: ClockIcon,
          type: "warning",
        };
      case "manual_clear":
        return {
          title: "Session Cleared",
          subtitle: "Your session was manually cleared",
          description:
            "Your session has been cleared. This might have happened if you logged out from another tab or if there was a security-related action.",
          icon: ShieldCheckIcon,
          type: "info",
        };
      default:
        return {
          title: "Session Expired",
          subtitle: "Your session has expired",
          description:
            "For your security, your session has expired. Please sign in again to continue accessing your encrypted files.",
          icon: LockClosedIcon,
          type: "error",
        };
    }
  }, [reason]);

  const sessionInfo = getSessionInfo();

  // Auto-redirect countdown
  useEffect(() => {
    timerRef.current = setInterval(() => {
      if (!isMountedRef.current) return;

      setCountdown((prev) => {
        if (prev <= 1) {
          navigate("/login", {
            state: {
              from: from,
              autoRedirect: true,
              reason: "session_expired",
            },
          });
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [navigate, from]);

  const handleSignInNow = useCallback(() => {
    navigate("/login", {
      state: {
        from: from,
        reason: "session_expired",
      },
    });
  }, [navigate, from]);

  const handleGoHome = useCallback(() => {
    navigate("/");
  }, [navigate]);

  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">
              <Link
                to="/register"
                className={`text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")} transition-colors duration-200`}
              >
                Need an account?
              </Link>
              <Link
                to="/recovery"
                className={`text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")} transition-colors duration-200`}
              >
                Forgot password?
              </Link>
            </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-md w-full space-y-8">
          {/* 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 ${
                  sessionInfo.type === "warning" ? getThemeClasses("bg-warning-light") :
                  sessionInfo.type === "info" ? getThemeClasses("bg-info-light") :
                  getThemeClasses("bg-error-light")
                } rounded-2xl shadow-lg`}>
                  <sessionInfo.icon className={`h-8 w-8 ${
                    sessionInfo.type === "warning" ? getThemeClasses("text-warning") :
                    sessionInfo.type === "info" ? getThemeClasses("text-info") :
                    getThemeClasses("text-error")
                  }`} />
                </div>
                <div className={`absolute -inset-1 ${getThemeClasses("bg-gradient-secondary")} rounded-2xl blur opacity-20`}></div>
              </div>
            </div>
            <h2 className={`text-3xl font-black ${getThemeClasses("text-primary")} mb-2`}>
              {sessionInfo.title}
            </h2>
            <p className={`${getThemeClasses("text-secondary")} mb-4`}>{sessionInfo.subtitle}</p>
          </div>

          {/* Session Info Card */}
          <Card className="shadow-2xl p-8 animate-fade-in-up-delay">
            {/* Description */}
            <Alert type="info" className="mb-6">
              <div>
                <strong className="font-semibold">What happened?</strong>
                <p className="mt-1">{sessionInfo.description}</p>
              </div>
            </Alert>

            {/* Security Info */}
            <Alert type="success" className="mb-6">
              <div>
                <strong className="font-semibold">Your data is secure</strong>
                <ul className="mt-1 space-y-1">
                  <li>• Your files remain encrypted and protected</li>
                  <li>• No one can access your data without your password</li>
                  <li>• Session expiry is a security feature, not a problem</li>
                </ul>
              </div>
            </Alert>

            {/* Auto-redirect notice */}
            <Alert type="warning" className="mb-6">
              <div className="flex items-center justify-center">
                <ClockIcon className="h-5 w-5 mr-3 flex-shrink-0" />
                <p>
                  Automatically redirecting to sign in page in{" "}
                  <span className="font-bold">{countdown}</span>{" "}
                  seconds
                </p>
              </div>
            </Alert>

            {/* Action Buttons */}
            <div className="space-y-4">
              <Button
                onClick={handleSignInNow}
                variant="primary"
                fullWidth
                className="py-3"
              >
                <span className="inline-flex items-center gap-2">
                  <span>Sign In Now</span>
                  <ArrowRightIcon className="h-4 w-4" />
                </span>
              </Button>

              <Button
                onClick={handleGoHome}
                variant="secondary"
                fullWidth
                className="py-3"
              >
                <span className="inline-flex items-center gap-2">
                  <HomeIcon className="h-4 w-4" />
                  <span>Go to Homepage</span>
                </span>
              </Button>
            </div>

            {/* Alternative Actions */}
            <div className="mt-6 flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0 text-sm">
              <Link
                to="/register"
                className={`${getThemeClasses("link-primary")} font-medium hover:underline transition-colors duration-200`}
              >
                Create new account
              </Link>
              <Link
                to="/recovery"
                className={`${getThemeClasses("text-secondary")} ${getThemeClasses("hover:text-accent")} font-medium hover:underline transition-colors duration-200`}
              >
                Forgot your password?
              </Link>
            </div>
          </Card>

          {/* Additional Info */}
          <div className={`text-center text-sm ${getThemeClasses("text-secondary")} animate-fade-in-up-delay-2`}>
            <p>Session timeout: 60 minutes of inactivity</p>
            <p className="mt-1">This helps keep your encrypted files secure</p>
          </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>

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

        .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;
        }
      `}</style>
    </div>
  );
};

export default SessionExpired;
