import React, { useEffect, useState, useRef } from 'react';
import { LogOut, Monitor, Smartphone, Tablet } from 'lucide-react';
import sessionService, { UserSession } from '../../features/auth/services/sessionService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { formatDate } from '../../shared/utils/format';

const SessionManagementPage: React.FC = () => {
  const [sessions, setSessions] = useState<UserSession[]>([]);
  const [loading, setLoading] = useState(true);
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchSessions();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  const fetchSessions = async () => {
    try {
      setLoading(true);
      const response = await sessionService.getMySessions();
      setSessions(response.data.sessions || []);
    } catch (error: unknown) {
      const isAbortError = (e: unknown): boolean => {
        if (typeof e === 'object' && e !== null) {
          const err = e as { name?: string; code?: string };
          return err.name === 'AbortError' || err.code === 'ERR_CANCELED';
        }
        return false;
      };
      if (isAbortError(error)) {
        return;
      }
      toast.error(getUserFriendlyError(error) || 'Unable to load sessions');
    } finally {
      setLoading(false);
    }
  };

  const handleRevoke = async (sessionId: number) => {
    if (!confirm('Are you sure you want to revoke this session?')) return;

    try {
      const response = await sessionService.revokeSession(sessionId);
      // Check if logout is required (current session was revoked)
      // Response structure: {success: true, data: {logout_required: true}, message: '...'}
      // sessionService returns response.data, so response is {success: true, data: {...}, message: '...'}
      if (response.data?.logout_required) {
        toast.warning('Your current session has been revoked. You will be logged out.');
        // Give user a moment to see the message, then logout
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.success(response.message || 'Session revoked');
        fetchSessions();
      }
    } catch (error: unknown) {
      // Check if it's an unauthorized error (session was revoked)
      if (getUserFriendlyError(error) === 401) {
        toast.warning('Your session has been revoked. You will be logged out.');
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.error(getUserFriendlyError(error) || 'Unable to revoke session');
      }
    }
  };

  const handleRevokeAll = async () => {
    if (!confirm('Are you sure you want to revoke all other sessions? This will also log you out.')) return;

    try {
      const response = await sessionService.revokeAllSessions();
      // Revoking all sessions always logs the user out
      // Response structure: {success: true, data: {logout_required: true, revoked_count: X}, message: '...'}
      // sessionService returns response.data, so response is {success: true, data: {...}, message: '...'}
      if (response.data?.logout_required) {
        toast.warning(response.message || 'All sessions have been revoked. You will be logged out.');
        // Give user a moment to see the message, then logout
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.success(response.message || 'All sessions revoked');
        fetchSessions();
      }
    } catch (error: unknown) {
      // Check if it's an unauthorized error (sessions were revoked)
      if (getUserFriendlyError(error) === 401) {
        toast.warning('All sessions have been revoked. You will be logged out.');
        setTimeout(() => {
          window.location.href = '/';
        }, 2000);
      } else {
        toast.error(getUserFriendlyError(error) || 'Unable to revoke sessions');
      }
    }
  };

  const getDeviceIcon = (userAgent?: string) => {
    if (!userAgent) return <Monitor className="w-5 h-5" />;
    if (userAgent.includes('Mobile')) return <Smartphone className="w-5 h-5" />;
    if (userAgent.includes('Tablet')) return <Tablet className="w-5 h-5" />;
    return <Monitor className="w-5 h-5" />;
  };

  if (loading) {
    return <Loading fullScreen text="Loading sessions..." />;
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 sm:gap-6 mb-6 sm:mb-8 md:mb-10 animate-fade-in">
        <div className="w-full lg:w-auto">
          <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
            <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-blue-400 via-indigo-500 to-purple-600 rounded-full"></div>
            <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Active Sessions
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">Manage your active sessions</p>
        </div>
        {sessions.length > 1 && (
          <button
            onClick={handleRevokeAll}
            className="w-full sm:w-auto px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-xl font-semibold hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl transition-all duration-200 text-xs sm:text-sm"
          >
            Revoke All Other Sessions
          </button>
        )}
      </div>

      <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300">
        {sessions.length === 0 ? (
          <div className="text-center py-8 sm:py-12">
            <p className="text-slate-500 text-sm sm:text-base">No active sessions</p>
          </div>
        ) : (
          <div className="space-y-3 sm:space-y-4">
            {sessions.map((session) => (
              <div
                key={session.id}
                className="bg-gradient-to-r from-slate-50 to-white border border-slate-200 rounded-lg sm:rounded-xl p-3 sm:p-4 hover:from-red-50 hover:to-rose-50 hover:border-red-300 hover:shadow-lg transition-all duration-200"
              >
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4">
                  <div className="flex items-start gap-3 sm:gap-4 flex-1 min-w-0">
                    <div className="mt-1 flex-shrink-0 text-slate-600">
                      {getDeviceIcon(session.user_agent)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-semibold text-sm sm:text-base mb-1 truncate">
                        {session.user_agent || 'Unknown Device'}
                      </p>
                      <p className="text-slate-600 text-xs sm:text-sm mb-1">
                        IP: {session.ip_address || 'Unknown'}
                      </p>
                      <p className="text-slate-500 text-xs">
                        Last Activity: {formatDate(session.last_activity)}
                      </p>
                      <p className="text-slate-500 text-xs">
                        Expires: {formatDate(session.expires_at)}
                      </p>
                    </div>
                  </div>
                  <button
                    onClick={() => handleRevoke(session.id)}
                    className="w-full sm:w-auto px-3 sm:px-4 py-2 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-lg sm:rounded-xl hover:from-red-700 hover:to-red-800 shadow-lg hover:shadow-xl transition-all duration-200 flex items-center justify-center gap-2 text-xs sm:text-sm font-semibold"
                  >
                    <LogOut className="w-4 h-4" />
                    Revoke
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default SessionManagementPage;

