/**
 * SessionsList Component
 * Displays list of active sessions with management capabilities
 */

import { useEffect, useState } from 'react';
import { useSessionsStore } from '../../../stores/sessionsStore';
import { DeviceCard } from './DeviceCard';

// ============================================================================
// Component
// ============================================================================

export function SessionsList() {
  const {
    sessions,
    loading,
    error,
    revoking,
    fetchSessions,
    revokeSession,
    revokeAllSessions,
    clearError,
  } = useSessionsStore();

  const [showRevokeAllConfirm, setShowRevokeAllConfirm] = useState(false);
  const [revokeAllLoading, setRevokeAllLoading] = useState(false);

  // Fetch sessions on mount
  useEffect(() => {
    fetchSessions();
  }, [fetchSessions]);

  // Handle revoke all sessions
  const handleRevokeAll = async () => {
    setRevokeAllLoading(true);
    try {
      await revokeAllSessions();
    } catch {
      // Error is handled in store
    } finally {
      setRevokeAllLoading(false);
      setShowRevokeAllConfirm(false);
    }
  };

  // Sort sessions: current first, then by last active
  const sortedSessions = [...sessions].sort((a, b) => {
    if (a.isCurrent) return -1;
    if (b.isCurrent) return 1;
    return new Date(b.lastActiveAt).getTime() - new Date(a.lastActiveAt).getTime();
  });

  const otherSessionsCount = sessions.filter(s => !s.isCurrent).length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold text-white">Active Sessions</h3>
          <p className="text-sm text-slate-400 mt-1">
            {sessions.length} active session{sessions.length !== 1 ? 's' : ''} across your devices
          </p>
        </div>

        {/* Revoke All Button */}
        {otherSessionsCount > 0 && (
          <div>
            {showRevokeAllConfirm ? (
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={handleRevokeAll}
                  disabled={revokeAllLoading}
                  className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors"
                >
                  {revokeAllLoading ? (
                    <span className="flex items-center gap-2">
                      <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                      </svg>
                      Signing out...
                    </span>
                  ) : (
                    'Confirm Sign Out All'
                  )}
                </button>
                <button
                  type="button"
                  onClick={() => setShowRevokeAllConfirm(false)}
                  disabled={revokeAllLoading}
                  className="px-4 py-2 text-sm font-medium text-slate-300 bg-slate-700 rounded-lg hover:bg-slate-600 disabled:opacity-50 transition-colors"
                >
                  Cancel
                </button>
              </div>
            ) : (
              <button
                type="button"
                onClick={() => setShowRevokeAllConfirm(true)}
                className="px-4 py-2 text-sm font-medium text-red-400 bg-red-500/10 rounded-lg hover:bg-red-500/20 transition-colors"
              >
                Sign Out All Devices
              </button>
            )}
          </div>
        )}
      </div>

      {/* Error Message */}
      {error && (
        <div className="p-4 rounded-lg bg-red-500/10 border border-red-500/30">
          <div className="flex items-start gap-3">
            <svg className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div className="flex-1">
              <p className="text-sm text-red-400">{error}</p>
            </div>
            <button
              type="button"
              onClick={clearError}
              className="text-red-400 hover:text-red-300 transition-colors"
            >
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* Loading State */}
      {loading && (
        <div className="flex items-center justify-center py-12">
          <div className="flex flex-col items-center gap-3">
            <svg className="w-8 h-8 text-blue-500 animate-spin" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
            </svg>
            <p className="text-sm text-slate-400">Loading sessions...</p>
          </div>
        </div>
      )}

      {/* Sessions List */}
      {!loading && (
        <div className="space-y-3">
          {sortedSessions.length === 0 ? (
            <div className="text-center py-12">
              <svg className="w-12 h-12 mx-auto text-slate-600 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                  d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
              <p className="text-slate-400">No active sessions found</p>
            </div>
          ) : (
            sortedSessions.map((session) => (
              <DeviceCard
                key={session.id}
                session={session}
                isRevoking={revoking.has(session.id)}
                onRevoke={revokeSession}
              />
            ))
          )}
        </div>
      )}

      {/* Security Info */}
      {!loading && sessions.length > 0 && (
        <div className="mt-6 p-4 rounded-lg bg-blue-500/5 border border-blue-500/20">
          <div className="flex items-start gap-3">
            <svg className="w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div className="text-sm text-slate-400">
              <p className="font-medium text-slate-300 mb-1">Security Tip</p>
              <p>
                If you see a device or location you don&apos;t recognize, revoke that session immediately
                and change your password. Enable two-factor authentication for additional security.
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default SessionsList;
